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