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_EXECUTIONENGINE_EXECUTIONENGINE_H
16 #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
18 #include "llvm-c/ExecutionEngine.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/MC/MCCodeGenInfo.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
38 class ExecutionEngine;
42 class JITEventListener;
43 class JITMemoryManager;
44 class MachineCodeInfo;
48 class RTDyldMemoryManager;
52 /// \brief Helper class for helping synchronize access to the global address map
54 class ExecutionEngineState {
56 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
57 typedef ExecutionEngineState *ExtraData;
58 static sys::Mutex *getMutex(ExecutionEngineState *EES);
59 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
60 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
64 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
70 /// GlobalAddressMap - A mapping between LLVM global values and their
71 /// actualized version...
72 GlobalAddressMapTy GlobalAddressMap;
74 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
75 /// used to convert raw addresses into the LLVM global value that is emitted
76 /// at the address. This map is not computed unless getGlobalValueAtAddress
77 /// is called at some point.
78 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
81 ExecutionEngineState(ExecutionEngine &EE);
83 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
84 return GlobalAddressMap;
87 std::map<void*, AssertingVH<const GlobalValue> > &
88 getGlobalAddressReverseMap(const MutexGuard &) {
89 return GlobalAddressReverseMap;
92 /// \brief Erase an entry from the mapping table.
94 /// \returns The address that \p ToUnmap was happed to.
95 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
98 /// \brief Abstract interface for implementation execution of LLVM modules,
99 /// designed to support both interpreter and just-in-time (JIT) compiler
101 class ExecutionEngine {
102 /// The state object holding the global address mapping, which must be
103 /// accessed synchronously.
105 // FIXME: There is no particular need the entire map needs to be
106 // synchronized. Wouldn't a reader-writer design be better here?
107 ExecutionEngineState EEState;
109 /// The target data for the platform for which execution is being performed.
110 const DataLayout *TD;
112 /// Whether lazy JIT compilation is enabled.
113 bool CompilingLazily;
115 /// Whether JIT compilation of external global variables is allowed.
116 bool GVCompilationDisabled;
118 /// Whether the JIT should perform lookups of external symbols (e.g.,
120 bool SymbolSearchingDisabled;
122 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
125 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
126 /// optimize for the case where there is only one module.
127 SmallVector<Module*, 1> Modules;
129 void setDataLayout(const DataLayout *td) { TD = td; }
131 /// getMemoryforGV - Allocate memory for a global variable.
132 virtual char *getMemoryForGV(const GlobalVariable *GV);
134 // To avoid having libexecutionengine depend on the JIT and interpreter
135 // libraries, the execution engine implementations set these functions to ctor
136 // pointers at startup time if they are linked in.
137 static ExecutionEngine *(*JITCtor)(
139 std::string *ErrorStr,
140 JITMemoryManager *JMM,
143 static ExecutionEngine *(*MCJITCtor)(
145 std::string *ErrorStr,
146 RTDyldMemoryManager *MCJMM,
149 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
151 /// LazyFunctionCreator - If an unknown function is needed, this function
152 /// pointer is invoked to create it. If this returns null, the JIT will
154 void *(*LazyFunctionCreator)(const std::string &);
156 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
157 /// register dwarf tables with this function.
158 typedef void (*EERegisterFn)(void*);
159 EERegisterFn ExceptionTableRegister;
160 EERegisterFn ExceptionTableDeregister;
161 /// This maps functions to their exception tables frames.
162 DenseMap<const Function*, void*> AllExceptionTables;
166 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
167 /// JITEmitter classes. It must be held while changing the internal state of
168 /// any of those classes.
171 //===--------------------------------------------------------------------===//
172 // ExecutionEngine Startup
173 //===--------------------------------------------------------------------===//
175 virtual ~ExecutionEngine();
177 /// create - This is the factory method for creating an execution engine which
178 /// is appropriate for the current machine. This takes ownership of the
181 /// \param GVsWithCode - Allocating globals with code breaks
182 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
183 /// However, we have clients who depend on this behavior, so we must support
184 /// it. Eventually, when we're willing to break some backwards compatibility,
185 /// this flag should be flipped to false, so that by default
186 /// freeMachineCodeForFunction works.
187 static ExecutionEngine *create(Module *M,
188 bool ForceInterpreter = false,
189 std::string *ErrorStr = 0,
190 CodeGenOpt::Level OptLevel =
192 bool GVsWithCode = true);
194 /// createJIT - This is the factory method for creating a JIT for the current
195 /// machine, it does not fall back to the interpreter. This takes ownership
196 /// of the Module and JITMemoryManager if successful.
198 /// Clients should make sure to initialize targets prior to calling this
200 static ExecutionEngine *createJIT(Module *M,
201 std::string *ErrorStr = 0,
202 JITMemoryManager *JMM = 0,
203 CodeGenOpt::Level OptLevel =
205 bool GVsWithCode = true,
206 Reloc::Model RM = Reloc::Default,
207 CodeModel::Model CMM =
208 CodeModel::JITDefault);
210 /// addModule - Add a Module to the list of modules that we can JIT from.
211 /// Note that this takes ownership of the Module: when the ExecutionEngine is
212 /// destroyed, it destroys the Module as well.
213 virtual void addModule(Module *M) {
214 Modules.push_back(M);
217 //===--------------------------------------------------------------------===//
219 const DataLayout *getDataLayout() const { return TD; }
221 /// removeModule - Remove a Module from the list of modules. Returns true if
223 virtual bool removeModule(Module *M);
225 /// FindFunctionNamed - Search all of the active modules to find the one that
226 /// defines FnName. This is very slow operation and shouldn't be used for
228 Function *FindFunctionNamed(const char *FnName);
230 /// runFunction - Execute the specified function with the specified arguments,
231 /// and return the result.
232 virtual GenericValue runFunction(Function *F,
233 const std::vector<GenericValue> &ArgValues) = 0;
235 /// getPointerToNamedFunction - This method returns the address of the
236 /// specified function by using the dlsym function call. As such it is only
237 /// useful for resolving library symbols, not code generated symbols.
239 /// If AbortOnFailure is false and no function with the given name is
240 /// found, this function silently returns a null pointer. Otherwise,
241 /// it prints a message to stderr and aborts.
243 virtual void *getPointerToNamedFunction(const std::string &Name,
244 bool AbortOnFailure = true) = 0;
246 /// mapSectionAddress - map a section to its target address space value.
247 /// Map the address of a JIT section as returned from the memory manager
248 /// to the address in the target process as the running code will see it.
249 /// This is the address which will be used for relocation resolution.
250 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
251 llvm_unreachable("Re-mapping of section addresses not supported with this "
255 /// finalizeObject - ensure the module is fully processed and is usable.
257 /// It is the user-level function for completing the process of making the
258 /// object usable for execution. It should be called after sections within an
259 /// object have been relocated using mapSectionAddress. When this method is
260 /// called the MCJIT execution engine will reapply relocations for a loaded
261 /// object. This method has no effect for the legacy JIT engine or the
263 virtual void finalizeObject() {}
265 /// runStaticConstructorsDestructors - This method is used to execute all of
266 /// the static constructors or destructors for a program.
268 /// \param isDtors - Run the destructors instead of constructors.
269 void runStaticConstructorsDestructors(bool isDtors);
271 /// runStaticConstructorsDestructors - This method is used to execute all of
272 /// the static constructors or destructors for a particular module.
274 /// \param isDtors - Run the destructors instead of constructors.
275 void runStaticConstructorsDestructors(Module *module, bool isDtors);
278 /// runFunctionAsMain - This is a helper function which wraps runFunction to
279 /// handle the common task of starting up main with the specified argc, argv,
280 /// and envp parameters.
281 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
282 const char * const * envp);
285 /// addGlobalMapping - Tell the execution engine that the specified global is
286 /// at the specified location. This is used internally as functions are JIT'd
287 /// and as global variables are laid out in memory. It can and should also be
288 /// used by clients of the EE that want to have an LLVM global overlay
289 /// existing data in memory. Mappings are automatically removed when their
290 /// GlobalValue is destroyed.
291 void addGlobalMapping(const GlobalValue *GV, void *Addr);
293 /// clearAllGlobalMappings - Clear all global mappings and start over again,
294 /// for use in dynamic compilation scenarios to move globals.
295 void clearAllGlobalMappings();
297 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
298 /// particular module, because it has been removed from the JIT.
299 void clearGlobalMappingsFromModule(Module *M);
301 /// updateGlobalMapping - Replace an existing mapping for GV with a new
302 /// address. This updates both maps as required. If "Addr" is null, the
303 /// entry for the global is removed from the mappings. This returns the old
304 /// value of the pointer, or null if it was not in the map.
305 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
307 /// getPointerToGlobalIfAvailable - This returns the address of the specified
308 /// global value if it is has already been codegen'd, otherwise it returns
310 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
312 /// getPointerToGlobal - This returns the address of the specified global
313 /// value. This may involve code generation if it's a function.
314 void *getPointerToGlobal(const GlobalValue *GV);
316 /// getPointerToFunction - The different EE's represent function bodies in
317 /// different ways. They should each implement this to say what a function
318 /// pointer should look like. When F is destroyed, the ExecutionEngine will
319 /// remove its global mapping and free any machine code. Be sure no threads
320 /// are running inside F when that happens.
321 virtual void *getPointerToFunction(Function *F) = 0;
323 /// getPointerToBasicBlock - The different EE's represent basic blocks in
324 /// different ways. Return the representation for a blockaddress of the
326 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
328 /// getPointerToFunctionOrStub - If the specified function has been
329 /// code-gen'd, return a pointer to the function. If not, compile it, or use
330 /// a stub to implement lazy compilation if available. See
331 /// getPointerToFunction for the requirements on destroying F.
332 virtual void *getPointerToFunctionOrStub(Function *F) {
333 // Default implementation, just codegen the function.
334 return getPointerToFunction(F);
337 // The JIT overrides a version that actually does this.
338 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
340 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
341 /// at the specified address.
343 const GlobalValue *getGlobalValueAtAddress(void *Addr);
345 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
346 /// Ptr is the address of the memory at which to store Val, cast to
347 /// GenericValue *. It is not a pointer to a GenericValue containing the
348 /// address at which to store Val.
349 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
352 void InitializeMemory(const Constant *Init, void *Addr);
354 /// recompileAndRelinkFunction - This method is used to force a function which
355 /// has already been compiled to be compiled again, possibly after it has been
356 /// modified. Then the entry to the old copy is overwritten with a branch to
357 /// the new copy. If there was no old copy, this acts just like
358 /// VM::getPointerToFunction().
359 virtual void *recompileAndRelinkFunction(Function *F) = 0;
361 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
362 /// corresponding to the machine code emitted to execute this function, useful
363 /// for garbage-collecting generated code.
364 virtual void freeMachineCodeForFunction(Function *F) = 0;
366 /// getOrEmitGlobalVariable - Return the address of the specified global
367 /// variable, possibly emitting it to memory if needed. This is used by the
369 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
370 return getPointerToGlobal((const GlobalValue *)GV);
373 /// Registers a listener to be called back on various events within
374 /// the JIT. See JITEventListener.h for more details. Does not
375 /// take ownership of the argument. The argument may be NULL, in
376 /// which case these functions do nothing.
377 virtual void RegisterJITEventListener(JITEventListener *) {}
378 virtual void UnregisterJITEventListener(JITEventListener *) {}
380 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
381 /// not changed. Supported by MCJIT but not JIT.
382 virtual void setObjectCache(ObjectCache *) {
383 llvm_unreachable("No support for an object cache");
386 /// DisableLazyCompilation - When lazy compilation is off (the default), the
387 /// JIT will eagerly compile every function reachable from the argument to
388 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
389 /// compile the one function and emit stubs to compile the rest when they're
390 /// first called. If lazy compilation is turned off again while some lazy
391 /// stubs are still around, and one of those stubs is called, the program will
394 /// In order to safely compile lazily in a threaded program, the user must
395 /// ensure that 1) only one thread at a time can call any particular lazy
396 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
397 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
398 /// lazy stub. See http://llvm.org/PR5184 for details.
399 void DisableLazyCompilation(bool Disabled = true) {
400 CompilingLazily = !Disabled;
402 bool isCompilingLazily() const {
403 return CompilingLazily;
405 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
406 // Remove this in LLVM 2.8.
407 bool isLazyCompilationDisabled() const {
408 return !CompilingLazily;
411 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
412 /// allocate space and populate a GlobalVariable that is not internal to
414 void DisableGVCompilation(bool Disabled = true) {
415 GVCompilationDisabled = Disabled;
417 bool isGVCompilationDisabled() const {
418 return GVCompilationDisabled;
421 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
422 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
423 /// resolve symbols in a custom way.
424 void DisableSymbolSearching(bool Disabled = true) {
425 SymbolSearchingDisabled = Disabled;
427 bool isSymbolSearchingDisabled() const {
428 return SymbolSearchingDisabled;
431 /// InstallLazyFunctionCreator - If an unknown function is needed, the
432 /// specified function pointer is invoked to create it. If it returns null,
433 /// the JIT will abort.
434 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
435 LazyFunctionCreator = P;
438 /// InstallExceptionTableRegister - The JIT will use the given function
439 /// to register the exception tables it generates.
440 void InstallExceptionTableRegister(EERegisterFn F) {
441 ExceptionTableRegister = F;
443 void InstallExceptionTableDeregister(EERegisterFn F) {
444 ExceptionTableDeregister = F;
447 /// RegisterTable - Registers the given pointer as an exception table. It
448 /// uses the ExceptionTableRegister function.
449 void RegisterTable(const Function *fn, void* res) {
450 if (ExceptionTableRegister) {
451 ExceptionTableRegister(res);
452 AllExceptionTables[fn] = res;
456 /// DeregisterTable - Deregisters the exception frame previously registered
457 /// for the given function.
458 void DeregisterTable(const Function *Fn) {
459 if (ExceptionTableDeregister) {
460 DenseMap<const Function*, void*>::iterator frame =
461 AllExceptionTables.find(Fn);
462 if(frame != AllExceptionTables.end()) {
463 ExceptionTableDeregister(frame->second);
464 AllExceptionTables.erase(frame);
469 /// DeregisterAllTables - Deregisters all previously registered pointers to an
470 /// exception tables. It uses the ExceptionTableoDeregister function.
471 void DeregisterAllTables();
474 explicit ExecutionEngine(Module *M);
478 void EmitGlobalVariable(const GlobalVariable *GV);
480 GenericValue getConstantValue(const Constant *C);
481 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
485 namespace EngineKind {
486 // These are actually bitmasks that get or-ed together.
491 const static Kind Either = (Kind)(JIT | Interpreter);
494 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
495 /// stack-allocating a builder, chaining the various set* methods, and
496 /// terminating it with a .create() call.
497 class EngineBuilder {
500 EngineKind::Kind WhichEngine;
501 std::string *ErrorStr;
502 CodeGenOpt::Level OptLevel;
503 RTDyldMemoryManager *MCJMM;
504 JITMemoryManager *JMM;
505 bool AllocateGVsWithCode;
506 TargetOptions Options;
507 Reloc::Model RelocModel;
508 CodeModel::Model CMModel;
511 SmallVector<std::string, 4> MAttrs;
514 /// InitEngine - Does the common initialization of default options.
516 WhichEngine = EngineKind::Either;
518 OptLevel = CodeGenOpt::Default;
521 Options = TargetOptions();
522 AllocateGVsWithCode = false;
523 RelocModel = Reloc::Default;
524 CMModel = CodeModel::JITDefault;
529 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
530 /// is successful, the created engine takes ownership of the module.
531 EngineBuilder(Module *m) : M(m) {
535 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
536 /// or whichever engine works. This option defaults to EngineKind::Either.
537 EngineBuilder &setEngineKind(EngineKind::Kind w) {
542 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
543 /// clients to customize their memory allocation policies for the MCJIT. This
544 /// is only appropriate for the MCJIT; setting this and configuring the builder
545 /// to create anything other than MCJIT will cause a runtime error. If create()
546 /// is called and is successful, the created engine takes ownership of the
547 /// memory manager. This option defaults to NULL. Using this option nullifies
548 /// the setJITMemoryManager() option.
549 EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
555 /// setJITMemoryManager - Sets the JIT memory manager to use. This allows
556 /// clients to customize their memory allocation policies. This is only
557 /// appropriate for either JIT or MCJIT; setting this and configuring the
558 /// builder to create an interpreter will cause a runtime error. If create()
559 /// is called and is successful, the created engine takes ownership of the
560 /// memory manager. This option defaults to NULL. This option overrides
561 /// setMCJITMemoryManager() as well.
562 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
568 /// setErrorStr - Set the error string to write to on error. This option
569 /// defaults to NULL.
570 EngineBuilder &setErrorStr(std::string *e) {
575 /// setOptLevel - Set the optimization level for the JIT. This option
576 /// defaults to CodeGenOpt::Default.
577 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
582 /// setTargetOptions - Set the target options that the ExecutionEngine
583 /// target is using. Defaults to TargetOptions().
584 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
589 /// setRelocationModel - Set the relocation model that the ExecutionEngine
590 /// target is using. Defaults to target specific default "Reloc::Default".
591 EngineBuilder &setRelocationModel(Reloc::Model RM) {
596 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
597 /// data is using. Defaults to target specific default
598 /// "CodeModel::JITDefault".
599 EngineBuilder &setCodeModel(CodeModel::Model M) {
604 /// setAllocateGVsWithCode - Sets whether global values should be allocated
605 /// into the same buffer as code. For most applications this should be set
606 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
607 /// and is probably unsafe and bad for performance. However, we have clients
608 /// who depend on this behavior, so we must support it. This option defaults
609 /// to false so that users of the new API can safely use the new memory
610 /// manager and free machine code.
611 EngineBuilder &setAllocateGVsWithCode(bool a) {
612 AllocateGVsWithCode = a;
616 /// setMArch - Override the architecture set by the Module's triple.
617 EngineBuilder &setMArch(StringRef march) {
618 MArch.assign(march.begin(), march.end());
622 /// setMCPU - Target a specific cpu type.
623 EngineBuilder &setMCPU(StringRef mcpu) {
624 MCPU.assign(mcpu.begin(), mcpu.end());
628 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
630 EngineBuilder &setUseMCJIT(bool Value) {
635 /// setMAttrs - Set cpu-specific attributes.
636 template<typename StringSequence>
637 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
639 MAttrs.append(mattrs.begin(), mattrs.end());
643 TargetMachine *selectTarget();
645 /// selectTarget - Pick a target either via -march or by guessing the native
646 /// arch. Add any CPU features specified via -mcpu or -mattr.
647 TargetMachine *selectTarget(const Triple &TargetTriple,
650 const SmallVectorImpl<std::string>& MAttrs);
652 ExecutionEngine *create() {
653 return create(selectTarget());
656 ExecutionEngine *create(TargetMachine *TM);
659 // Create wrappers for C Binding types (see CBindingWrapping.h).
660 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
662 } // End llvm namespace