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