c09c2724881ceb24fef4cf0cd9e8285e451e804c
[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 LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H
18 #define LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H
19
20 #include "MCJITTestAPICommon.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
24 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/TypeBuilder.h"
30 #include "llvm/Support/CodeGen.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33
34 namespace llvm {
35
36 /// Helper class that can build very simple Modules
37 class TrivialModuleBuilder {
38 protected:
39   LLVMContext Context;
40   IRBuilder<> Builder;
41   std::string BuilderTriple;
42
43   TrivialModuleBuilder(const std::string &Triple)
44     : Builder(Context), BuilderTriple(Triple) {}
45
46   Module *createEmptyModule(StringRef Name = StringRef()) {
47     Module * M = new Module(Name, Context);
48     M->setTargetTriple(Triple::normalize(BuilderTriple));
49     return M;
50   }
51
52   template<typename FuncType>
53   Function *startFunction(Module *M, StringRef Name) {
54     Function *Result = Function::Create(
55       TypeBuilder<FuncType, false>::get(Context),
56       GlobalValue::ExternalLinkage, Name, M);
57
58     BasicBlock *BB = BasicBlock::Create(Context, Name, Result);
59     Builder.SetInsertPoint(BB);
60
61     return Result;
62   }
63
64   void endFunctionWithRet(Function *Func, Value *RetValue) {
65     Builder.CreateRet(RetValue);
66   }
67
68   // Inserts a simple function that invokes Callee and takes the same arguments:
69   //    int Caller(...) { return Callee(...); }
70   template<typename Signature>
71   Function *insertSimpleCallFunction(Module *M, Function *Callee) {
72     Function *Result = startFunction<Signature>(M, "caller");
73
74     SmallVector<Value*, 1> CallArgs;
75
76     Function::arg_iterator arg_iter = Result->arg_begin();
77     for(;arg_iter != Result->arg_end(); ++arg_iter)
78       CallArgs.push_back(arg_iter);
79
80     Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
81     Builder.CreateRet(ReturnCode);
82     return Result;
83   }
84
85   // Inserts a function named 'main' that returns a uint32_t:
86   //    int32_t main() { return X; }
87   // where X is given by returnCode
88   Function *insertMainFunction(Module *M, uint32_t returnCode) {
89     Function *Result = startFunction<int32_t(void)>(M, "main");
90
91     Value *ReturnVal = ConstantInt::get(Context, APInt(32, returnCode));
92     endFunctionWithRet(Result, ReturnVal);
93
94     return Result;
95   }
96
97   // Inserts a function
98   //    int32_t add(int32_t a, int32_t b) { return a + b; }
99   // in the current module and returns a pointer to it.
100   Function *insertAddFunction(Module *M, StringRef Name = "add") {
101     Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
102
103     Function::arg_iterator args = Result->arg_begin();
104     Value *Arg1 = args;
105     Value *Arg2 = ++args;
106     Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
107
108     endFunctionWithRet(Result, AddResult);
109
110     return Result;
111   }
112
113   // Inserts a declaration to a function defined elsewhere
114   template <typename FuncType>
115   Function *insertExternalReferenceToFunction(Module *M, StringRef Name) {
116     Function *Result = Function::Create(
117                          TypeBuilder<FuncType, false>::get(Context),
118                          GlobalValue::ExternalLinkage, Name, M);
119     return Result;
120   }
121
122   // Inserts an declaration to a function defined elsewhere
123   Function *insertExternalReferenceToFunction(Module *M, StringRef Name,
124                                               FunctionType *FuncTy) {
125     Function *Result = Function::Create(FuncTy,
126                                         GlobalValue::ExternalLinkage,
127                                         Name, M);
128     return Result;
129   }
130
131   // Inserts an declaration to a function defined elsewhere
132   Function *insertExternalReferenceToFunction(Module *M, Function *Func) {
133     Function *Result = Function::Create(Func->getFunctionType(),
134                                         GlobalValue::ExternalLinkage,
135                                         Func->getName(), M);
136     return Result;
137   }
138
139   // Inserts a global variable of type int32
140   // FIXME: make this a template function to support any type
141   GlobalVariable *insertGlobalInt32(Module *M,
142                                     StringRef name,
143                                     int32_t InitialValue) {
144     Type *GlobalTy = TypeBuilder<types::i<32>, true>::get(Context);
145     Constant *IV = ConstantInt::get(Context, APInt(32, InitialValue));
146     GlobalVariable *Global = new GlobalVariable(*M,
147                                                 GlobalTy,
148                                                 false,
149                                                 GlobalValue::ExternalLinkage,
150                                                 IV,
151                                                 name);
152     return Global;
153   }
154
155   // Inserts a function
156   //   int32_t recursive_add(int32_t num) {
157   //     if (num == 0) {
158   //       return num;
159   //     } else {
160   //       int32_t recursive_param = num - 1;
161   //       return num + Helper(recursive_param);
162   //     }
163   //   }
164   // NOTE: if Helper is left as the default parameter, Helper == recursive_add.
165   Function *insertAccumulateFunction(Module *M,
166                                               Function *Helper = 0,
167                                               StringRef Name = "accumulate") {
168     Function *Result = startFunction<int32_t(int32_t)>(M, Name);
169     if (Helper == 0)
170       Helper = Result;
171
172     BasicBlock *BaseCase = BasicBlock::Create(Context, "", Result);
173     BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);
174
175     // if (num == 0)
176     Value *Param = Result->arg_begin();
177     Value *Zero = ConstantInt::get(Context, APInt(32, 0));
178     Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),
179                          BaseCase, RecursiveCase);
180
181     //   return num;
182     Builder.SetInsertPoint(BaseCase);
183     Builder.CreateRet(Param);
184
185     //   int32_t recursive_param = num - 1;
186     //   return Helper(recursive_param);
187     Builder.SetInsertPoint(RecursiveCase);
188     Value *One = ConstantInt::get(Context, APInt(32, 1));
189     Value *RecursiveParam = Builder.CreateSub(Param, One);
190     Value *RecursiveReturn = Builder.CreateCall(Helper, RecursiveParam);
191     Value *Accumulator = Builder.CreateAdd(Param, RecursiveReturn);
192     Builder.CreateRet(Accumulator);
193
194     return Result;
195   }
196
197   // Populates Modules A and B:
198   // Module A { Extern FB1, Function FA which calls FB1 },
199   // Module B { Extern FA, Function FB1, Function FB2 which calls FA },
200   void createCrossModuleRecursiveCase(std::unique_ptr<Module> &A, Function *&FA,
201                                       std::unique_ptr<Module> &B,
202                                       Function *&FB1, Function *&FB2) {
203     // Define FB1 in B.
204     B.reset(createEmptyModule("B"));
205     FB1 = insertAccumulateFunction(B.get(), 0, "FB1");
206
207     // Declare FB1 in A (as an external).
208     A.reset(createEmptyModule("A"));
209     Function *FB1Extern = insertExternalReferenceToFunction(A.get(), FB1);
210
211     // Define FA in A (with a call to FB1).
212     FA = insertAccumulateFunction(A.get(), FB1Extern, "FA");
213
214     // Declare FA in B (as an external)
215     Function *FAExtern = insertExternalReferenceToFunction(B.get(), FA);
216
217     // Define FB2 in B (with a call to FA)
218     FB2 = insertAccumulateFunction(B.get(), FAExtern, "FB2");
219   }
220
221   // Module A { Function FA },
222   // Module B { Extern FA, Function FB which calls FA },
223   // Module C { Extern FB, Function FC which calls FB },
224   void
225   createThreeModuleChainedCallsCase(std::unique_ptr<Module> &A, Function *&FA,
226                                     std::unique_ptr<Module> &B, Function *&FB,
227                                     std::unique_ptr<Module> &C, Function *&FC) {
228     A.reset(createEmptyModule("A"));
229     FA = insertAddFunction(A.get());
230
231     B.reset(createEmptyModule("B"));
232     Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
233     FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(), FAExtern_in_B);
234
235     C.reset(createEmptyModule("C"));
236     Function *FBExtern_in_C = insertExternalReferenceToFunction(C.get(), FB);
237     FC = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(C.get(), FBExtern_in_C);
238   }
239
240
241   // Module A { Function FA },
242   // Populates Modules A and B:
243   // Module B { Function FB }
244   void createTwoModuleCase(std::unique_ptr<Module> &A, Function *&FA,
245                            std::unique_ptr<Module> &B, Function *&FB) {
246     A.reset(createEmptyModule("A"));
247     FA = insertAddFunction(A.get());
248
249     B.reset(createEmptyModule("B"));
250     FB = insertAddFunction(B.get());
251   }
252
253   // Module A { Function FA },
254   // Module B { Extern FA, Function FB which calls FA }
255   void createTwoModuleExternCase(std::unique_ptr<Module> &A, Function *&FA,
256                                  std::unique_ptr<Module> &B, Function *&FB) {
257     A.reset(createEmptyModule("A"));
258     FA = insertAddFunction(A.get());
259
260     B.reset(createEmptyModule("B"));
261     Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
262     FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(),
263                                                              FAExtern_in_B);
264   }
265
266   // Module A { Function FA },
267   // Module B { Extern FA, Function FB which calls FA },
268   // Module C { Extern FB, Function FC which calls FA },
269   void createThreeModuleCase(std::unique_ptr<Module> &A, Function *&FA,
270                              std::unique_ptr<Module> &B, Function *&FB,
271                              std::unique_ptr<Module> &C, Function *&FC) {
272     A.reset(createEmptyModule("A"));
273     FA = insertAddFunction(A.get());
274
275     B.reset(createEmptyModule("B"));
276     Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
277     FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(), FAExtern_in_B);
278
279     C.reset(createEmptyModule("C"));
280     Function *FAExtern_in_C = insertExternalReferenceToFunction(C.get(), FA);
281     FC = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(C.get(), FAExtern_in_C);
282   }
283 };
284
285
286 class MCJITTestBase : public MCJITTestAPICommon, public TrivialModuleBuilder {
287 protected:
288
289   MCJITTestBase()
290     : TrivialModuleBuilder(HostTriple)
291     , OptLevel(CodeGenOpt::None)
292     , RelocModel(Reloc::Default)
293     , CodeModel(CodeModel::Default)
294     , MArch("")
295     , MM(new SectionMemoryManager)
296   {
297     // The architectures below are known to be compatible with MCJIT as they
298     // are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
299     // kept in sync.
300     SupportedArchs.push_back(Triple::aarch64);
301     SupportedArchs.push_back(Triple::arm);
302     SupportedArchs.push_back(Triple::mips);
303     SupportedArchs.push_back(Triple::mipsel);
304     SupportedArchs.push_back(Triple::x86);
305     SupportedArchs.push_back(Triple::x86_64);
306
307     // Some architectures have sub-architectures in which tests will fail, like
308     // ARM. These two vectors will define if they do have sub-archs (to avoid
309     // extra work for those who don't), and if so, if they are listed to work
310     HasSubArchs.push_back(Triple::arm);
311     SupportedSubArchs.push_back("armv6");
312     SupportedSubArchs.push_back("armv7");
313
314     // The operating systems below are known to be incompatible with MCJIT as
315     // they are copied from the test/ExecutionEngine/MCJIT/lit.local.cfg and
316     // should be kept in sync.
317     UnsupportedOSs.push_back(Triple::Darwin);
318
319     UnsupportedEnvironments.push_back(Triple::Cygnus);
320   }
321
322   void createJIT(std::unique_ptr<Module> M) {
323
324     // Due to the EngineBuilder constructor, it is required to have a Module
325     // in order to construct an ExecutionEngine (i.e. MCJIT)
326     assert(M != 0 && "a non-null Module must be provided to create MCJIT");
327
328     EngineBuilder EB(std::move(M));
329     std::string Error;
330     TheJIT.reset(EB.setEngineKind(EngineKind::JIT)
331                  .setMCJITMemoryManager(std::move(MM))
332                  .setErrorStr(&Error)
333                  .setOptLevel(CodeGenOpt::None)
334                  .setCodeModel(CodeModel::JITDefault)
335                  .setRelocationModel(Reloc::Default)
336                  .setMArch(MArch)
337                  .setMCPU(sys::getHostCPUName())
338                  //.setMAttrs(MAttrs)
339                  .create());
340     // At this point, we cannot modify the module any more.
341     assert(TheJIT.get() != NULL && "error creating MCJIT with EngineBuilder");
342   }
343
344   void createJITFromAssembly(const char *Test) {
345     SMDiagnostic Error;
346     M = parseAssemblyString(Test, Error, Context);
347     M->setTargetTriple(Triple::normalize(BuilderTriple));
348
349     std::string errMsg;
350     raw_string_ostream os(errMsg);
351     Error.print("", os);
352
353     // A failure here means that the test itself is buggy.
354     if (!M)
355       report_fatal_error(os.str().c_str());
356
357     createJIT(std::move(M));
358   }
359
360   CodeGenOpt::Level OptLevel;
361   Reloc::Model RelocModel;
362   CodeModel::Model CodeModel;
363   StringRef MArch;
364   SmallVector<std::string, 1> MAttrs;
365   std::unique_ptr<ExecutionEngine> TheJIT;
366   std::unique_ptr<RTDyldMemoryManager> MM;
367
368   std::unique_ptr<Module> M;
369 };
370
371 } // namespace llvm
372
373 #endif