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/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/MC/MCCodeGenInfo.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
36 class ExecutionEngine;
40 class JITEventListener;
41 class JITMemoryManager;
42 class MachineCodeInfo;
50 /// \brief Helper class for helping synchronize access to the global address map
52 class ExecutionEngineState {
54 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
55 typedef ExecutionEngineState *ExtraData;
56 static sys::Mutex *getMutex(ExecutionEngineState *EES);
57 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
58 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
62 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
68 /// GlobalAddressMap - A mapping between LLVM global values and their
69 /// actualized version...
70 GlobalAddressMapTy GlobalAddressMap;
72 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
73 /// used to convert raw addresses into the LLVM global value that is emitted
74 /// at the address. This map is not computed unless getGlobalValueAtAddress
75 /// is called at some point.
76 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
79 ExecutionEngineState(ExecutionEngine &EE);
81 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
82 return GlobalAddressMap;
85 std::map<void*, AssertingVH<const GlobalValue> > &
86 getGlobalAddressReverseMap(const MutexGuard &) {
87 return GlobalAddressReverseMap;
90 /// \brief Erase an entry from the mapping table.
92 /// \returns The address that \p ToUnmap was happed to.
93 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
96 /// \brief Abstract interface for implementation execution of LLVM modules,
97 /// designed to support both interpreter and just-in-time (JIT) compiler
99 class ExecutionEngine {
100 /// The state object holding the global address mapping, which must be
101 /// accessed synchronously.
103 // FIXME: There is no particular need the entire map needs to be
104 // synchronized. Wouldn't a reader-writer design be better here?
105 ExecutionEngineState EEState;
107 /// The target data for the platform for which execution is being performed.
108 const DataLayout *TD;
110 /// Whether lazy JIT compilation is enabled.
111 bool CompilingLazily;
113 /// Whether JIT compilation of external global variables is allowed.
114 bool GVCompilationDisabled;
116 /// Whether the JIT should perform lookups of external symbols (e.g.,
118 bool SymbolSearchingDisabled;
120 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
123 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
124 /// optimize for the case where there is only one module.
125 SmallVector<Module*, 1> Modules;
127 void setDataLayout(const DataLayout *td) { TD = td; }
129 /// getMemoryforGV - Allocate memory for a global variable.
130 virtual char *getMemoryForGV(const GlobalVariable *GV);
132 // To avoid having libexecutionengine depend on the JIT and interpreter
133 // libraries, the execution engine implementations set these functions to ctor
134 // pointers at startup time if they are linked in.
135 static ExecutionEngine *(*JITCtor)(
137 std::string *ErrorStr,
138 JITMemoryManager *JMM,
141 static ExecutionEngine *(*MCJITCtor)(
143 std::string *ErrorStr,
144 JITMemoryManager *JMM,
147 static ExecutionEngine *(*InterpCtor)(Module *M, 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 Reloc::Model RM = Reloc::Default,
205 CodeModel::Model CMM =
206 CodeModel::JITDefault);
208 /// addModule - Add a Module to the list of modules that we can JIT from.
209 /// Note that this takes ownership of the Module: when the ExecutionEngine is
210 /// destroyed, it destroys the Module as well.
211 virtual void addModule(Module *M) {
212 Modules.push_back(M);
215 //===--------------------------------------------------------------------===//
217 const DataLayout *getDataLayout() const { return TD; }
219 /// removeModule - Remove a Module from the list of modules. Returns true if
221 virtual bool removeModule(Module *M);
223 /// FindFunctionNamed - Search all of the active modules to find the one that
224 /// defines FnName. This is very slow operation and shouldn't be used for
226 Function *FindFunctionNamed(const char *FnName);
228 /// runFunction - Execute the specified function with the specified arguments,
229 /// and return the result.
230 virtual GenericValue runFunction(Function *F,
231 const std::vector<GenericValue> &ArgValues) = 0;
233 /// getPointerToNamedFunction - This method returns the address of the
234 /// specified function by using the dlsym function call. As such it is only
235 /// useful for resolving library symbols, not code generated symbols.
237 /// If AbortOnFailure is false and no function with the given name is
238 /// found, this function silently returns a null pointer. Otherwise,
239 /// it prints a message to stderr and aborts.
241 virtual void *getPointerToNamedFunction(const std::string &Name,
242 bool AbortOnFailure = true) = 0;
244 /// mapSectionAddress - map a section to its target address space value.
245 /// Map the address of a JIT section as returned from the memory manager
246 /// to the address in the target process as the running code will see it.
247 /// This is the address which will be used for relocation resolution.
248 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
249 llvm_unreachable("Re-mapping of section addresses not supported with this "
253 // finalizeObject - This method should be called after sections within an
254 // object have been relocated using mapSectionAddress. When this method is
255 // called the MCJIT execution engine will reapply relocations for a loaded
256 // object. This method has no effect for the legacy JIT engine or the
258 virtual void finalizeObject() {}
260 /// runStaticConstructorsDestructors - This method is used to execute all of
261 /// the static constructors or destructors for a program.
263 /// \param isDtors - Run the destructors instead of constructors.
264 void runStaticConstructorsDestructors(bool isDtors);
266 /// runStaticConstructorsDestructors - This method is used to execute all of
267 /// the static constructors or destructors for a particular module.
269 /// \param isDtors - Run the destructors instead of constructors.
270 void runStaticConstructorsDestructors(Module *module, bool isDtors);
273 /// runFunctionAsMain - This is a helper function which wraps runFunction to
274 /// handle the common task of starting up main with the specified argc, argv,
275 /// and envp parameters.
276 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
277 const char * const * envp);
280 /// addGlobalMapping - Tell the execution engine that the specified global is
281 /// at the specified location. This is used internally as functions are JIT'd
282 /// and as global variables are laid out in memory. It can and should also be
283 /// used by clients of the EE that want to have an LLVM global overlay
284 /// existing data in memory. Mappings are automatically removed when their
285 /// GlobalValue is destroyed.
286 void addGlobalMapping(const GlobalValue *GV, void *Addr);
288 /// clearAllGlobalMappings - Clear all global mappings and start over again,
289 /// for use in dynamic compilation scenarios to move globals.
290 void clearAllGlobalMappings();
292 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
293 /// particular module, because it has been removed from the JIT.
294 void clearGlobalMappingsFromModule(Module *M);
296 /// updateGlobalMapping - Replace an existing mapping for GV with a new
297 /// address. This updates both maps as required. If "Addr" is null, the
298 /// entry for the global is removed from the mappings. This returns the old
299 /// value of the pointer, or null if it was not in the map.
300 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
302 /// getPointerToGlobalIfAvailable - This returns the address of the specified
303 /// global value if it is has already been codegen'd, otherwise it returns
305 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
307 /// getPointerToGlobal - This returns the address of the specified global
308 /// value. This may involve code generation if it's a function.
309 void *getPointerToGlobal(const GlobalValue *GV);
311 /// getPointerToFunction - The different EE's represent function bodies in
312 /// different ways. They should each implement this to say what a function
313 /// pointer should look like. When F is destroyed, the ExecutionEngine will
314 /// remove its global mapping and free any machine code. Be sure no threads
315 /// are running inside F when that happens.
316 virtual void *getPointerToFunction(Function *F) = 0;
318 /// getPointerToBasicBlock - The different EE's represent basic blocks in
319 /// different ways. Return the representation for a blockaddress of the
321 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
323 /// getPointerToFunctionOrStub - If the specified function has been
324 /// code-gen'd, return a pointer to the function. If not, compile it, or use
325 /// a stub to implement lazy compilation if available. See
326 /// getPointerToFunction for the requirements on destroying F.
327 virtual void *getPointerToFunctionOrStub(Function *F) {
328 // Default implementation, just codegen the function.
329 return getPointerToFunction(F);
332 // The JIT overrides a version that actually does this.
333 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
335 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
336 /// at the specified address.
338 const GlobalValue *getGlobalValueAtAddress(void *Addr);
340 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
341 /// Ptr is the address of the memory at which to store Val, cast to
342 /// GenericValue *. It is not a pointer to a GenericValue containing the
343 /// address at which to store Val.
344 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
347 void InitializeMemory(const Constant *Init, void *Addr);
349 /// recompileAndRelinkFunction - This method is used to force a function which
350 /// has already been compiled to be compiled again, possibly after it has been
351 /// modified. Then the entry to the old copy is overwritten with a branch to
352 /// the new copy. If there was no old copy, this acts just like
353 /// VM::getPointerToFunction().
354 virtual void *recompileAndRelinkFunction(Function *F) = 0;
356 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
357 /// corresponding to the machine code emitted to execute this function, useful
358 /// for garbage-collecting generated code.
359 virtual void freeMachineCodeForFunction(Function *F) = 0;
361 /// getOrEmitGlobalVariable - Return the address of the specified global
362 /// variable, possibly emitting it to memory if needed. This is used by the
364 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
365 return getPointerToGlobal((const GlobalValue *)GV);
368 /// Registers a listener to be called back on various events within
369 /// the JIT. See JITEventListener.h for more details. Does not
370 /// take ownership of the argument. The argument may be NULL, in
371 /// which case these functions do nothing.
372 virtual void RegisterJITEventListener(JITEventListener *) {}
373 virtual void UnregisterJITEventListener(JITEventListener *) {}
375 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
376 /// not changed. Supported by MCJIT by not JIT.
377 virtual void setObjectCache(ObjectCache *) {
378 llvm_unreachable("No support for an object cache");
381 /// DisableLazyCompilation - When lazy compilation is off (the default), the
382 /// JIT will eagerly compile every function reachable from the argument to
383 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
384 /// compile the one function and emit stubs to compile the rest when they're
385 /// first called. If lazy compilation is turned off again while some lazy
386 /// stubs are still around, and one of those stubs is called, the program will
389 /// In order to safely compile lazily in a threaded program, the user must
390 /// ensure that 1) only one thread at a time can call any particular lazy
391 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
392 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
393 /// lazy stub. See http://llvm.org/PR5184 for details.
394 void DisableLazyCompilation(bool Disabled = true) {
395 CompilingLazily = !Disabled;
397 bool isCompilingLazily() const {
398 return CompilingLazily;
400 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
401 // Remove this in LLVM 2.8.
402 bool isLazyCompilationDisabled() const {
403 return !CompilingLazily;
406 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
407 /// allocate space and populate a GlobalVariable that is not internal to
409 void DisableGVCompilation(bool Disabled = true) {
410 GVCompilationDisabled = Disabled;
412 bool isGVCompilationDisabled() const {
413 return GVCompilationDisabled;
416 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
417 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
418 /// resolve symbols in a custom way.
419 void DisableSymbolSearching(bool Disabled = true) {
420 SymbolSearchingDisabled = Disabled;
422 bool isSymbolSearchingDisabled() const {
423 return SymbolSearchingDisabled;
426 /// InstallLazyFunctionCreator - If an unknown function is needed, the
427 /// specified function pointer is invoked to create it. If it returns null,
428 /// the JIT will abort.
429 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
430 LazyFunctionCreator = P;
433 /// InstallExceptionTableRegister - The JIT will use the given function
434 /// to register the exception tables it generates.
435 void InstallExceptionTableRegister(EERegisterFn F) {
436 ExceptionTableRegister = F;
438 void InstallExceptionTableDeregister(EERegisterFn F) {
439 ExceptionTableDeregister = F;
442 /// RegisterTable - Registers the given pointer as an exception table. It
443 /// uses the ExceptionTableRegister function.
444 void RegisterTable(const Function *fn, void* res) {
445 if (ExceptionTableRegister) {
446 ExceptionTableRegister(res);
447 AllExceptionTables[fn] = res;
451 /// DeregisterTable - Deregisters the exception frame previously registered
452 /// for the given function.
453 void DeregisterTable(const Function *Fn) {
454 if (ExceptionTableDeregister) {
455 DenseMap<const Function*, void*>::iterator frame =
456 AllExceptionTables.find(Fn);
457 if(frame != AllExceptionTables.end()) {
458 ExceptionTableDeregister(frame->second);
459 AllExceptionTables.erase(frame);
464 /// DeregisterAllTables - Deregisters all previously registered pointers to an
465 /// exception tables. It uses the ExceptionTableoDeregister function.
466 void DeregisterAllTables();
469 explicit ExecutionEngine(Module *M);
473 void EmitGlobalVariable(const GlobalVariable *GV);
475 GenericValue getConstantValue(const Constant *C);
476 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
480 namespace EngineKind {
481 // These are actually bitmasks that get or-ed together.
486 const static Kind Either = (Kind)(JIT | Interpreter);
489 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
490 /// stack-allocating a builder, chaining the various set* methods, and
491 /// terminating it with a .create() call.
492 class EngineBuilder {
495 EngineKind::Kind WhichEngine;
496 std::string *ErrorStr;
497 CodeGenOpt::Level OptLevel;
498 JITMemoryManager *JMM;
499 bool AllocateGVsWithCode;
500 TargetOptions Options;
501 Reloc::Model RelocModel;
502 CodeModel::Model CMModel;
505 SmallVector<std::string, 4> MAttrs;
508 /// InitEngine - Does the common initialization of default options.
510 WhichEngine = EngineKind::Either;
512 OptLevel = CodeGenOpt::Default;
514 Options = TargetOptions();
515 AllocateGVsWithCode = false;
516 RelocModel = Reloc::Default;
517 CMModel = CodeModel::JITDefault;
522 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
523 /// is successful, the created engine takes ownership of the module.
524 EngineBuilder(Module *m) : M(m) {
528 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
529 /// or whichever engine works. This option defaults to EngineKind::Either.
530 EngineBuilder &setEngineKind(EngineKind::Kind w) {
535 /// setJITMemoryManager - Sets the memory manager to use. This allows
536 /// clients to customize their memory allocation policies. If create() is
537 /// called and is successful, the created engine takes ownership of the
538 /// memory manager. This option defaults to NULL.
539 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
544 /// setErrorStr - Set the error string to write to on error. This option
545 /// defaults to NULL.
546 EngineBuilder &setErrorStr(std::string *e) {
551 /// setOptLevel - Set the optimization level for the JIT. This option
552 /// defaults to CodeGenOpt::Default.
553 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
558 /// setTargetOptions - Set the target options that the ExecutionEngine
559 /// target is using. Defaults to TargetOptions().
560 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
565 /// setRelocationModel - Set the relocation model that the ExecutionEngine
566 /// target is using. Defaults to target specific default "Reloc::Default".
567 EngineBuilder &setRelocationModel(Reloc::Model RM) {
572 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
573 /// data is using. Defaults to target specific default
574 /// "CodeModel::JITDefault".
575 EngineBuilder &setCodeModel(CodeModel::Model M) {
580 /// setAllocateGVsWithCode - Sets whether global values should be allocated
581 /// into the same buffer as code. For most applications this should be set
582 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
583 /// and is probably unsafe and bad for performance. However, we have clients
584 /// who depend on this behavior, so we must support it. This option defaults
585 /// to false so that users of the new API can safely use the new memory
586 /// manager and free machine code.
587 EngineBuilder &setAllocateGVsWithCode(bool a) {
588 AllocateGVsWithCode = a;
592 /// setMArch - Override the architecture set by the Module's triple.
593 EngineBuilder &setMArch(StringRef march) {
594 MArch.assign(march.begin(), march.end());
598 /// setMCPU - Target a specific cpu type.
599 EngineBuilder &setMCPU(StringRef mcpu) {
600 MCPU.assign(mcpu.begin(), mcpu.end());
604 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
606 EngineBuilder &setUseMCJIT(bool Value) {
611 /// setMAttrs - Set cpu-specific attributes.
612 template<typename StringSequence>
613 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
615 MAttrs.append(mattrs.begin(), mattrs.end());
619 TargetMachine *selectTarget();
621 /// selectTarget - Pick a target either via -march or by guessing the native
622 /// arch. Add any CPU features specified via -mcpu or -mattr.
623 TargetMachine *selectTarget(const Triple &TargetTriple,
626 const SmallVectorImpl<std::string>& MAttrs);
628 ExecutionEngine *create() {
629 return create(selectTarget());
632 ExecutionEngine *create(TargetMachine *TM);
635 } // End llvm namespace