ExecutionEngine.h revision 210299
1//===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the abstract interface that implements execution support
11// for LLVM.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_EXECUTION_ENGINE_H
16#define LLVM_EXECUTION_ENGINE_H
17
18#include <vector>
19#include <map>
20#include <string>
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"
27
28namespace llvm {
29
30struct GenericValue;
31class Constant;
32class ExecutionEngine;
33class Function;
34class GlobalVariable;
35class GlobalValue;
36class JITEventListener;
37class JITMemoryManager;
38class MachineCodeInfo;
39class Module;
40class MutexGuard;
41class TargetData;
42class Type;
43
44class ExecutionEngineState {
45public:
46  struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
47    typedef ExecutionEngineState *ExtraData;
48    static sys::Mutex *getMutex(ExecutionEngineState *EES);
49    static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
50    static void onRAUW(ExecutionEngineState *, const GlobalValue *,
51                       const GlobalValue *);
52  };
53
54  typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
55      GlobalAddressMapTy;
56
57private:
58  ExecutionEngine &EE;
59
60  /// GlobalAddressMap - A mapping between LLVM global values and their
61  /// actualized version...
62  GlobalAddressMapTy GlobalAddressMap;
63
64  /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
65  /// used to convert raw addresses into the LLVM global value that is emitted
66  /// at the address.  This map is not computed unless getGlobalValueAtAddress
67  /// is called at some point.
68  std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
69
70public:
71  ExecutionEngineState(ExecutionEngine &EE);
72
73  GlobalAddressMapTy &
74  getGlobalAddressMap(const MutexGuard &) {
75    return GlobalAddressMap;
76  }
77
78  std::map<void*, AssertingVH<const GlobalValue> > &
79  getGlobalAddressReverseMap(const MutexGuard &) {
80    return GlobalAddressReverseMap;
81  }
82
83  // Returns the address ToUnmap was mapped to.
84  void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
85};
86
87
88class ExecutionEngine {
89  const TargetData *TD;
90  ExecutionEngineState EEState;
91  bool CompilingLazily;
92  bool GVCompilationDisabled;
93  bool SymbolSearchingDisabled;
94
95  friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
96
97protected:
98  /// Modules - This is a list of Modules that we are JIT'ing from.  We use a
99  /// smallvector to optimize for the case where there is only one module.
100  SmallVector<Module*, 1> Modules;
101
102  void setTargetData(const TargetData *td) {
103    TD = td;
104  }
105
106  /// getMemoryforGV - Allocate memory for a global variable.
107  virtual char* getMemoryForGV(const GlobalVariable* GV);
108
109  // To avoid having libexecutionengine depend on the JIT and interpreter
110  // libraries, the JIT and Interpreter set these functions to ctor pointers
111  // at startup time if they are linked in.
112  static ExecutionEngine *(*JITCtor)(
113    Module *M,
114    std::string *ErrorStr,
115    JITMemoryManager *JMM,
116    CodeGenOpt::Level OptLevel,
117    bool GVsWithCode,
118    CodeModel::Model CMM,
119    StringRef MArch,
120    StringRef MCPU,
121    const SmallVectorImpl<std::string>& MAttrs);
122  static ExecutionEngine *(*InterpCtor)(Module *M,
123                                        std::string *ErrorStr);
124
125  /// LazyFunctionCreator - If an unknown function is needed, this function
126  /// pointer is invoked to create it. If this returns null, the JIT will abort.
127  void* (*LazyFunctionCreator)(const std::string &);
128
129  /// ExceptionTableRegister - If Exception Handling is set, the JIT will
130  /// register dwarf tables with this function
131  typedef void (*EERegisterFn)(void*);
132  static EERegisterFn ExceptionTableRegister;
133
134public:
135  /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
136  /// JITEmitter classes.  It must be held while changing the internal state of
137  /// any of those classes.
138  sys::Mutex lock; // Used to make this class and subclasses thread-safe
139
140  //===--------------------------------------------------------------------===//
141  //  ExecutionEngine Startup
142  //===--------------------------------------------------------------------===//
143
144  virtual ~ExecutionEngine();
145
146  /// create - This is the factory method for creating an execution engine which
147  /// is appropriate for the current machine.  This takes ownership of the
148  /// module.
149  static ExecutionEngine *create(Module *M,
150                                 bool ForceInterpreter = false,
151                                 std::string *ErrorStr = 0,
152                                 CodeGenOpt::Level OptLevel =
153                                   CodeGenOpt::Default,
154                                 // Allocating globals with code breaks
155                                 // freeMachineCodeForFunction and is probably
156                                 // unsafe and bad for performance.  However,
157                                 // we have clients who depend on this
158                                 // behavior, so we must support it.
159                                 // Eventually, when we're willing to break
160                                 // some backwards compatability, this flag
161                                 // should be flipped to false, so that by
162                                 // default freeMachineCodeForFunction works.
163                                 bool GVsWithCode = true);
164
165  /// createJIT - This is the factory method for creating a JIT for the current
166  /// machine, it does not fall back to the interpreter.  This takes ownership
167  /// of the Module and JITMemoryManager if successful.
168  ///
169  /// Clients should make sure to initialize targets prior to calling this
170  /// function.
171  static ExecutionEngine *createJIT(Module *M,
172                                    std::string *ErrorStr = 0,
173                                    JITMemoryManager *JMM = 0,
174                                    CodeGenOpt::Level OptLevel =
175                                      CodeGenOpt::Default,
176                                    bool GVsWithCode = true,
177                                    CodeModel::Model CMM =
178                                      CodeModel::Default);
179
180  /// addModule - Add a Module to the list of modules that we can JIT from.
181  /// Note that this takes ownership of the Module: when the ExecutionEngine is
182  /// destroyed, it destroys the Module as well.
183  virtual void addModule(Module *M) {
184    Modules.push_back(M);
185  }
186
187  //===----------------------------------------------------------------------===//
188
189  const TargetData *getTargetData() const { return TD; }
190
191
192  /// removeModule - Remove a Module from the list of modules.  Returns true if
193  /// M is found.
194  virtual bool removeModule(Module *M);
195
196  /// FindFunctionNamed - Search all of the active modules to find the one that
197  /// defines FnName.  This is very slow operation and shouldn't be used for
198  /// general code.
199  Function *FindFunctionNamed(const char *FnName);
200
201  /// runFunction - Execute the specified function with the specified arguments,
202  /// and return the result.
203  ///
204  virtual GenericValue runFunction(Function *F,
205                                const std::vector<GenericValue> &ArgValues) = 0;
206
207  /// runStaticConstructorsDestructors - This method is used to execute all of
208  /// the static constructors or destructors for a program, depending on the
209  /// value of isDtors.
210  void runStaticConstructorsDestructors(bool isDtors);
211  /// runStaticConstructorsDestructors - This method is used to execute all of
212  /// the static constructors or destructors for a module, depending on the
213  /// value of isDtors.
214  void runStaticConstructorsDestructors(Module *module, bool isDtors);
215
216
217  /// runFunctionAsMain - This is a helper function which wraps runFunction to
218  /// handle the common task of starting up main with the specified argc, argv,
219  /// and envp parameters.
220  int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
221                        const char * const * envp);
222
223
224  /// addGlobalMapping - Tell the execution engine that the specified global is
225  /// at the specified location.  This is used internally as functions are JIT'd
226  /// and as global variables are laid out in memory.  It can and should also be
227  /// used by clients of the EE that want to have an LLVM global overlay
228  /// existing data in memory.  Mappings are automatically removed when their
229  /// GlobalValue is destroyed.
230  void addGlobalMapping(const GlobalValue *GV, void *Addr);
231
232  /// clearAllGlobalMappings - Clear all global mappings and start over again
233  /// use in dynamic compilation scenarios when you want to move globals
234  void clearAllGlobalMappings();
235
236  /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
237  /// particular module, because it has been removed from the JIT.
238  void clearGlobalMappingsFromModule(Module *M);
239
240  /// updateGlobalMapping - Replace an existing mapping for GV with a new
241  /// address.  This updates both maps as required.  If "Addr" is null, the
242  /// entry for the global is removed from the mappings.  This returns the old
243  /// value of the pointer, or null if it was not in the map.
244  void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
245
246  /// getPointerToGlobalIfAvailable - This returns the address of the specified
247  /// global value if it is has already been codegen'd, otherwise it returns
248  /// null.
249  ///
250  void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
251
252  /// getPointerToGlobal - This returns the address of the specified global
253  /// value.  This may involve code generation if it's a function.
254  ///
255  void *getPointerToGlobal(const GlobalValue *GV);
256
257  /// getPointerToFunction - The different EE's represent function bodies in
258  /// different ways.  They should each implement this to say what a function
259  /// pointer should look like.  When F is destroyed, the ExecutionEngine will
260  /// remove its global mapping and free any machine code.  Be sure no threads
261  /// are running inside F when that happens.
262  ///
263  virtual void *getPointerToFunction(Function *F) = 0;
264
265  /// getPointerToBasicBlock - The different EE's represent basic blocks in
266  /// different ways.  Return the representation for a blockaddress of the
267  /// specified block.
268  ///
269  virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
270
271  /// getPointerToFunctionOrStub - If the specified function has been
272  /// code-gen'd, return a pointer to the function.  If not, compile it, or use
273  /// a stub to implement lazy compilation if available.  See
274  /// getPointerToFunction for the requirements on destroying F.
275  ///
276  virtual void *getPointerToFunctionOrStub(Function *F) {
277    // Default implementation, just codegen the function.
278    return getPointerToFunction(F);
279  }
280
281  // The JIT overrides a version that actually does this.
282  virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
283
284  /// getGlobalValueAtAddress - Return the LLVM global value object that starts
285  /// at the specified address.
286  ///
287  const GlobalValue *getGlobalValueAtAddress(void *Addr);
288
289
290  void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
291                          const Type *Ty);
292  void InitializeMemory(const Constant *Init, void *Addr);
293
294  /// recompileAndRelinkFunction - This method is used to force a function
295  /// which has already been compiled to be compiled again, possibly
296  /// after it has been modified. Then the entry to the old copy is overwritten
297  /// with a branch to the new copy. If there was no old copy, this acts
298  /// just like VM::getPointerToFunction().
299  ///
300  virtual void *recompileAndRelinkFunction(Function *F) = 0;
301
302  /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
303  /// corresponding to the machine code emitted to execute this function, useful
304  /// for garbage-collecting generated code.
305  ///
306  virtual void freeMachineCodeForFunction(Function *F) = 0;
307
308  /// getOrEmitGlobalVariable - Return the address of the specified global
309  /// variable, possibly emitting it to memory if needed.  This is used by the
310  /// Emitter.
311  virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
312    return getPointerToGlobal((GlobalValue*)GV);
313  }
314
315  /// Registers a listener to be called back on various events within
316  /// the JIT.  See JITEventListener.h for more details.  Does not
317  /// take ownership of the argument.  The argument may be NULL, in
318  /// which case these functions do nothing.
319  virtual void RegisterJITEventListener(JITEventListener *) {}
320  virtual void UnregisterJITEventListener(JITEventListener *) {}
321
322  /// DisableLazyCompilation - When lazy compilation is off (the default), the
323  /// JIT will eagerly compile every function reachable from the argument to
324  /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
325  /// compile the one function and emit stubs to compile the rest when they're
326  /// first called.  If lazy compilation is turned off again while some lazy
327  /// stubs are still around, and one of those stubs is called, the program will
328  /// abort.
329  ///
330  /// In order to safely compile lazily in a threaded program, the user must
331  /// ensure that 1) only one thread at a time can call any particular lazy
332  /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
333  /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
334  /// lazy stub.  See http://llvm.org/PR5184 for details.
335  void DisableLazyCompilation(bool Disabled = true) {
336    CompilingLazily = !Disabled;
337  }
338  bool isCompilingLazily() const {
339    return CompilingLazily;
340  }
341  // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
342  // Remove this in LLVM 2.8.
343  bool isLazyCompilationDisabled() const {
344    return !CompilingLazily;
345  }
346
347  /// DisableGVCompilation - If called, the JIT will abort if it's asked to
348  /// allocate space and populate a GlobalVariable that is not internal to
349  /// the module.
350  void DisableGVCompilation(bool Disabled = true) {
351    GVCompilationDisabled = Disabled;
352  }
353  bool isGVCompilationDisabled() const {
354    return GVCompilationDisabled;
355  }
356
357  /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
358  /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
359  /// resolve symbols in a custom way.
360  void DisableSymbolSearching(bool Disabled = true) {
361    SymbolSearchingDisabled = Disabled;
362  }
363  bool isSymbolSearchingDisabled() const {
364    return SymbolSearchingDisabled;
365  }
366
367  /// InstallLazyFunctionCreator - If an unknown function is needed, the
368  /// specified function pointer is invoked to create it.  If it returns null,
369  /// the JIT will abort.
370  void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
371    LazyFunctionCreator = P;
372  }
373
374  /// InstallExceptionTableRegister - The JIT will use the given function
375  /// to register the exception tables it generates.
376  static void InstallExceptionTableRegister(void (*F)(void*)) {
377    ExceptionTableRegister = F;
378  }
379
380  /// RegisterTable - Registers the given pointer as an exception table. It uses
381  /// the ExceptionTableRegister function.
382  static void RegisterTable(void* res) {
383    if (ExceptionTableRegister)
384      ExceptionTableRegister(res);
385  }
386
387protected:
388  explicit ExecutionEngine(Module *M);
389
390  void emitGlobals();
391
392  // EmitGlobalVariable - This method emits the specified global variable to the
393  // address specified in GlobalAddresses, or allocates new memory if it's not
394  // already in the map.
395  void EmitGlobalVariable(const GlobalVariable *GV);
396
397  GenericValue getConstantValue(const Constant *C);
398  void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
399                           const Type *Ty);
400};
401
402namespace EngineKind {
403  // These are actually bitmasks that get or-ed together.
404  enum Kind {
405    JIT         = 0x1,
406    Interpreter = 0x2
407  };
408  const static Kind Either = (Kind)(JIT | Interpreter);
409}
410
411/// EngineBuilder - Builder class for ExecutionEngines.  Use this by
412/// stack-allocating a builder, chaining the various set* methods, and
413/// terminating it with a .create() call.
414class EngineBuilder {
415
416 private:
417  Module *M;
418  EngineKind::Kind WhichEngine;
419  std::string *ErrorStr;
420  CodeGenOpt::Level OptLevel;
421  JITMemoryManager *JMM;
422  bool AllocateGVsWithCode;
423  CodeModel::Model CMModel;
424  std::string MArch;
425  std::string MCPU;
426  SmallVector<std::string, 4> MAttrs;
427
428  /// InitEngine - Does the common initialization of default options.
429  ///
430  void InitEngine() {
431    WhichEngine = EngineKind::Either;
432    ErrorStr = NULL;
433    OptLevel = CodeGenOpt::Default;
434    JMM = NULL;
435    AllocateGVsWithCode = false;
436    CMModel = CodeModel::Default;
437  }
438
439 public:
440  /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
441  /// is successful, the created engine takes ownership of the module.
442  EngineBuilder(Module *m) : M(m) {
443    InitEngine();
444  }
445
446  /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
447  /// or whichever engine works.  This option defaults to EngineKind::Either.
448  EngineBuilder &setEngineKind(EngineKind::Kind w) {
449    WhichEngine = w;
450    return *this;
451  }
452
453  /// setJITMemoryManager - Sets the memory manager to use.  This allows
454  /// clients to customize their memory allocation policies.  If create() is
455  /// called and is successful, the created engine takes ownership of the
456  /// memory manager.  This option defaults to NULL.
457  EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
458    JMM = jmm;
459    return *this;
460  }
461
462  /// setErrorStr - Set the error string to write to on error.  This option
463  /// defaults to NULL.
464  EngineBuilder &setErrorStr(std::string *e) {
465    ErrorStr = e;
466    return *this;
467  }
468
469  /// setOptLevel - Set the optimization level for the JIT.  This option
470  /// defaults to CodeGenOpt::Default.
471  EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
472    OptLevel = l;
473    return *this;
474  }
475
476  /// setCodeModel - Set the CodeModel that the ExecutionEngine target
477  /// data is using. Defaults to target specific default "CodeModel::Default".
478  EngineBuilder &setCodeModel(CodeModel::Model M) {
479    CMModel = M;
480    return *this;
481  }
482
483  /// setAllocateGVsWithCode - Sets whether global values should be allocated
484  /// into the same buffer as code.  For most applications this should be set
485  /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
486  /// and is probably unsafe and bad for performance.  However, we have clients
487  /// who depend on this behavior, so we must support it.  This option defaults
488  /// to false so that users of the new API can safely use the new memory
489  /// manager and free machine code.
490  EngineBuilder &setAllocateGVsWithCode(bool a) {
491    AllocateGVsWithCode = a;
492    return *this;
493  }
494
495  /// setMArch - Override the architecture set by the Module's triple.
496  EngineBuilder &setMArch(StringRef march) {
497    MArch.assign(march.begin(), march.end());
498    return *this;
499  }
500
501  /// setMCPU - Target a specific cpu type.
502  EngineBuilder &setMCPU(StringRef mcpu) {
503    MCPU.assign(mcpu.begin(), mcpu.end());
504    return *this;
505  }
506
507  /// setMAttrs - Set cpu-specific attributes.
508  template<typename StringSequence>
509  EngineBuilder &setMAttrs(const StringSequence &mattrs) {
510    MAttrs.clear();
511    MAttrs.append(mattrs.begin(), mattrs.end());
512    return *this;
513  }
514
515  ExecutionEngine *create();
516};
517
518} // End llvm namespace
519
520#endif
521