1 //===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
38 // Tests on ARM, PowerPC and SystemZ disabled as we're running the old jit
39 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)
41 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
42 std::vector<Type*> params;
43 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
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);
56 std::string DumpFunction(const Function *F) {
58 raw_string_ostream(Result) << "" << *F;
62 class RecordingJITMemoryManager : public JITMemoryManager {
63 const OwningPtr<JITMemoryManager> Base;
65 RecordingJITMemoryManager()
66 : Base(JITMemoryManager::CreateDefaultMemManager()) {
69 virtual void *getPointerToNamedFunction(const std::string &Name,
70 bool AbortOnFailure = true) {
71 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
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) {}
88 uintptr_t ActualSizeResult;
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));
100 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
101 unsigned Alignment) {
103 return Base->allocateStub(F, StubSize, Alignment);
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) {}
112 uint8_t *FunctionStart;
113 uint8_t *FunctionEnd;
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);
122 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
123 unsigned SectionID, bool IsReadOnly) {
124 return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
126 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
127 unsigned SectionID) {
128 return Base->allocateCodeSection(Size, Alignment, SectionID);
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);
134 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
135 return Base->allocateGlobal(Size, Alignment);
137 struct DeallocateFunctionBodyCall {
138 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
141 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
142 virtual void deallocateFunctionBody(void *Body) {
143 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
144 Base->deallocateFunctionBody(Body);
148 bool LoadAssemblyInto(Module *M, const char *assembly) {
151 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
153 raw_string_ostream os(errMsg);
155 EXPECT_TRUE(success) << os.str();
159 class JITTest : public testing::Test {
161 virtual RecordingJITMemoryManager *createMemoryManager() {
162 return new RecordingJITMemoryManager;
165 virtual void SetUp() {
166 M = new Module("<main>", Context);
167 RJMM = createMemoryManager();
168 RJMM->setPoisonMemory(true);
170 TargetOptions Options;
171 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
172 .setJITMemoryManager(RJMM)
174 .setTargetOptions(Options).create());
175 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
178 void LoadAssembly(const char *assembly) {
179 LoadAssemblyInto(M, assembly);
183 Module *M; // Owned by ExecutionEngine.
184 RecordingJITMemoryManager *RJMM;
185 OwningPtr<ExecutionEngine> TheJIT;
188 // Regression test for a bug. The JIT used to allocate globals inside the same
189 // memory block used for the function, and when the function code was freed,
190 // the global was left in the same place. This test allocates a function
191 // that uses and global, deallocates it, and then makes sure that the global
192 // stays alive after that.
193 TEST(JIT, GlobalInFunction) {
195 Module *M = new Module("<main>", context);
197 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
198 // Tell the memory manager to poison freed memory so that accessing freed
199 // memory is more easily tested.
200 MemMgr->setPoisonMemory(true);
202 OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
203 .setEngineKind(EngineKind::JIT)
205 .setJITMemoryManager(MemMgr)
206 // The next line enables the fix:
207 .setAllocateGVsWithCode(false)
209 ASSERT_EQ(Error, "");
211 // Create a global variable.
212 Type *GTy = Type::getInt32Ty(context);
213 GlobalVariable *G = new GlobalVariable(
216 false, // Not constant.
217 GlobalValue::InternalLinkage,
218 Constant::getNullValue(GTy),
221 // Make a function that points to a global.
222 Function *F1 = makeReturnGlobal("F1", G, M);
224 // Get the pointer to the native code to force it to JIT the function and
225 // allocate space for the global.
227 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
229 // Since F1 was codegen'd, a pointer to G should be available.
230 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
231 ASSERT_NE((int32_t*)NULL, GPtr);
234 // F1() should increment G.
238 // Make a second function identical to the first, referring to the same
240 Function *F2 = makeReturnGlobal("F2", G, M);
242 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
244 // F2() should increment G.
249 JIT->freeMachineCodeForFunction(F1);
251 // F2() should *still* increment G.
256 int PlusOne(int arg) {
260 TEST_F(JITTest, FarCallToKnownFunction) {
261 // x86-64 can only make direct calls to functions within 32 bits of
262 // the current PC. To call anything farther away, we have to load
263 // the address into a register and call through the register. The
264 // current JIT does this by allocating a stub for any far call.
265 // There was a bug in which the JIT tried to emit a direct call when
266 // the target was already in the JIT's global mappings and lazy
267 // compilation was disabled.
269 Function *KnownFunction = Function::Create(
270 TypeBuilder<int(int), false>::get(Context),
271 GlobalValue::ExternalLinkage, "known", M);
272 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
274 // int test() { return known(7); }
275 Function *TestFunction = Function::Create(
276 TypeBuilder<int(), false>::get(Context),
277 GlobalValue::ExternalLinkage, "test", M);
278 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
279 IRBuilder<> Builder(Entry);
280 Value *result = Builder.CreateCall(
282 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
283 Builder.CreateRet(result);
285 TheJIT->DisableLazyCompilation(true);
286 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
287 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
288 // This used to crash in trying to call PlusOne().
289 EXPECT_EQ(8, TestFunctionPtr());
292 // Test a function C which calls A and B which call each other.
293 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
294 TheJIT->DisableLazyCompilation(true);
296 FunctionType *Func1Ty =
297 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
298 std::vector<Type*> arg_types;
299 arg_types.push_back(Type::getInt1Ty(Context));
300 FunctionType *FuncTy = FunctionType::get(
301 Type::getVoidTy(Context), arg_types, false);
302 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
304 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
306 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
308 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
309 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
310 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
311 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
312 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
313 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
314 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
316 // Make Func1 call Func2(0) and Func3(0).
317 IRBuilder<> Builder(Block1);
318 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
319 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
320 Builder.CreateRetVoid();
322 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
323 Builder.SetInsertPoint(Block2);
324 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
325 Builder.SetInsertPoint(True2);
326 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
327 Builder.CreateRetVoid();
328 Builder.SetInsertPoint(False2);
329 Builder.CreateRetVoid();
331 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
332 Builder.SetInsertPoint(Block3);
333 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
334 Builder.SetInsertPoint(True3);
335 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
336 Builder.CreateRetVoid();
337 Builder.SetInsertPoint(False3);
338 Builder.CreateRetVoid();
340 // Compile the function to native code
342 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
347 // Regression test for PR5162. This used to trigger an AssertingVH inside the
348 // JIT's Function to stub mapping.
349 TEST_F(JITTest, NonLazyLeaksNoStubs) {
350 TheJIT->DisableLazyCompilation(true);
352 // Create two functions with a single basic block each.
353 FunctionType *FuncTy =
354 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
355 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
357 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
359 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
360 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
362 // The first function calls the second and returns the result
363 IRBuilder<> Builder(Block1);
364 Value *Result = Builder.CreateCall(Func2);
365 Builder.CreateRet(Result);
367 // The second function just returns a constant
368 Builder.SetInsertPoint(Block2);
369 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
371 // Compile the function to native code
372 (void)TheJIT->getPointerToFunction(Func1);
374 // Free the JIT state for the functions
375 TheJIT->freeMachineCodeForFunction(Func1);
376 TheJIT->freeMachineCodeForFunction(Func2);
378 // Delete the first function (and show that is has no users)
379 EXPECT_EQ(Func1->getNumUses(), 0u);
380 Func1->eraseFromParent();
382 // Delete the second function (and show that it has no users - it had one,
383 // func1 but that's gone now)
384 EXPECT_EQ(Func2->getNumUses(), 0u);
385 Func2->eraseFromParent();
388 TEST_F(JITTest, ModuleDeletion) {
389 TheJIT->DisableLazyCompilation(false);
390 LoadAssembly("define void @main() { "
391 " call i32 @computeVal() "
395 "define internal i32 @computeVal() { "
398 Function *func = M->getFunction("main");
399 TheJIT->getPointerToFunction(func);
400 TheJIT->removeModule(M);
403 SmallPtrSet<const void*, 2> FunctionsDeallocated;
404 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
406 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
408 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
409 EXPECT_TRUE(FunctionsDeallocated.count(
410 RJMM->startFunctionBodyCalls[i].Result))
411 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
413 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
414 RJMM->deallocateFunctionBodyCalls.size());
417 // ARM, MIPS and PPC still emit stubs for calls since the target may be
418 // too far away to call directly. This #if can probably be removed when
419 // http://llvm.org/PR5201 is fixed.
420 #if !defined(__arm__) && !defined(__mips__) && \
421 !defined(__powerpc__) && !defined(__ppc__)
422 typedef int (*FooPtr) ();
424 TEST_F(JITTest, NoStubs) {
425 LoadAssembly("define void @bar() {"
430 "define i32 @foo() {"
436 "define i32 @main() {"
438 "%0 = call i32 @foo()"
442 Function *foo = M->getFunction("foo");
443 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
444 FooPtr ptr = (FooPtr)(tmp);
448 // We should now allocate no more stubs, we have the code to foo
449 // and the existing stub for bar.
450 int stubsBefore = RJMM->stubsAllocated;
451 Function *func = M->getFunction("main");
452 TheJIT->getPointerToFunction(func);
454 Function *bar = M->getFunction("bar");
455 TheJIT->getPointerToFunction(bar);
457 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
459 #endif // !ARM && !PPC
461 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
462 TheJIT->DisableLazyCompilation(true);
463 LoadAssembly("define i8()* @get_foo_addr() { "
467 "define i8 @foo() { "
470 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
472 typedef char(*fooT)();
473 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
474 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
475 fooT foo_addr = get_foo_addr();
477 // Now free get_foo_addr. This should not free the machine code for foo or
478 // any call stub returned as foo's canonical address.
479 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
481 // Check by calling the reported address of foo.
482 EXPECT_EQ(42, foo_addr());
484 // The reported address should also be the same as the result of a subsequent
485 // getPointerToFunction(foo).
487 // Fails until PR5126 is fixed:
488 Function *F_foo = M->getFunction("foo");
489 fooT foo = reinterpret_cast<fooT>(
490 (intptr_t)TheJIT->getPointerToFunction(F_foo));
491 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
495 // ARM does not have an implementation of replaceMachineCodeForFunction(),
496 // so recompileAndRelinkFunction doesn't work.
497 #if !defined(__arm__)
498 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
499 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
500 GlobalValue::ExternalLinkage, "test", M);
501 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
502 IRBuilder<> Builder(Entry);
503 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
504 Builder.CreateRet(Val);
506 TheJIT->DisableLazyCompilation(true);
507 // Compile the function once, and make sure it works.
508 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
509 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
510 EXPECT_EQ(1, OrigFPtr());
512 // Now change the function to return a different value.
513 Entry->eraseFromParent();
514 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
515 Builder.SetInsertPoint(NewEntry);
516 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
517 Builder.CreateRet(Val);
518 // Recompile it, which should produce a new function pointer _and_ update the
520 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
521 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
523 EXPECT_EQ(2, NewFPtr())
524 << "The new pointer should call the new version of the function";
525 EXPECT_EQ(2, OrigFPtr())
526 << "The old pointer's target should now jump to the new version";
528 #endif // !defined(__arm__)
530 } // anonymous namespace
531 // This variable is intentionally defined differently in the statically-compiled
532 // program from the IR input to the JIT to assert that the JIT doesn't use its
534 extern "C" int32_t JITTest_AvailableExternallyGlobal;
535 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
538 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
539 TheJIT->DisableLazyCompilation(true);
540 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
541 " available_externally global i32 7 "
543 "define i32 @loader() { "
544 " %result = load i32* @JITTest_AvailableExternallyGlobal "
547 Function *loaderIR = M->getFunction("loader");
549 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
550 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
551 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
552 << " not 7 from the IR version.";
554 } // anonymous namespace
555 // This function is intentionally defined differently in the statically-compiled
556 // program from the IR input to the JIT to assert that the JIT doesn't use its
558 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
559 extern "C" int32_t JITTest_AvailableExternallyFunction() {
564 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
565 TheJIT->DisableLazyCompilation(true);
566 LoadAssembly("define available_externally i32 "
567 " @JITTest_AvailableExternallyFunction() { "
571 "define i32 @func() { "
572 " %result = tail call i32 "
573 " @JITTest_AvailableExternallyFunction() "
576 Function *funcIR = M->getFunction("func");
578 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
579 (intptr_t)TheJIT->getPointerToFunction(funcIR));
580 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
581 << " not 7 from the IR version.";
584 TEST_F(JITTest, EscapedLazyStubStillCallable) {
585 TheJIT->DisableLazyCompilation(false);
586 LoadAssembly("define internal i32 @stubbed() { "
590 "define i32()* @get_stub() { "
591 " ret i32()* @stubbed "
593 typedef int32_t(*StubTy)();
595 // Call get_stub() to get the address of @stubbed without actually JITting it.
596 Function *get_stubIR = M->getFunction("get_stub");
597 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
598 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
599 StubTy stubbed = get_stub();
600 // Now get_stubIR is the only reference to stubbed's stub.
601 get_stubIR->eraseFromParent();
602 // Now there are no references inside the JIT, but we've got a pointer outside
603 // it. The stub should be callable and return the right value.
604 EXPECT_EQ(42, stubbed());
607 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
608 // empty string indicates an error.
609 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
610 Module TempModule("TempModule", Context);
611 if (!LoadAssemblyInto(&TempModule, Assembly)) {
616 raw_string_ostream OS(Result);
617 WriteBitcodeToFile(&TempModule, OS);
622 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
623 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
624 // M. Both will be NULL on an error. Bitcode must live at least as long as the
626 ExecutionEngine *getJITFromBitcode(
627 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
628 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
629 MemoryBuffer *BitcodeBuffer =
630 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
632 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
634 ADD_FAILURE() << errMsg;
635 delete BitcodeBuffer;
638 ExecutionEngine *TheJIT = EngineBuilder(M)
639 .setEngineKind(EngineKind::JIT)
640 .setErrorStr(&errMsg)
642 if (TheJIT == NULL) {
643 ADD_FAILURE() << errMsg;
651 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
653 const std::string Bitcode =
654 AssembleToBitcode(Context,
655 "define available_externally i32 "
656 " @JITTest_AvailableExternallyFunction() { "
660 "define i32 @func() { "
661 " %result = tail call i32 "
662 " @JITTest_AvailableExternallyFunction() "
665 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
667 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
668 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
669 TheJIT->DisableLazyCompilation(true);
671 Function *funcIR = M->getFunction("func");
672 Function *availableFunctionIR =
673 M->getFunction("JITTest_AvailableExternallyFunction");
675 // Double-check that the available_externally function is still unmaterialized
676 // when getPointerToFunction needs to find out if it's available_externally.
677 EXPECT_TRUE(availableFunctionIR->isMaterializable());
679 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
680 (intptr_t)TheJIT->getPointerToFunction(funcIR));
681 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
682 << " not 7 from the IR version.";
685 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
687 const std::string Bitcode =
688 AssembleToBitcode(Context,
689 "define i32 @recur1(i32 %a) { "
690 " %zero = icmp eq i32 %a, 0 "
691 " br i1 %zero, label %done, label %notdone "
695 " %am1 = sub i32 %a, 1 "
696 " %result = call i32 @recur2(i32 %am1) "
700 "define i32 @recur2(i32 %b) { "
701 " %result = call i32 @recur1(i32 %b) "
704 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
706 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
707 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
708 TheJIT->DisableLazyCompilation(true);
710 Function *recur1IR = M->getFunction("recur1");
711 Function *recur2IR = M->getFunction("recur2");
712 EXPECT_TRUE(recur1IR->isMaterializable());
713 EXPECT_TRUE(recur2IR->isMaterializable());
715 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
716 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
717 EXPECT_EQ(3, recur1(4));
719 #endif // !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)
721 // This code is copied from JITEventListenerTest, but it only runs once for all
722 // the tests in this directory. Everything seems fine, but that's strange
724 class JITEnvironment : public testing::Environment {
725 virtual void SetUp() {
726 // Required to create a JIT.
727 InitializeNativeTarget();
730 testing::Environment* const jit_env =
731 testing::AddGlobalTestEnvironment(new JITEnvironment);