Sort the #include lines for unittest/...
[oota-llvm.git] / unittests / ExecutionEngine / MCJIT / MCJITTestBase.h
1 //===- MCJITTestBase.h - Common base class for MCJIT Unit tests  ----------===//
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 class implements common functionality required by the MCJIT unit tests,
11 // as well as logic to skip tests on unsupported architectures and operating
12 // systems.
13 //
14 //===----------------------------------------------------------------------===//
15
16
17 #ifndef MCJIT_TEST_BASE_H
18 #define MCJIT_TEST_BASE_H
19
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
24 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
25 #include "llvm/Function.h"
26 #include "llvm/IRBuilder.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Support/CodeGen.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/TypeBuilder.h"
33
34 // Used to skip tests on unsupported architectures and operating systems.
35 // To skip a test, add this macro at the top of a test-case in a suite that
36 // inherits from MCJITTestBase. See MCJITTest.cpp for examples.
37 #define SKIP_UNSUPPORTED_PLATFORM \
38   do \
39     if (!ArchSupportsMCJIT() || !OSSupportsMCJIT()) \
40       return; \
41   while(0);
42
43 namespace llvm {
44
45 class MCJITTestBase {
46 protected:
47
48   MCJITTestBase()
49     : OptLevel(CodeGenOpt::None)
50     , RelocModel(Reloc::Default)
51     , CodeModel(CodeModel::Default)
52     , MArch("")
53     , Builder(Context)
54     , MM(new SectionMemoryManager)
55     , HostTriple(LLVM_HOSTTRIPLE)
56   {
57     InitializeNativeTarget();
58     InitializeNativeTargetAsmPrinter();
59
60 #ifdef LLVM_ON_WIN32
61     // On Windows, generate ELF objects by specifying "-elf" in triple
62     HostTriple += "-elf";
63 #endif // LLVM_ON_WIN32
64     HostTriple = Triple::normalize(HostTriple);
65
66     // The architectures below are known to be compatible with MCJIT as they
67     // are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
68     // kept in sync.
69     SupportedArchs.push_back(Triple::arm);
70     SupportedArchs.push_back(Triple::mips);
71     SupportedArchs.push_back(Triple::x86);
72     SupportedArchs.push_back(Triple::x86_64);
73
74     // The operating systems below are known to be incompatible with MCJIT as
75     // they are copied from the test/ExecutionEngine/MCJIT/lit.local.cfg and
76     // should be kept in sync.
77     UnsupportedOSs.push_back(Triple::Cygwin);
78     UnsupportedOSs.push_back(Triple::Darwin);
79   }
80
81   /// Returns true if the host architecture is known to support MCJIT
82   bool ArchSupportsMCJIT() {
83     Triple Host(HostTriple);
84     if (std::find(SupportedArchs.begin(), SupportedArchs.end(), Host.getArch())
85         == SupportedArchs.end()) {
86       return false;
87     }
88     return true;
89   }
90
91   /// Returns true if the host OS is known to support MCJIT
92   bool OSSupportsMCJIT() {
93     Triple Host(HostTriple);
94     if (std::find(UnsupportedOSs.begin(), UnsupportedOSs.end(), Host.getOS())
95         == UnsupportedOSs.end()) {
96       return true;
97     }
98     return false;
99   }
100
101   Module *createEmptyModule(StringRef Name) {
102     Module * M = new Module(Name, Context);
103     M->setTargetTriple(Triple::normalize(HostTriple));
104     return M;
105   }
106
107   template<typename FuncType>
108   Function *startFunction(Module *M, StringRef Name) {
109     Function *Result = Function::Create(
110       TypeBuilder<FuncType, false>::get(Context),
111       GlobalValue::ExternalLinkage, Name, M);
112
113     BasicBlock *BB = BasicBlock::Create(Context, Name, Result);
114     Builder.SetInsertPoint(BB);
115
116     return Result;
117   }
118
119   void endFunctionWithRet(Function *Func, Value *RetValue) {
120     Builder.CreateRet(RetValue);
121   }
122
123   // Inserts a simple function that invokes Callee and takes the same arguments:
124   //    int Caller(...) { return Callee(...); }
125   template<typename Signature>
126   Function *insertSimpleCallFunction(Module *M, Function *Callee) {
127     Function *Result = startFunction<Signature>(M, "caller");
128
129     SmallVector<Value*, 1> CallArgs;
130
131     Function::arg_iterator arg_iter = Result->arg_begin();
132     for(;arg_iter != Result->arg_end(); ++arg_iter)
133       CallArgs.push_back(arg_iter);
134
135     Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
136     Builder.CreateRet(ReturnCode);
137     return Result;
138   }
139
140   // Inserts a function named 'main' that returns a uint32_t:
141   //    int32_t main() { return X; }
142   // where X is given by returnCode
143   Function *insertMainFunction(Module *M, uint32_t returnCode) {
144     Function *Result = startFunction<int32_t(void)>(M, "main");
145
146     Value *ReturnVal = ConstantInt::get(Context, APInt(32, returnCode));
147     endFunctionWithRet(Result, ReturnVal);
148
149     return Result;
150   }
151
152   // Inserts a function
153   //    int32_t add(int32_t a, int32_t b) { return a + b; }
154   // in the current module and returns a pointer to it.
155   Function *insertAddFunction(Module *M, StringRef Name = "add") {
156     Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
157
158     Function::arg_iterator args = Result->arg_begin();
159     Value *Arg1 = args;
160     Value *Arg2 = ++args;
161     Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
162
163     endFunctionWithRet(Result, AddResult);
164
165     return Result;
166   }
167
168   // Inserts an declaration to a function defined elsewhere
169   Function *insertExternalReferenceToFunction(Module *M, StringRef Name,
170                                               FunctionType *FuncTy) {
171     Function *Result = Function::Create(FuncTy,
172                                         GlobalValue::ExternalLinkage,
173                                         Name, M);
174     return Result;
175   }
176
177   // Inserts an declaration to a function defined elsewhere
178   Function *insertExternalReferenceToFunction(Module *M, Function *Func) {
179     Function *Result = Function::Create(Func->getFunctionType(),
180                                         GlobalValue::AvailableExternallyLinkage,
181                                         Func->getName(), M);
182     return Result;
183   }
184
185   // Inserts a global variable of type int32
186   GlobalVariable *insertGlobalInt32(Module *M,
187                                     StringRef name,
188                                     int32_t InitialValue) {
189     Type *GlobalTy = TypeBuilder<types::i<32>, true>::get(Context);
190     Constant *IV = ConstantInt::get(Context, APInt(32, InitialValue));
191     GlobalVariable *Global = new GlobalVariable(*M,
192                                                 GlobalTy,
193                                                 false,
194                                                 GlobalValue::ExternalLinkage,
195                                                 IV,
196                                                 name);
197     return Global;
198   }
199
200   void createJIT(Module *M) {
201
202     // Due to the EngineBuilder constructor, it is required to have a Module
203     // in order to construct an ExecutionEngine (i.e. MCJIT)
204     assert(M != 0 && "a non-null Module must be provided to create MCJIT");
205
206     EngineBuilder EB(M);
207     std::string Error;
208     TheJIT.reset(EB.setEngineKind(EngineKind::JIT)
209                  .setUseMCJIT(true) /* can this be folded into the EngineKind enum? */
210                  .setJITMemoryManager(MM)
211                  .setErrorStr(&Error)
212                  .setOptLevel(CodeGenOpt::None)
213                  .setAllocateGVsWithCode(false) /*does this do anything?*/
214                  .setCodeModel(CodeModel::JITDefault)
215                  .setRelocationModel(Reloc::Default)
216                  .setMArch(MArch)
217                  .setMCPU(sys::getHostCPUName())
218                  //.setMAttrs(MAttrs)
219                  .create());
220     // At this point, we cannot modify the module any more.
221     assert(TheJIT.get() != NULL && "error creating MCJIT with EngineBuilder");
222   }
223
224   LLVMContext Context;
225   CodeGenOpt::Level OptLevel;
226   Reloc::Model RelocModel;
227   CodeModel::Model CodeModel;
228   StringRef MArch;
229   SmallVector<std::string, 1> MAttrs;
230   OwningPtr<TargetMachine> TM;
231   OwningPtr<ExecutionEngine> TheJIT;
232   IRBuilder<> Builder;
233   JITMemoryManager *MM;
234
235   std::string HostTriple;
236   SmallVector<Triple::ArchType, 4> SupportedArchs;
237   SmallVector<Triple::OSType, 4> UnsupportedOSs;
238
239   OwningPtr<Module> M;
240 };
241
242 } // namespace llvm
243
244 #endif // MCJIT_TEST_H