ExecutionEngine.h revision 221345
1193323Sed//===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the abstract interface that implements execution support
11193323Sed// for LLVM.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#ifndef LLVM_EXECUTION_ENGINE_H
16193323Sed#define LLVM_EXECUTION_ENGINE_H
17193323Sed
18193323Sed#include <vector>
19193323Sed#include <map>
20193323Sed#include <string>
21193323Sed#include "llvm/ADT/SmallVector.h"
22203954Srdivacky#include "llvm/ADT/StringRef.h"
23198892Srdivacky#include "llvm/ADT/ValueMap.h"
24221345Sdim#include "llvm/ADT/DenseMap.h"
25198090Srdivacky#include "llvm/Support/ValueHandle.h"
26218893Sdim#include "llvm/Support/Mutex.h"
27193323Sed#include "llvm/Target/TargetMachine.h"
28193323Sed
29193323Sednamespace llvm {
30193323Sed
31193323Sedstruct GenericValue;
32193323Sedclass Constant;
33198090Srdivackyclass ExecutionEngine;
34193323Sedclass Function;
35193323Sedclass GlobalVariable;
36193323Sedclass GlobalValue;
37195098Sedclass JITEventListener;
38195098Sedclass JITMemoryManager;
39195098Sedclass MachineCodeInfo;
40193323Sedclass Module;
41195098Sedclass MutexGuard;
42193323Sedclass TargetData;
43193323Sedclass Type;
44193323Sed
45218893Sdim/// \brief Helper class for helping synchronize access to the global address map
46218893Sdim/// table.
47193323Sedclass ExecutionEngineState {
48198090Srdivackypublic:
49198892Srdivacky  struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
50198892Srdivacky    typedef ExecutionEngineState *ExtraData;
51198892Srdivacky    static sys::Mutex *getMutex(ExecutionEngineState *EES);
52198892Srdivacky    static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
53198892Srdivacky    static void onRAUW(ExecutionEngineState *, const GlobalValue *,
54198892Srdivacky                       const GlobalValue *);
55198892Srdivacky  };
56198090Srdivacky
57198892Srdivacky  typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
58198892Srdivacky      GlobalAddressMapTy;
59198090Srdivacky
60193323Sedprivate:
61198090Srdivacky  ExecutionEngine &EE;
62198090Srdivacky
63193323Sed  /// GlobalAddressMap - A mapping between LLVM global values and their
64193323Sed  /// actualized version...
65198892Srdivacky  GlobalAddressMapTy GlobalAddressMap;
66193323Sed
67193323Sed  /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
68193323Sed  /// used to convert raw addresses into the LLVM global value that is emitted
69193323Sed  /// at the address.  This map is not computed unless getGlobalValueAtAddress
70193323Sed  /// is called at some point.
71198090Srdivacky  std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
72193323Sed
73193323Sedpublic:
74198892Srdivacky  ExecutionEngineState(ExecutionEngine &EE);
75198090Srdivacky
76218893Sdim  GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
77193323Sed    return GlobalAddressMap;
78193323Sed  }
79193323Sed
80198090Srdivacky  std::map<void*, AssertingVH<const GlobalValue> > &
81193323Sed  getGlobalAddressReverseMap(const MutexGuard &) {
82193323Sed    return GlobalAddressReverseMap;
83193323Sed  }
84198090Srdivacky
85218893Sdim  /// \brief Erase an entry from the mapping table.
86218893Sdim  ///
87218893Sdim  /// \returns The address that \arg ToUnmap was happed to.
88198090Srdivacky  void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
89193323Sed};
90193323Sed
91218893Sdim/// \brief Abstract interface for implementation execution of LLVM modules,
92218893Sdim/// designed to support both interpreter and just-in-time (JIT) compiler
93218893Sdim/// implementations.
94218893Sdimclass ExecutionEngine {
95218893Sdim  /// The state object holding the global address mapping, which must be
96218893Sdim  /// accessed synchronously.
97218893Sdim  //
98218893Sdim  // FIXME: There is no particular need the entire map needs to be
99218893Sdim  // synchronized.  Wouldn't a reader-writer design be better here?
100218893Sdim  ExecutionEngineState EEState;
101193323Sed
102218893Sdim  /// The target data for the platform for which execution is being performed.
103193323Sed  const TargetData *TD;
104218893Sdim
105218893Sdim  /// Whether lazy JIT compilation is enabled.
106198892Srdivacky  bool CompilingLazily;
107218893Sdim
108218893Sdim  /// Whether JIT compilation of external global variables is allowed.
109193323Sed  bool GVCompilationDisabled;
110218893Sdim
111218893Sdim  /// Whether the JIT should perform lookups of external symbols (e.g.,
112218893Sdim  /// using dlsym).
113193323Sed  bool SymbolSearchingDisabled;
114193323Sed
115198090Srdivacky  friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
116198090Srdivacky
117193323Sedprotected:
118218893Sdim  /// The list of Modules that we are JIT'ing from.  We use a SmallVector to
119218893Sdim  /// optimize for the case where there is only one module.
120203954Srdivacky  SmallVector<Module*, 1> Modules;
121221345Sdim
122193323Sed  void setTargetData(const TargetData *td) {
123193323Sed    TD = td;
124193323Sed  }
125221345Sdim
126193323Sed  /// getMemoryforGV - Allocate memory for a global variable.
127218893Sdim  virtual char *getMemoryForGV(const GlobalVariable *GV);
128193323Sed
129193323Sed  // To avoid having libexecutionengine depend on the JIT and interpreter
130218893Sdim  // libraries, the execution engine implementations set these functions to ctor
131218893Sdim  // pointers at startup time if they are linked in.
132203954Srdivacky  static ExecutionEngine *(*JITCtor)(
133203954Srdivacky    Module *M,
134203954Srdivacky    std::string *ErrorStr,
135203954Srdivacky    JITMemoryManager *JMM,
136203954Srdivacky    CodeGenOpt::Level OptLevel,
137203954Srdivacky    bool GVsWithCode,
138203954Srdivacky    CodeModel::Model CMM,
139203954Srdivacky    StringRef MArch,
140203954Srdivacky    StringRef MCPU,
141203954Srdivacky    const SmallVectorImpl<std::string>& MAttrs);
142218893Sdim  static ExecutionEngine *(*MCJITCtor)(
143218893Sdim    Module *M,
144218893Sdim    std::string *ErrorStr,
145218893Sdim    JITMemoryManager *JMM,
146218893Sdim    CodeGenOpt::Level OptLevel,
147218893Sdim    bool GVsWithCode,
148218893Sdim    CodeModel::Model CMM,
149218893Sdim    StringRef MArch,
150218893Sdim    StringRef MCPU,
151218893Sdim    const SmallVectorImpl<std::string>& MAttrs);
152203954Srdivacky  static ExecutionEngine *(*InterpCtor)(Module *M,
153198090Srdivacky                                        std::string *ErrorStr);
154193323Sed
155193323Sed  /// LazyFunctionCreator - If an unknown function is needed, this function
156218893Sdim  /// pointer is invoked to create it.  If this returns null, the JIT will
157218893Sdim  /// abort.
158218893Sdim  void *(*LazyFunctionCreator)(const std::string &);
159221345Sdim
160218893Sdim  /// ExceptionTableRegister - If Exception Handling is set, the JIT will
161218893Sdim  /// register dwarf tables with this function.
162193323Sed  typedef void (*EERegisterFn)(void*);
163218893Sdim  EERegisterFn ExceptionTableRegister;
164218893Sdim  EERegisterFn ExceptionTableDeregister;
165221345Sdim  /// This maps functions to their exception tables frames.
166221345Sdim  DenseMap<const Function*, void*> AllExceptionTables;
167193323Sed
168221345Sdim
169193323Sedpublic:
170218893Sdim  /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
171193323Sed  /// JITEmitter classes.  It must be held while changing the internal state of
172193323Sed  /// any of those classes.
173218893Sdim  sys::Mutex lock;
174193323Sed
175193323Sed  //===--------------------------------------------------------------------===//
176193323Sed  //  ExecutionEngine Startup
177193323Sed  //===--------------------------------------------------------------------===//
178193323Sed
179193323Sed  virtual ~ExecutionEngine();
180193323Sed
181193323Sed  /// create - This is the factory method for creating an execution engine which
182193323Sed  /// is appropriate for the current machine.  This takes ownership of the
183203954Srdivacky  /// module.
184218893Sdim  ///
185218893Sdim  /// \param GVsWithCode - Allocating globals with code breaks
186218893Sdim  /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
187218893Sdim  /// However, we have clients who depend on this behavior, so we must support
188221345Sdim  /// it.  Eventually, when we're willing to break some backwards compatibility,
189218893Sdim  /// this flag should be flipped to false, so that by default
190218893Sdim  /// freeMachineCodeForFunction works.
191203954Srdivacky  static ExecutionEngine *create(Module *M,
192193323Sed                                 bool ForceInterpreter = false,
193193323Sed                                 std::string *ErrorStr = 0,
194193323Sed                                 CodeGenOpt::Level OptLevel =
195198090Srdivacky                                   CodeGenOpt::Default,
196198090Srdivacky                                 bool GVsWithCode = true);
197198090Srdivacky
198193323Sed  /// createJIT - This is the factory method for creating a JIT for the current
199193323Sed  /// machine, it does not fall back to the interpreter.  This takes ownership
200203954Srdivacky  /// of the Module and JITMemoryManager if successful.
201198090Srdivacky  ///
202198090Srdivacky  /// Clients should make sure to initialize targets prior to calling this
203198090Srdivacky  /// function.
204203954Srdivacky  static ExecutionEngine *createJIT(Module *M,
205193323Sed                                    std::string *ErrorStr = 0,
206193323Sed                                    JITMemoryManager *JMM = 0,
207193323Sed                                    CodeGenOpt::Level OptLevel =
208198090Srdivacky                                      CodeGenOpt::Default,
209199481Srdivacky                                    bool GVsWithCode = true,
210210299Sed                                    CodeModel::Model CMM =
211210299Sed                                      CodeModel::Default);
212193323Sed
213203954Srdivacky  /// addModule - Add a Module to the list of modules that we can JIT from.
214203954Srdivacky  /// Note that this takes ownership of the Module: when the ExecutionEngine is
215203954Srdivacky  /// destroyed, it destroys the Module as well.
216203954Srdivacky  virtual void addModule(Module *M) {
217203954Srdivacky    Modules.push_back(M);
218193323Sed  }
219221345Sdim
220218893Sdim  //===--------------------------------------------------------------------===//
221193323Sed
222193323Sed  const TargetData *getTargetData() const { return TD; }
223193323Sed
224203954Srdivacky  /// removeModule - Remove a Module from the list of modules.  Returns true if
225203954Srdivacky  /// M is found.
226203954Srdivacky  virtual bool removeModule(Module *M);
227193323Sed
228193323Sed  /// FindFunctionNamed - Search all of the active modules to find the one that
229193323Sed  /// defines FnName.  This is very slow operation and shouldn't be used for
230193323Sed  /// general code.
231193323Sed  Function *FindFunctionNamed(const char *FnName);
232221345Sdim
233193323Sed  /// runFunction - Execute the specified function with the specified arguments,
234193323Sed  /// and return the result.
235193323Sed  virtual GenericValue runFunction(Function *F,
236193323Sed                                const std::vector<GenericValue> &ArgValues) = 0;
237193323Sed
238193323Sed  /// runStaticConstructorsDestructors - This method is used to execute all of
239218893Sdim  /// the static constructors or destructors for a program.
240218893Sdim  ///
241218893Sdim  /// \param isDtors - Run the destructors instead of constructors.
242193323Sed  void runStaticConstructorsDestructors(bool isDtors);
243218893Sdim
244193323Sed  /// runStaticConstructorsDestructors - This method is used to execute all of
245218893Sdim  /// the static constructors or destructors for a particular module.
246218893Sdim  ///
247218893Sdim  /// \param isDtors - Run the destructors instead of constructors.
248193323Sed  void runStaticConstructorsDestructors(Module *module, bool isDtors);
249221345Sdim
250221345Sdim
251193323Sed  /// runFunctionAsMain - This is a helper function which wraps runFunction to
252193323Sed  /// handle the common task of starting up main with the specified argc, argv,
253193323Sed  /// and envp parameters.
254193323Sed  int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
255193323Sed                        const char * const * envp);
256193323Sed
257193323Sed
258193323Sed  /// addGlobalMapping - Tell the execution engine that the specified global is
259193323Sed  /// at the specified location.  This is used internally as functions are JIT'd
260193323Sed  /// and as global variables are laid out in memory.  It can and should also be
261193323Sed  /// used by clients of the EE that want to have an LLVM global overlay
262198090Srdivacky  /// existing data in memory.  Mappings are automatically removed when their
263198090Srdivacky  /// GlobalValue is destroyed.
264193323Sed  void addGlobalMapping(const GlobalValue *GV, void *Addr);
265221345Sdim
266218893Sdim  /// clearAllGlobalMappings - Clear all global mappings and start over again,
267218893Sdim  /// for use in dynamic compilation scenarios to move globals.
268193323Sed  void clearAllGlobalMappings();
269221345Sdim
270193323Sed  /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
271193323Sed  /// particular module, because it has been removed from the JIT.
272193323Sed  void clearGlobalMappingsFromModule(Module *M);
273221345Sdim
274193323Sed  /// updateGlobalMapping - Replace an existing mapping for GV with a new
275193323Sed  /// address.  This updates both maps as required.  If "Addr" is null, the
276193323Sed  /// entry for the global is removed from the mappings.  This returns the old
277193323Sed  /// value of the pointer, or null if it was not in the map.
278193323Sed  void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
279221345Sdim
280193323Sed  /// getPointerToGlobalIfAvailable - This returns the address of the specified
281193323Sed  /// global value if it is has already been codegen'd, otherwise it returns
282193323Sed  /// null.
283193323Sed  void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
284193323Sed
285193323Sed  /// getPointerToGlobal - This returns the address of the specified global
286218893Sdim  /// value. This may involve code generation if it's a function.
287193323Sed  void *getPointerToGlobal(const GlobalValue *GV);
288193323Sed
289193323Sed  /// getPointerToFunction - The different EE's represent function bodies in
290193323Sed  /// different ways.  They should each implement this to say what a function
291198090Srdivacky  /// pointer should look like.  When F is destroyed, the ExecutionEngine will
292198892Srdivacky  /// remove its global mapping and free any machine code.  Be sure no threads
293198892Srdivacky  /// are running inside F when that happens.
294193323Sed  virtual void *getPointerToFunction(Function *F) = 0;
295193323Sed
296198892Srdivacky  /// getPointerToBasicBlock - The different EE's represent basic blocks in
297198892Srdivacky  /// different ways.  Return the representation for a blockaddress of the
298198892Srdivacky  /// specified block.
299198892Srdivacky  virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
300221345Sdim
301193323Sed  /// getPointerToFunctionOrStub - If the specified function has been
302193323Sed  /// code-gen'd, return a pointer to the function.  If not, compile it, or use
303198090Srdivacky  /// a stub to implement lazy compilation if available.  See
304198090Srdivacky  /// getPointerToFunction for the requirements on destroying F.
305193323Sed  virtual void *getPointerToFunctionOrStub(Function *F) {
306193323Sed    // Default implementation, just codegen the function.
307193323Sed    return getPointerToFunction(F);
308193323Sed  }
309193323Sed
310193323Sed  // The JIT overrides a version that actually does this.
311194178Sed  virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
312193323Sed
313193323Sed  /// getGlobalValueAtAddress - Return the LLVM global value object that starts
314193323Sed  /// at the specified address.
315193323Sed  ///
316193323Sed  const GlobalValue *getGlobalValueAtAddress(void *Addr);
317193323Sed
318218893Sdim  /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
319218893Sdim  /// Ptr is the address of the memory at which to store Val, cast to
320218893Sdim  /// GenericValue *.  It is not a pointer to a GenericValue containing the
321218893Sdim  /// address at which to store Val.
322193323Sed  void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
323193323Sed                          const Type *Ty);
324218893Sdim
325193323Sed  void InitializeMemory(const Constant *Init, void *Addr);
326193323Sed
327218893Sdim  /// recompileAndRelinkFunction - This method is used to force a function which
328218893Sdim  /// has already been compiled to be compiled again, possibly after it has been
329218893Sdim  /// modified.  Then the entry to the old copy is overwritten with a branch to
330218893Sdim  /// the new copy.  If there was no old copy, this acts just like
331218893Sdim  /// VM::getPointerToFunction().
332193323Sed  virtual void *recompileAndRelinkFunction(Function *F) = 0;
333193323Sed
334193323Sed  /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
335193323Sed  /// corresponding to the machine code emitted to execute this function, useful
336193323Sed  /// for garbage-collecting generated code.
337193323Sed  virtual void freeMachineCodeForFunction(Function *F) = 0;
338193323Sed
339193323Sed  /// getOrEmitGlobalVariable - Return the address of the specified global
340193323Sed  /// variable, possibly emitting it to memory if needed.  This is used by the
341198090Srdivacky  /// Emitter.
342193323Sed  virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
343193323Sed    return getPointerToGlobal((GlobalValue*)GV);
344193323Sed  }
345195098Sed
346195098Sed  /// Registers a listener to be called back on various events within
347195098Sed  /// the JIT.  See JITEventListener.h for more details.  Does not
348195098Sed  /// take ownership of the argument.  The argument may be NULL, in
349195098Sed  /// which case these functions do nothing.
350198090Srdivacky  virtual void RegisterJITEventListener(JITEventListener *) {}
351198090Srdivacky  virtual void UnregisterJITEventListener(JITEventListener *) {}
352195098Sed
353198892Srdivacky  /// DisableLazyCompilation - When lazy compilation is off (the default), the
354198892Srdivacky  /// JIT will eagerly compile every function reachable from the argument to
355198892Srdivacky  /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
356198892Srdivacky  /// compile the one function and emit stubs to compile the rest when they're
357198892Srdivacky  /// first called.  If lazy compilation is turned off again while some lazy
358198892Srdivacky  /// stubs are still around, and one of those stubs is called, the program will
359198892Srdivacky  /// abort.
360198892Srdivacky  ///
361198892Srdivacky  /// In order to safely compile lazily in a threaded program, the user must
362198892Srdivacky  /// ensure that 1) only one thread at a time can call any particular lazy
363198892Srdivacky  /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
364198892Srdivacky  /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
365198892Srdivacky  /// lazy stub.  See http://llvm.org/PR5184 for details.
366193323Sed  void DisableLazyCompilation(bool Disabled = true) {
367198892Srdivacky    CompilingLazily = !Disabled;
368193323Sed  }
369198892Srdivacky  bool isCompilingLazily() const {
370198892Srdivacky    return CompilingLazily;
371198892Srdivacky  }
372198892Srdivacky  // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
373198892Srdivacky  // Remove this in LLVM 2.8.
374193323Sed  bool isLazyCompilationDisabled() const {
375198892Srdivacky    return !CompilingLazily;
376193323Sed  }
377193323Sed
378193323Sed  /// DisableGVCompilation - If called, the JIT will abort if it's asked to
379193323Sed  /// allocate space and populate a GlobalVariable that is not internal to
380193323Sed  /// the module.
381193323Sed  void DisableGVCompilation(bool Disabled = true) {
382193323Sed    GVCompilationDisabled = Disabled;
383193323Sed  }
384193323Sed  bool isGVCompilationDisabled() const {
385193323Sed    return GVCompilationDisabled;
386193323Sed  }
387193323Sed
388193323Sed  /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
389193323Sed  /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
390193323Sed  /// resolve symbols in a custom way.
391193323Sed  void DisableSymbolSearching(bool Disabled = true) {
392193323Sed    SymbolSearchingDisabled = Disabled;
393193323Sed  }
394193323Sed  bool isSymbolSearchingDisabled() const {
395193323Sed    return SymbolSearchingDisabled;
396193323Sed  }
397199481Srdivacky
398193323Sed  /// InstallLazyFunctionCreator - If an unknown function is needed, the
399193323Sed  /// specified function pointer is invoked to create it.  If it returns null,
400193323Sed  /// the JIT will abort.
401193323Sed  void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
402193323Sed    LazyFunctionCreator = P;
403193323Sed  }
404221345Sdim
405193323Sed  /// InstallExceptionTableRegister - The JIT will use the given function
406193323Sed  /// to register the exception tables it generates.
407218893Sdim  void InstallExceptionTableRegister(EERegisterFn F) {
408193323Sed    ExceptionTableRegister = F;
409193323Sed  }
410218893Sdim  void InstallExceptionTableDeregister(EERegisterFn F) {
411218893Sdim    ExceptionTableDeregister = F;
412218893Sdim  }
413221345Sdim
414218893Sdim  /// RegisterTable - Registers the given pointer as an exception table.  It
415218893Sdim  /// uses the ExceptionTableRegister function.
416221345Sdim  void RegisterTable(const Function *fn, void* res) {
417218893Sdim    if (ExceptionTableRegister) {
418193323Sed      ExceptionTableRegister(res);
419221345Sdim      AllExceptionTables[fn] = res;
420218893Sdim    }
421193323Sed  }
422193323Sed
423221345Sdim  /// DeregisterTable - Deregisters the exception frame previously registered
424221345Sdim  /// for the given function.
425221345Sdim  void DeregisterTable(const Function *Fn) {
426221345Sdim    if (ExceptionTableDeregister) {
427221345Sdim      DenseMap<const Function*, void*>::iterator frame =
428221345Sdim        AllExceptionTables.find(Fn);
429221345Sdim      if(frame != AllExceptionTables.end()) {
430221345Sdim        ExceptionTableDeregister(frame->second);
431221345Sdim        AllExceptionTables.erase(frame);
432221345Sdim      }
433221345Sdim    }
434221345Sdim  }
435221345Sdim
436218893Sdim  /// DeregisterAllTables - Deregisters all previously registered pointers to an
437218893Sdim  /// exception tables.  It uses the ExceptionTableoDeregister function.
438218893Sdim  void DeregisterAllTables();
439218893Sdim
440193323Sedprotected:
441203954Srdivacky  explicit ExecutionEngine(Module *M);
442193323Sed
443193323Sed  void emitGlobals();
444193323Sed
445193323Sed  void EmitGlobalVariable(const GlobalVariable *GV);
446193323Sed
447193323Sed  GenericValue getConstantValue(const Constant *C);
448221345Sdim  void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
449193323Sed                           const Type *Ty);
450193323Sed};
451193323Sed
452198090Srdivackynamespace EngineKind {
453198090Srdivacky  // These are actually bitmasks that get or-ed together.
454198090Srdivacky  enum Kind {
455198090Srdivacky    JIT         = 0x1,
456198090Srdivacky    Interpreter = 0x2
457198090Srdivacky  };
458198090Srdivacky  const static Kind Either = (Kind)(JIT | Interpreter);
459198090Srdivacky}
460198090Srdivacky
461198090Srdivacky/// EngineBuilder - Builder class for ExecutionEngines.  Use this by
462198090Srdivacky/// stack-allocating a builder, chaining the various set* methods, and
463198090Srdivacky/// terminating it with a .create() call.
464198090Srdivackyclass EngineBuilder {
465218893Sdimprivate:
466203954Srdivacky  Module *M;
467198090Srdivacky  EngineKind::Kind WhichEngine;
468198090Srdivacky  std::string *ErrorStr;
469198090Srdivacky  CodeGenOpt::Level OptLevel;
470198090Srdivacky  JITMemoryManager *JMM;
471198090Srdivacky  bool AllocateGVsWithCode;
472199481Srdivacky  CodeModel::Model CMModel;
473203954Srdivacky  std::string MArch;
474203954Srdivacky  std::string MCPU;
475203954Srdivacky  SmallVector<std::string, 4> MAttrs;
476218893Sdim  bool UseMCJIT;
477198090Srdivacky
478198090Srdivacky  /// InitEngine - Does the common initialization of default options.
479198090Srdivacky  void InitEngine() {
480198090Srdivacky    WhichEngine = EngineKind::Either;
481198090Srdivacky    ErrorStr = NULL;
482198090Srdivacky    OptLevel = CodeGenOpt::Default;
483198090Srdivacky    JMM = NULL;
484198090Srdivacky    AllocateGVsWithCode = false;
485199481Srdivacky    CMModel = CodeModel::Default;
486218893Sdim    UseMCJIT = false;
487198090Srdivacky  }
488198090Srdivacky
489218893Sdimpublic:
490198090Srdivacky  /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
491203954Srdivacky  /// is successful, the created engine takes ownership of the module.
492203954Srdivacky  EngineBuilder(Module *m) : M(m) {
493198090Srdivacky    InitEngine();
494198090Srdivacky  }
495198090Srdivacky
496198090Srdivacky  /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
497198090Srdivacky  /// or whichever engine works.  This option defaults to EngineKind::Either.
498198090Srdivacky  EngineBuilder &setEngineKind(EngineKind::Kind w) {
499198090Srdivacky    WhichEngine = w;
500198090Srdivacky    return *this;
501198090Srdivacky  }
502198090Srdivacky
503198090Srdivacky  /// setJITMemoryManager - Sets the memory manager to use.  This allows
504198090Srdivacky  /// clients to customize their memory allocation policies.  If create() is
505198090Srdivacky  /// called and is successful, the created engine takes ownership of the
506198090Srdivacky  /// memory manager.  This option defaults to NULL.
507198090Srdivacky  EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
508198090Srdivacky    JMM = jmm;
509198090Srdivacky    return *this;
510198090Srdivacky  }
511198090Srdivacky
512198090Srdivacky  /// setErrorStr - Set the error string to write to on error.  This option
513198090Srdivacky  /// defaults to NULL.
514198090Srdivacky  EngineBuilder &setErrorStr(std::string *e) {
515198090Srdivacky    ErrorStr = e;
516198090Srdivacky    return *this;
517198090Srdivacky  }
518198090Srdivacky
519198090Srdivacky  /// setOptLevel - Set the optimization level for the JIT.  This option
520198090Srdivacky  /// defaults to CodeGenOpt::Default.
521198090Srdivacky  EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
522198090Srdivacky    OptLevel = l;
523198090Srdivacky    return *this;
524198090Srdivacky  }
525198090Srdivacky
526199481Srdivacky  /// setCodeModel - Set the CodeModel that the ExecutionEngine target
527199481Srdivacky  /// data is using. Defaults to target specific default "CodeModel::Default".
528199481Srdivacky  EngineBuilder &setCodeModel(CodeModel::Model M) {
529199481Srdivacky    CMModel = M;
530199481Srdivacky    return *this;
531199481Srdivacky  }
532199481Srdivacky
533198090Srdivacky  /// setAllocateGVsWithCode - Sets whether global values should be allocated
534198090Srdivacky  /// into the same buffer as code.  For most applications this should be set
535198090Srdivacky  /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
536198090Srdivacky  /// and is probably unsafe and bad for performance.  However, we have clients
537198090Srdivacky  /// who depend on this behavior, so we must support it.  This option defaults
538198090Srdivacky  /// to false so that users of the new API can safely use the new memory
539198090Srdivacky  /// manager and free machine code.
540198090Srdivacky  EngineBuilder &setAllocateGVsWithCode(bool a) {
541198090Srdivacky    AllocateGVsWithCode = a;
542198090Srdivacky    return *this;
543198090Srdivacky  }
544198090Srdivacky
545203954Srdivacky  /// setMArch - Override the architecture set by the Module's triple.
546203954Srdivacky  EngineBuilder &setMArch(StringRef march) {
547203954Srdivacky    MArch.assign(march.begin(), march.end());
548203954Srdivacky    return *this;
549203954Srdivacky  }
550203954Srdivacky
551203954Srdivacky  /// setMCPU - Target a specific cpu type.
552203954Srdivacky  EngineBuilder &setMCPU(StringRef mcpu) {
553203954Srdivacky    MCPU.assign(mcpu.begin(), mcpu.end());
554203954Srdivacky    return *this;
555203954Srdivacky  }
556203954Srdivacky
557218893Sdim  /// setUseMCJIT - Set whether the MC-JIT implementation should be used
558218893Sdim  /// (experimental).
559221345Sdim  EngineBuilder &setUseMCJIT(bool Value) {
560218893Sdim    UseMCJIT = Value;
561221345Sdim    return *this;
562218893Sdim  }
563218893Sdim
564203954Srdivacky  /// setMAttrs - Set cpu-specific attributes.
565203954Srdivacky  template<typename StringSequence>
566203954Srdivacky  EngineBuilder &setMAttrs(const StringSequence &mattrs) {
567203954Srdivacky    MAttrs.clear();
568203954Srdivacky    MAttrs.append(mattrs.begin(), mattrs.end());
569203954Srdivacky    return *this;
570203954Srdivacky  }
571203954Srdivacky
572198090Srdivacky  ExecutionEngine *create();
573198090Srdivacky};
574198090Srdivacky
575193323Sed} // End llvm namespace
576193323Sed
577193323Sed#endif
578