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