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/MC/MCCodeGenInfo.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/ValueMap.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
35 class ExecutionEngine;
39 class JITEventListener;
40 class JITMemoryManager;
41 class MachineCodeInfo;
48 /// \brief Helper class for helping synchronize access to the global address map
50 class ExecutionEngineState {
52 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
53 typedef ExecutionEngineState *ExtraData;
54 static sys::Mutex *getMutex(ExecutionEngineState *EES);
55 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
56 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
60 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
66 /// GlobalAddressMap - A mapping between LLVM global values and their
67 /// actualized version...
68 GlobalAddressMapTy GlobalAddressMap;
70 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
71 /// used to convert raw addresses into the LLVM global value that is emitted
72 /// at the address. This map is not computed unless getGlobalValueAtAddress
73 /// is called at some point.
74 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
77 ExecutionEngineState(ExecutionEngine &EE);
79 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
80 return GlobalAddressMap;
83 std::map<void*, AssertingVH<const GlobalValue> > &
84 getGlobalAddressReverseMap(const MutexGuard &) {
85 return GlobalAddressReverseMap;
88 /// \brief Erase an entry from the mapping table.
90 /// \returns The address that \arg ToUnmap was happed to.
91 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
94 /// \brief Abstract interface for implementation execution of LLVM modules,
95 /// designed to support both interpreter and just-in-time (JIT) compiler
97 class ExecutionEngine {
98 /// The state object holding the global address mapping, which must be
99 /// accessed synchronously.
101 // FIXME: There is no particular need the entire map needs to be
102 // synchronized. Wouldn't a reader-writer design be better here?
103 ExecutionEngineState EEState;
105 /// The target data for the platform for which execution is being performed.
106 const TargetData *TD;
108 /// Whether lazy JIT compilation is enabled.
109 bool CompilingLazily;
111 /// Whether JIT compilation of external global variables is allowed.
112 bool GVCompilationDisabled;
114 /// Whether the JIT should perform lookups of external symbols (e.g.,
116 bool SymbolSearchingDisabled;
118 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
121 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
122 /// optimize for the case where there is only one module.
123 SmallVector<Module*, 1> Modules;
125 void setTargetData(const TargetData *td) { TD = td; }
127 /// getMemoryforGV - Allocate memory for a global variable.
128 virtual char *getMemoryForGV(const GlobalVariable *GV);
130 // To avoid having libexecutionengine depend on the JIT and interpreter
131 // libraries, the execution engine implementations set these functions to ctor
132 // pointers at startup time if they are linked in.
133 static ExecutionEngine *(*JITCtor)(
135 std::string *ErrorStr,
136 JITMemoryManager *JMM,
139 static ExecutionEngine *(*MCJITCtor)(
141 std::string *ErrorStr,
142 JITMemoryManager *JMM,
145 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
147 /// LazyFunctionCreator - If an unknown function is needed, this function
148 /// pointer is invoked to create it. If this returns null, the JIT will
150 void *(*LazyFunctionCreator)(const std::string &);
152 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
153 /// register dwarf tables with this function.
154 typedef void (*EERegisterFn)(void*);
155 EERegisterFn ExceptionTableRegister;
156 EERegisterFn ExceptionTableDeregister;
157 /// This maps functions to their exception tables frames.
158 DenseMap<const Function*, void*> AllExceptionTables;
162 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
163 /// JITEmitter classes. It must be held while changing the internal state of
164 /// any of those classes.
167 //===--------------------------------------------------------------------===//
168 // ExecutionEngine Startup
169 //===--------------------------------------------------------------------===//
171 virtual ~ExecutionEngine();
173 /// create - This is the factory method for creating an execution engine which
174 /// is appropriate for the current machine. This takes ownership of the
177 /// \param GVsWithCode - Allocating globals with code breaks
178 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
179 /// However, we have clients who depend on this behavior, so we must support
180 /// it. Eventually, when we're willing to break some backwards compatibility,
181 /// this flag should be flipped to false, so that by default
182 /// freeMachineCodeForFunction works.
183 static ExecutionEngine *create(Module *M,
184 bool ForceInterpreter = false,
185 std::string *ErrorStr = 0,
186 CodeGenOpt::Level OptLevel =
188 bool GVsWithCode = true);
190 /// createJIT - This is the factory method for creating a JIT for the current
191 /// machine, it does not fall back to the interpreter. This takes ownership
192 /// of the Module and JITMemoryManager if successful.
194 /// Clients should make sure to initialize targets prior to calling this
196 static ExecutionEngine *createJIT(Module *M,
197 std::string *ErrorStr = 0,
198 JITMemoryManager *JMM = 0,
199 CodeGenOpt::Level OptLevel =
201 bool GVsWithCode = true,
202 Reloc::Model RM = Reloc::Default,
203 CodeModel::Model CMM =
204 CodeModel::JITDefault);
206 /// addModule - Add a Module to the list of modules that we can JIT from.
207 /// Note that this takes ownership of the Module: when the ExecutionEngine is
208 /// destroyed, it destroys the Module as well.
209 virtual void addModule(Module *M) {
210 Modules.push_back(M);
213 //===--------------------------------------------------------------------===//
215 const TargetData *getTargetData() const { return TD; }
217 /// removeModule - Remove a Module from the list of modules. Returns true if
219 virtual bool removeModule(Module *M);
221 /// FindFunctionNamed - Search all of the active modules to find the one that
222 /// defines FnName. This is very slow operation and shouldn't be used for
224 Function *FindFunctionNamed(const char *FnName);
226 /// runFunction - Execute the specified function with the specified arguments,
227 /// and return the result.
228 virtual GenericValue runFunction(Function *F,
229 const std::vector<GenericValue> &ArgValues) = 0;
231 /// runStaticConstructorsDestructors - This method is used to execute all of
232 /// the static constructors or destructors for a program.
234 /// \param isDtors - Run the destructors instead of constructors.
235 void runStaticConstructorsDestructors(bool isDtors);
237 /// runStaticConstructorsDestructors - This method is used to execute all of
238 /// the static constructors or destructors for a particular module.
240 /// \param isDtors - Run the destructors instead of constructors.
241 void runStaticConstructorsDestructors(Module *module, bool isDtors);
244 /// runFunctionAsMain - This is a helper function which wraps runFunction to
245 /// handle the common task of starting up main with the specified argc, argv,
246 /// and envp parameters.
247 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
248 const char * const * envp);
251 /// addGlobalMapping - Tell the execution engine that the specified global is
252 /// at the specified location. This is used internally as functions are JIT'd
253 /// and as global variables are laid out in memory. It can and should also be
254 /// used by clients of the EE that want to have an LLVM global overlay
255 /// existing data in memory. Mappings are automatically removed when their
256 /// GlobalValue is destroyed.
257 void addGlobalMapping(const GlobalValue *GV, void *Addr);
259 /// clearAllGlobalMappings - Clear all global mappings and start over again,
260 /// for use in dynamic compilation scenarios to move globals.
261 void clearAllGlobalMappings();
263 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
264 /// particular module, because it has been removed from the JIT.
265 void clearGlobalMappingsFromModule(Module *M);
267 /// updateGlobalMapping - Replace an existing mapping for GV with a new
268 /// address. This updates both maps as required. If "Addr" is null, the
269 /// entry for the global is removed from the mappings. This returns the old
270 /// value of the pointer, or null if it was not in the map.
271 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
273 /// getPointerToGlobalIfAvailable - This returns the address of the specified
274 /// global value if it is has already been codegen'd, otherwise it returns
276 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
278 /// getPointerToGlobal - This returns the address of the specified global
279 /// value. This may involve code generation if it's a function.
280 void *getPointerToGlobal(const GlobalValue *GV);
282 /// getPointerToFunction - The different EE's represent function bodies in
283 /// different ways. They should each implement this to say what a function
284 /// pointer should look like. When F is destroyed, the ExecutionEngine will
285 /// remove its global mapping and free any machine code. Be sure no threads
286 /// are running inside F when that happens.
287 virtual void *getPointerToFunction(Function *F) = 0;
289 /// getPointerToBasicBlock - The different EE's represent basic blocks in
290 /// different ways. Return the representation for a blockaddress of the
292 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
294 /// getPointerToFunctionOrStub - If the specified function has been
295 /// code-gen'd, return a pointer to the function. If not, compile it, or use
296 /// a stub to implement lazy compilation if available. See
297 /// getPointerToFunction for the requirements on destroying F.
298 virtual void *getPointerToFunctionOrStub(Function *F) {
299 // Default implementation, just codegen the function.
300 return getPointerToFunction(F);
303 // The JIT overrides a version that actually does this.
304 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
306 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
307 /// at the specified address.
309 const GlobalValue *getGlobalValueAtAddress(void *Addr);
311 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
312 /// Ptr is the address of the memory at which to store Val, cast to
313 /// GenericValue *. It is not a pointer to a GenericValue containing the
314 /// address at which to store Val.
315 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
318 void InitializeMemory(const Constant *Init, void *Addr);
320 /// recompileAndRelinkFunction - This method is used to force a function which
321 /// has already been compiled to be compiled again, possibly after it has been
322 /// modified. Then the entry to the old copy is overwritten with a branch to
323 /// the new copy. If there was no old copy, this acts just like
324 /// VM::getPointerToFunction().
325 virtual void *recompileAndRelinkFunction(Function *F) = 0;
327 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
328 /// corresponding to the machine code emitted to execute this function, useful
329 /// for garbage-collecting generated code.
330 virtual void freeMachineCodeForFunction(Function *F) = 0;
332 /// getOrEmitGlobalVariable - Return the address of the specified global
333 /// variable, possibly emitting it to memory if needed. This is used by the
335 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
336 return getPointerToGlobal((GlobalValue*)GV);
339 /// Registers a listener to be called back on various events within
340 /// the JIT. See JITEventListener.h for more details. Does not
341 /// take ownership of the argument. The argument may be NULL, in
342 /// which case these functions do nothing.
343 virtual void RegisterJITEventListener(JITEventListener *) {}
344 virtual void UnregisterJITEventListener(JITEventListener *) {}
346 /// DisableLazyCompilation - When lazy compilation is off (the default), the
347 /// JIT will eagerly compile every function reachable from the argument to
348 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
349 /// compile the one function and emit stubs to compile the rest when they're
350 /// first called. If lazy compilation is turned off again while some lazy
351 /// stubs are still around, and one of those stubs is called, the program will
354 /// In order to safely compile lazily in a threaded program, the user must
355 /// ensure that 1) only one thread at a time can call any particular lazy
356 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
357 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
358 /// lazy stub. See http://llvm.org/PR5184 for details.
359 void DisableLazyCompilation(bool Disabled = true) {
360 CompilingLazily = !Disabled;
362 bool isCompilingLazily() const {
363 return CompilingLazily;
365 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
366 // Remove this in LLVM 2.8.
367 bool isLazyCompilationDisabled() const {
368 return !CompilingLazily;
371 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
372 /// allocate space and populate a GlobalVariable that is not internal to
374 void DisableGVCompilation(bool Disabled = true) {
375 GVCompilationDisabled = Disabled;
377 bool isGVCompilationDisabled() const {
378 return GVCompilationDisabled;
381 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
382 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
383 /// resolve symbols in a custom way.
384 void DisableSymbolSearching(bool Disabled = true) {
385 SymbolSearchingDisabled = Disabled;
387 bool isSymbolSearchingDisabled() const {
388 return SymbolSearchingDisabled;
391 /// InstallLazyFunctionCreator - If an unknown function is needed, the
392 /// specified function pointer is invoked to create it. If it returns null,
393 /// the JIT will abort.
394 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
395 LazyFunctionCreator = P;
398 /// InstallExceptionTableRegister - The JIT will use the given function
399 /// to register the exception tables it generates.
400 void InstallExceptionTableRegister(EERegisterFn F) {
401 ExceptionTableRegister = F;
403 void InstallExceptionTableDeregister(EERegisterFn F) {
404 ExceptionTableDeregister = F;
407 /// RegisterTable - Registers the given pointer as an exception table. It
408 /// uses the ExceptionTableRegister function.
409 void RegisterTable(const Function *fn, void* res) {
410 if (ExceptionTableRegister) {
411 ExceptionTableRegister(res);
412 AllExceptionTables[fn] = res;
416 /// DeregisterTable - Deregisters the exception frame previously registered
417 /// for the given function.
418 void DeregisterTable(const Function *Fn) {
419 if (ExceptionTableDeregister) {
420 DenseMap<const Function*, void*>::iterator frame =
421 AllExceptionTables.find(Fn);
422 if(frame != AllExceptionTables.end()) {
423 ExceptionTableDeregister(frame->second);
424 AllExceptionTables.erase(frame);
429 /// DeregisterAllTables - Deregisters all previously registered pointers to an
430 /// exception tables. It uses the ExceptionTableoDeregister function.
431 void DeregisterAllTables();
434 explicit ExecutionEngine(Module *M);
438 void EmitGlobalVariable(const GlobalVariable *GV);
440 GenericValue getConstantValue(const Constant *C);
441 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
445 namespace EngineKind {
446 // These are actually bitmasks that get or-ed together.
451 const static Kind Either = (Kind)(JIT | Interpreter);
454 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
455 /// stack-allocating a builder, chaining the various set* methods, and
456 /// terminating it with a .create() call.
457 class EngineBuilder {
460 EngineKind::Kind WhichEngine;
461 std::string *ErrorStr;
462 CodeGenOpt::Level OptLevel;
463 JITMemoryManager *JMM;
464 bool AllocateGVsWithCode;
465 TargetOptions Options;
466 Reloc::Model RelocModel;
467 CodeModel::Model CMModel;
470 SmallVector<std::string, 4> MAttrs;
473 /// InitEngine - Does the common initialization of default options.
475 WhichEngine = EngineKind::Either;
477 OptLevel = CodeGenOpt::Default;
479 Options = TargetOptions();
480 AllocateGVsWithCode = false;
481 RelocModel = Reloc::Default;
482 CMModel = CodeModel::JITDefault;
487 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
488 /// is successful, the created engine takes ownership of the module.
489 EngineBuilder(Module *m) : M(m) {
493 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
494 /// or whichever engine works. This option defaults to EngineKind::Either.
495 EngineBuilder &setEngineKind(EngineKind::Kind w) {
500 /// setJITMemoryManager - Sets the memory manager to use. This allows
501 /// clients to customize their memory allocation policies. If create() is
502 /// called and is successful, the created engine takes ownership of the
503 /// memory manager. This option defaults to NULL.
504 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
509 /// setErrorStr - Set the error string to write to on error. This option
510 /// defaults to NULL.
511 EngineBuilder &setErrorStr(std::string *e) {
516 /// setOptLevel - Set the optimization level for the JIT. This option
517 /// defaults to CodeGenOpt::Default.
518 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
523 /// setTargetOptions - Set the target options that the ExecutionEngine
524 /// target is using. Defaults to TargetOptions().
525 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
530 /// setRelocationModel - Set the relocation model that the ExecutionEngine
531 /// target is using. Defaults to target specific default "Reloc::Default".
532 EngineBuilder &setRelocationModel(Reloc::Model RM) {
537 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
538 /// data is using. Defaults to target specific default
539 /// "CodeModel::JITDefault".
540 EngineBuilder &setCodeModel(CodeModel::Model M) {
545 /// setAllocateGVsWithCode - Sets whether global values should be allocated
546 /// into the same buffer as code. For most applications this should be set
547 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
548 /// and is probably unsafe and bad for performance. However, we have clients
549 /// who depend on this behavior, so we must support it. This option defaults
550 /// to false so that users of the new API can safely use the new memory
551 /// manager and free machine code.
552 EngineBuilder &setAllocateGVsWithCode(bool a) {
553 AllocateGVsWithCode = a;
557 /// setMArch - Override the architecture set by the Module's triple.
558 EngineBuilder &setMArch(StringRef march) {
559 MArch.assign(march.begin(), march.end());
563 /// setMCPU - Target a specific cpu type.
564 EngineBuilder &setMCPU(StringRef mcpu) {
565 MCPU.assign(mcpu.begin(), mcpu.end());
569 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
571 EngineBuilder &setUseMCJIT(bool Value) {
576 /// setMAttrs - Set cpu-specific attributes.
577 template<typename StringSequence>
578 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
580 MAttrs.append(mattrs.begin(), mattrs.end());
584 /// selectTarget - Pick a target either via -march or by guessing the native
585 /// arch. Add any CPU features specified via -mcpu or -mattr.
586 static TargetMachine *selectTarget(const Triple &TargetTriple,
589 const SmallVectorImpl<std::string>& MAttrs,
590 const TargetOptions &Options,
593 CodeGenOpt::Level OL,
596 ExecutionEngine *create();
599 } // End llvm namespace