Pass a std::unique_ptr<MemoryBuffer>& to getLazyBitcodeModule.
[oota-llvm.git] / unittests / ExecutionEngine / JIT / JITTest.cpp
1 //===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
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 #include "llvm/ExecutionEngine/JIT.h"
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/Bitcode/ReaderWriter.h"
14 #include "llvm/ExecutionEngine/JITMemoryManager.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Constant.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/IR/TypeBuilder.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "gtest/gtest.h"
31 #include <vector>
32
33 using namespace llvm;
34
35 // This variable is intentionally defined differently in the statically-compiled
36 // program from the IR input to the JIT to assert that the JIT doesn't use its
37 // definition.  Note that this variable must be defined even on platforms where
38 // JIT tests are disabled as it is referenced from the .def file.
39 extern "C" int32_t JITTest_AvailableExternallyGlobal;
40 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
41
42 // This function is intentionally defined differently in the statically-compiled
43 // program from the IR input to the JIT to assert that the JIT doesn't use its
44 // definition.  Note that this function must be defined even on platforms where
45 // JIT tests are disabled as it is referenced from the .def file.
46 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
47 extern "C" int32_t JITTest_AvailableExternallyFunction() {
48   return 42;
49 }
50
51 namespace {
52
53 // Tests on ARM, PowerPC and SystemZ disabled as we're running the old jit
54 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__) \
55                       && !defined(__aarch64__)
56
57 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
58   std::vector<Type*> params;
59   FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
60                                               params, false);
61   Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
62   BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
63   IRBuilder<> builder(Entry);
64   Value *Load = builder.CreateLoad(G);
65   Type *GTy = G->getType()->getElementType();
66   Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
67   builder.CreateStore(Add, G);
68   builder.CreateRet(Add);
69   return F;
70 }
71
72 std::string DumpFunction(const Function *F) {
73   std::string Result;
74   raw_string_ostream(Result) << "" << *F;
75   return Result;
76 }
77
78 class RecordingJITMemoryManager : public JITMemoryManager {
79   const std::unique_ptr<JITMemoryManager> Base;
80
81 public:
82   RecordingJITMemoryManager()
83     : Base(JITMemoryManager::CreateDefaultMemManager()) {
84     stubsAllocated = 0;
85   }
86   virtual void *getPointerToNamedFunction(const std::string &Name,
87                                           bool AbortOnFailure = true) {
88     return Base->getPointerToNamedFunction(Name, AbortOnFailure);
89   }
90
91   virtual void setMemoryWritable() { Base->setMemoryWritable(); }
92   virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
93   virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
94   virtual void AllocateGOT() { Base->AllocateGOT(); }
95   virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
96   struct StartFunctionBodyCall {
97     StartFunctionBodyCall(uint8_t *Result, const Function *F,
98                           uintptr_t ActualSize, uintptr_t ActualSizeResult)
99       : Result(Result), F(F), F_dump(DumpFunction(F)),
100         ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
101     uint8_t *Result;
102     const Function *F;
103     std::string F_dump;
104     uintptr_t ActualSize;
105     uintptr_t ActualSizeResult;
106   };
107   std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
108   virtual uint8_t *startFunctionBody(const Function *F,
109                                      uintptr_t &ActualSize) {
110     uintptr_t InitialActualSize = ActualSize;
111     uint8_t *Result = Base->startFunctionBody(F, ActualSize);
112     startFunctionBodyCalls.push_back(
113       StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
114     return Result;
115   }
116   int stubsAllocated;
117   uint8_t *allocateStub(const GlobalValue *F, unsigned StubSize,
118                         unsigned Alignment) override {
119     stubsAllocated++;
120     return Base->allocateStub(F, StubSize, Alignment);
121   }
122   struct EndFunctionBodyCall {
123     EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
124                         uint8_t *FunctionEnd)
125       : F(F), F_dump(DumpFunction(F)),
126         FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
127     const Function *F;
128     std::string F_dump;
129     uint8_t *FunctionStart;
130     uint8_t *FunctionEnd;
131   };
132   std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
133   virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
134                                uint8_t *FunctionEnd) {
135     endFunctionBodyCalls.push_back(
136       EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
137     Base->endFunctionBody(F, FunctionStart, FunctionEnd);
138   }
139   virtual uint8_t *allocateDataSection(
140     uintptr_t Size, unsigned Alignment, unsigned SectionID,
141     StringRef SectionName, bool IsReadOnly) {
142     return Base->allocateDataSection(
143       Size, Alignment, SectionID, SectionName, IsReadOnly);
144   }
145   virtual uint8_t *allocateCodeSection(
146     uintptr_t Size, unsigned Alignment, unsigned SectionID,
147     StringRef SectionName) {
148     return Base->allocateCodeSection(
149       Size, Alignment, SectionID, SectionName);
150   }
151   virtual bool finalizeMemory(std::string *ErrMsg) { return false; }
152   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
153     return Base->allocateSpace(Size, Alignment);
154   }
155   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
156     return Base->allocateGlobal(Size, Alignment);
157   }
158   struct DeallocateFunctionBodyCall {
159     DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
160     const void *Body;
161   };
162   std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
163   virtual void deallocateFunctionBody(void *Body) {
164     deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
165     Base->deallocateFunctionBody(Body);
166   }
167 };
168
169 std::unique_ptr<Module> loadAssembly(LLVMContext &C, const char *Assembly) {
170   SMDiagnostic Error;
171   std::unique_ptr<Module> M = parseAssemblyString(Assembly, Error, C);
172   std::string errMsg;
173   raw_string_ostream os(errMsg);
174   Error.print("", os);
175   EXPECT_TRUE((bool)M) << os.str();
176   return M;
177 }
178
179 class JITTest : public testing::Test {
180  protected:
181   virtual RecordingJITMemoryManager *createMemoryManager() {
182     return new RecordingJITMemoryManager;
183   }
184
185   virtual void SetUp() {
186     std::unique_ptr<Module> Owner = make_unique<Module>("<main>", Context);
187     M = Owner.get();
188     RJMM = createMemoryManager();
189     RJMM->setPoisonMemory(true);
190     std::string Error;
191     TargetOptions Options;
192     TheJIT.reset(EngineBuilder(std::move(Owner))
193                      .setEngineKind(EngineKind::JIT)
194                      .setJITMemoryManager(RJMM)
195                      .setErrorStr(&Error)
196                      .setTargetOptions(Options)
197                      .create());
198     ASSERT_TRUE(TheJIT.get() != nullptr) << Error;
199   }
200
201   void LoadAssembly(const char *assembly) {
202     M = loadAssembly(Context, assembly).release();
203   }
204
205   LLVMContext Context;
206   Module *M;  // Owned by ExecutionEngine.
207   RecordingJITMemoryManager *RJMM;
208   std::unique_ptr<ExecutionEngine> TheJIT;
209 };
210
211 // Regression test for a bug.  The JIT used to allocate globals inside the same
212 // memory block used for the function, and when the function code was freed,
213 // the global was left in the same place.  This test allocates a function
214 // that uses and global, deallocates it, and then makes sure that the global
215 // stays alive after that.
216 TEST(JIT, GlobalInFunction) {
217   LLVMContext context;
218   std::unique_ptr<Module> Owner = make_unique<Module>("<main>", context);
219   Module *M = Owner.get();
220
221   JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
222   // Tell the memory manager to poison freed memory so that accessing freed
223   // memory is more easily tested.
224   MemMgr->setPoisonMemory(true);
225   std::string Error;
226   std::unique_ptr<ExecutionEngine> JIT(EngineBuilder(std::move(Owner))
227                                            .setEngineKind(EngineKind::JIT)
228                                            .setErrorStr(&Error)
229                                            .setJITMemoryManager(MemMgr)
230                                            // The next line enables the fix:
231                                            .setAllocateGVsWithCode(false)
232                                            .create());
233   ASSERT_EQ(Error, "");
234
235   // Create a global variable.
236   Type *GTy = Type::getInt32Ty(context);
237   GlobalVariable *G = new GlobalVariable(
238       *M,
239       GTy,
240       false,  // Not constant.
241       GlobalValue::InternalLinkage,
242       Constant::getNullValue(GTy),
243       "myglobal");
244
245   // Make a function that points to a global.
246   Function *F1 = makeReturnGlobal("F1", G, M);
247
248   // Get the pointer to the native code to force it to JIT the function and
249   // allocate space for the global.
250   void (*F1Ptr)() =
251       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
252
253   // Since F1 was codegen'd, a pointer to G should be available.
254   int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
255   ASSERT_NE((int32_t*)nullptr, GPtr);
256   EXPECT_EQ(0, *GPtr);
257
258   // F1() should increment G.
259   F1Ptr();
260   EXPECT_EQ(1, *GPtr);
261
262   // Make a second function identical to the first, referring to the same
263   // global.
264   Function *F2 = makeReturnGlobal("F2", G, M);
265   void (*F2Ptr)() =
266       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
267
268   // F2() should increment G.
269   F2Ptr();
270   EXPECT_EQ(2, *GPtr);
271
272   // Deallocate F1.
273   JIT->freeMachineCodeForFunction(F1);
274
275   // F2() should *still* increment G.
276   F2Ptr();
277   EXPECT_EQ(3, *GPtr);
278 }
279
280 int PlusOne(int arg) {
281   return arg + 1;
282 }
283
284 TEST_F(JITTest, FarCallToKnownFunction) {
285   // x86-64 can only make direct calls to functions within 32 bits of
286   // the current PC.  To call anything farther away, we have to load
287   // the address into a register and call through the register.  The
288   // current JIT does this by allocating a stub for any far call.
289   // There was a bug in which the JIT tried to emit a direct call when
290   // the target was already in the JIT's global mappings and lazy
291   // compilation was disabled.
292
293   Function *KnownFunction = Function::Create(
294       TypeBuilder<int(int), false>::get(Context),
295       GlobalValue::ExternalLinkage, "known", M);
296   TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
297
298   // int test() { return known(7); }
299   Function *TestFunction = Function::Create(
300       TypeBuilder<int(), false>::get(Context),
301       GlobalValue::ExternalLinkage, "test", M);
302   BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
303   IRBuilder<> Builder(Entry);
304   Value *result = Builder.CreateCall(
305       KnownFunction,
306       ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
307   Builder.CreateRet(result);
308
309   TheJIT->DisableLazyCompilation(true);
310   int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
311       (intptr_t)TheJIT->getPointerToFunction(TestFunction));
312   // This used to crash in trying to call PlusOne().
313   EXPECT_EQ(8, TestFunctionPtr());
314 }
315
316 // Test a function C which calls A and B which call each other.
317 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
318   TheJIT->DisableLazyCompilation(true);
319
320   FunctionType *Func1Ty =
321       cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
322   std::vector<Type*> arg_types;
323   arg_types.push_back(Type::getInt1Ty(Context));
324   FunctionType *FuncTy = FunctionType::get(
325       Type::getVoidTy(Context), arg_types, false);
326   Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
327                                      "func1", M);
328   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
329                                      "func2", M);
330   Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
331                                      "func3", M);
332   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
333   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
334   BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
335   BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
336   BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
337   BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
338   BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
339
340   // Make Func1 call Func2(0) and Func3(0).
341   IRBuilder<> Builder(Block1);
342   Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
343   Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
344   Builder.CreateRetVoid();
345
346   // void Func2(bool b) { if (b) { Func3(false); return; } return; }
347   Builder.SetInsertPoint(Block2);
348   Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
349   Builder.SetInsertPoint(True2);
350   Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
351   Builder.CreateRetVoid();
352   Builder.SetInsertPoint(False2);
353   Builder.CreateRetVoid();
354
355   // void Func3(bool b) { if (b) { Func2(false); return; } return; }
356   Builder.SetInsertPoint(Block3);
357   Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
358   Builder.SetInsertPoint(True3);
359   Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
360   Builder.CreateRetVoid();
361   Builder.SetInsertPoint(False3);
362   Builder.CreateRetVoid();
363
364   // Compile the function to native code
365   void (*F1Ptr)() =
366      reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
367
368   F1Ptr();
369 }
370
371 // Regression test for PR5162.  This used to trigger an AssertingVH inside the
372 // JIT's Function to stub mapping.
373 TEST_F(JITTest, NonLazyLeaksNoStubs) {
374   TheJIT->DisableLazyCompilation(true);
375
376   // Create two functions with a single basic block each.
377   FunctionType *FuncTy =
378       cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
379   Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
380                                      "func1", M);
381   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
382                                      "func2", M);
383   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
384   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
385
386   // The first function calls the second and returns the result
387   IRBuilder<> Builder(Block1);
388   Value *Result = Builder.CreateCall(Func2);
389   Builder.CreateRet(Result);
390
391   // The second function just returns a constant
392   Builder.SetInsertPoint(Block2);
393   Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
394
395   // Compile the function to native code
396   (void)TheJIT->getPointerToFunction(Func1);
397
398   // Free the JIT state for the functions
399   TheJIT->freeMachineCodeForFunction(Func1);
400   TheJIT->freeMachineCodeForFunction(Func2);
401
402   // Delete the first function (and show that is has no users)
403   EXPECT_EQ(Func1->getNumUses(), 0u);
404   Func1->eraseFromParent();
405
406   // Delete the second function (and show that it has no users - it had one,
407   // func1 but that's gone now)
408   EXPECT_EQ(Func2->getNumUses(), 0u);
409   Func2->eraseFromParent();
410 }
411
412 TEST_F(JITTest, ModuleDeletion) {
413   TheJIT->DisableLazyCompilation(false);
414   LoadAssembly("define void @main() { "
415                "  call i32 @computeVal() "
416                "  ret void "
417                "} "
418                " "
419                "define internal i32 @computeVal()  { "
420                "  ret i32 0 "
421                "} ");
422   Function *func = M->getFunction("main");
423   TheJIT->getPointerToFunction(func);
424   TheJIT->removeModule(M);
425   delete M;
426
427   SmallPtrSet<const void*, 2> FunctionsDeallocated;
428   for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
429        i != e; ++i) {
430     FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
431   }
432   for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
433     EXPECT_TRUE(FunctionsDeallocated.count(
434                   RJMM->startFunctionBodyCalls[i].Result))
435       << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
436   }
437   EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
438             RJMM->deallocateFunctionBodyCalls.size());
439 }
440
441 // ARM, MIPS and PPC still emit stubs for calls since the target may be
442 // too far away to call directly.  This #if can probably be removed when
443 // http://llvm.org/PR5201 is fixed.
444 #if !defined(__arm__) && !defined(__mips__) && \
445     !defined(__powerpc__) && !defined(__ppc__) && !defined(__aarch64__)
446 typedef int (*FooPtr) ();
447
448 TEST_F(JITTest, NoStubs) {
449   LoadAssembly("define void @bar() {"
450                "entry: "
451                "ret void"
452                "}"
453                " "
454                "define i32 @foo() {"
455                "entry:"
456                "call void @bar()"
457                "ret i32 undef"
458                "}"
459                " "
460                "define i32 @main() {"
461                "entry:"
462                "%0 = call i32 @foo()"
463                "call void @bar()"
464                "ret i32 undef"
465                "}");
466   Function *foo = M->getFunction("foo");
467   uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
468   FooPtr ptr = (FooPtr)(tmp);
469
470   (ptr)();
471
472   // We should now allocate no more stubs, we have the code to foo
473   // and the existing stub for bar.
474   int stubsBefore = RJMM->stubsAllocated;
475   Function *func = M->getFunction("main");
476   TheJIT->getPointerToFunction(func);
477
478   Function *bar = M->getFunction("bar");
479   TheJIT->getPointerToFunction(bar);
480
481   ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
482 }
483 #endif  // !ARM && !PPC
484
485 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
486   TheJIT->DisableLazyCompilation(true);
487   LoadAssembly("define i8()* @get_foo_addr() { "
488                "  ret i8()* @foo "
489                "} "
490                " "
491                "define i8 @foo() { "
492                "  ret i8 42 "
493                "} ");
494   Function *F_get_foo_addr = M->getFunction("get_foo_addr");
495
496   typedef char(*fooT)();
497   fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
498       (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
499   fooT foo_addr = get_foo_addr();
500
501   // Now free get_foo_addr.  This should not free the machine code for foo or
502   // any call stub returned as foo's canonical address.
503   TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
504
505   // Check by calling the reported address of foo.
506   EXPECT_EQ(42, foo_addr());
507
508   // The reported address should also be the same as the result of a subsequent
509   // getPointerToFunction(foo).
510 #if 0
511   // Fails until PR5126 is fixed:
512   Function *F_foo = M->getFunction("foo");
513   fooT foo = reinterpret_cast<fooT>(
514       (intptr_t)TheJIT->getPointerToFunction(F_foo));
515   EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
516 #endif
517 }
518
519 // ARM does not have an implementation of replaceMachineCodeForFunction(),
520 // so recompileAndRelinkFunction doesn't work.
521 #if !defined(__arm__) && !defined(__aarch64__)
522 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
523   Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
524                                  GlobalValue::ExternalLinkage, "test", M);
525   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
526   IRBuilder<> Builder(Entry);
527   Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
528   Builder.CreateRet(Val);
529
530   TheJIT->DisableLazyCompilation(true);
531   // Compile the function once, and make sure it works.
532   int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
533     (intptr_t)TheJIT->recompileAndRelinkFunction(F));
534   EXPECT_EQ(1, OrigFPtr());
535
536   // Now change the function to return a different value.
537   Entry->eraseFromParent();
538   BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
539   Builder.SetInsertPoint(NewEntry);
540   Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
541   Builder.CreateRet(Val);
542   // Recompile it, which should produce a new function pointer _and_ update the
543   // old one.
544   int (*NewFPtr)() = reinterpret_cast<int(*)()>(
545     (intptr_t)TheJIT->recompileAndRelinkFunction(F));
546
547   EXPECT_EQ(2, NewFPtr())
548     << "The new pointer should call the new version of the function";
549   EXPECT_EQ(2, OrigFPtr())
550     << "The old pointer's target should now jump to the new version";
551 }
552 #endif  // !defined(__arm__)
553
554 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
555   TheJIT->DisableLazyCompilation(true);
556   LoadAssembly("@JITTest_AvailableExternallyGlobal = "
557                "  available_externally global i32 7 "
558                " "
559                "define i32 @loader() { "
560                "  %result = load i32* @JITTest_AvailableExternallyGlobal "
561                "  ret i32 %result "
562                "} ");
563   Function *loaderIR = M->getFunction("loader");
564
565   int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
566     (intptr_t)TheJIT->getPointerToFunction(loaderIR));
567   EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
568                           << " not 7 from the IR version.";
569 }
570
571 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
572   TheJIT->DisableLazyCompilation(true);
573   LoadAssembly("define available_externally i32 "
574                "    @JITTest_AvailableExternallyFunction() { "
575                "  ret i32 7 "
576                "} "
577                " "
578                "define i32 @func() { "
579                "  %result = tail call i32 "
580                "    @JITTest_AvailableExternallyFunction() "
581                "  ret i32 %result "
582                "} ");
583   Function *funcIR = M->getFunction("func");
584
585   int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
586     (intptr_t)TheJIT->getPointerToFunction(funcIR));
587   EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
588                         << " not 7 from the IR version.";
589 }
590
591 TEST_F(JITTest, EscapedLazyStubStillCallable) {
592   TheJIT->DisableLazyCompilation(false);
593   LoadAssembly("define internal i32 @stubbed() { "
594                "  ret i32 42 "
595                "} "
596                " "
597                "define i32()* @get_stub() { "
598                "  ret i32()* @stubbed "
599                "} ");
600   typedef int32_t(*StubTy)();
601
602   // Call get_stub() to get the address of @stubbed without actually JITting it.
603   Function *get_stubIR = M->getFunction("get_stub");
604   StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
605     (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
606   StubTy stubbed = get_stub();
607   // Now get_stubIR is the only reference to stubbed's stub.
608   get_stubIR->eraseFromParent();
609   // Now there are no references inside the JIT, but we've got a pointer outside
610   // it.  The stub should be callable and return the right value.
611   EXPECT_EQ(42, stubbed());
612 }
613
614 // Converts the LLVM assembly to bitcode and returns it in a std::string.  An
615 // empty string indicates an error.
616 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
617   std::unique_ptr<Module> TempModule = loadAssembly(Context, Assembly);
618   if (!TempModule)
619     return "";
620
621   std::string Result;
622   raw_string_ostream OS(Result);
623   WriteBitcodeToFile(TempModule.get(), OS);
624   OS.flush();
625   return Result;
626 }
627
628 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
629 // lazily.  The associated Module (owned by the ExecutionEngine) is returned in
630 // M.  Both will be NULL on an error.  Bitcode must live at least as long as the
631 // ExecutionEngine.
632 ExecutionEngine *getJITFromBitcode(
633   LLVMContext &Context, const std::string &Bitcode, Module *&M) {
634   // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
635   std::unique_ptr<MemoryBuffer> BitcodeBuffer(
636       MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test"));
637   ErrorOr<Module*> ModuleOrErr = getLazyBitcodeModule(BitcodeBuffer, Context);
638   if (std::error_code EC = ModuleOrErr.getError()) {
639     ADD_FAILURE() << EC.message();
640     return nullptr;
641   }
642   std::unique_ptr<Module> Owner(ModuleOrErr.get());
643   M = Owner.get();
644   std::string errMsg;
645   ExecutionEngine *TheJIT = EngineBuilder(std::move(Owner))
646     .setEngineKind(EngineKind::JIT)
647     .setErrorStr(&errMsg)
648     .create();
649   if (TheJIT == nullptr) {
650     ADD_FAILURE() << errMsg;
651     delete M;
652     M = nullptr;
653     return nullptr;
654   }
655   return TheJIT;
656 }
657
658 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
659   LLVMContext Context;
660   const std::string Bitcode =
661     AssembleToBitcode(Context,
662                       "define available_externally i32 "
663                       "    @JITTest_AvailableExternallyFunction() { "
664                       "  ret i32 7 "
665                       "} "
666                       " "
667                       "define i32 @func() { "
668                       "  %result = tail call i32 "
669                       "    @JITTest_AvailableExternallyFunction() "
670                       "  ret i32 %result "
671                       "} ");
672   ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
673   Module *M;
674   std::unique_ptr<ExecutionEngine> TheJIT(
675       getJITFromBitcode(Context, Bitcode, M));
676   ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
677   TheJIT->DisableLazyCompilation(true);
678
679   Function *funcIR = M->getFunction("func");
680   Function *availableFunctionIR =
681     M->getFunction("JITTest_AvailableExternallyFunction");
682
683   // Double-check that the available_externally function is still unmaterialized
684   // when getPointerToFunction needs to find out if it's available_externally.
685   EXPECT_TRUE(availableFunctionIR->isMaterializable());
686
687   int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
688     (intptr_t)TheJIT->getPointerToFunction(funcIR));
689   EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
690                         << " not 7 from the IR version.";
691 }
692
693 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
694   LLVMContext Context;
695   const std::string Bitcode =
696     AssembleToBitcode(Context,
697                       "define i32 @recur1(i32 %a) { "
698                       "  %zero = icmp eq i32 %a, 0 "
699                       "  br i1 %zero, label %done, label %notdone "
700                       "done: "
701                       "  ret i32 3 "
702                       "notdone: "
703                       "  %am1 = sub i32 %a, 1 "
704                       "  %result = call i32 @recur2(i32 %am1) "
705                       "  ret i32 %result "
706                       "} "
707                       " "
708                       "define i32 @recur2(i32 %b) { "
709                       "  %result = call i32 @recur1(i32 %b) "
710                       "  ret i32 %result "
711                       "} ");
712   ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
713   Module *M;
714   std::unique_ptr<ExecutionEngine> TheJIT(
715       getJITFromBitcode(Context, Bitcode, M));
716   ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
717   TheJIT->DisableLazyCompilation(true);
718
719   Function *recur1IR = M->getFunction("recur1");
720   Function *recur2IR = M->getFunction("recur2");
721   EXPECT_TRUE(recur1IR->isMaterializable());
722   EXPECT_TRUE(recur2IR->isMaterializable());
723
724   int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
725     (intptr_t)TheJIT->getPointerToFunction(recur1IR));
726   EXPECT_EQ(3, recur1(4));
727 }
728 #endif // !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)
729
730 }