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 PowerPC and SystemZ disabled as we're running the old jit
39 #if !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 // Tests on ARM disabled as we're running the old jit
189 #if !defined(__arm__)
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) {
198 Module *M = new Module("<main>", context);
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);
205 OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
206 .setEngineKind(EngineKind::JIT)
208 .setJITMemoryManager(MemMgr)
209 // The next line enables the fix:
210 .setAllocateGVsWithCode(false)
212 ASSERT_EQ(Error, "");
214 // Create a global variable.
215 Type *GTy = Type::getInt32Ty(context);
216 GlobalVariable *G = new GlobalVariable(
219 false, // Not constant.
220 GlobalValue::InternalLinkage,
221 Constant::getNullValue(GTy),
224 // Make a function that points to a global.
225 Function *F1 = makeReturnGlobal("F1", G, M);
227 // Get the pointer to the native code to force it to JIT the function and
228 // allocate space for the global.
230 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
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);
237 // F1() should increment G.
241 // Make a second function identical to the first, referring to the same
243 Function *F2 = makeReturnGlobal("F2", G, M);
245 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
247 // F2() should increment G.
252 JIT->freeMachineCodeForFunction(F1);
254 // F2() should *still* increment G.
259 #endif // !defined(__arm__)
261 // ARM tests disabled pending fix for PR10783.
262 #if !defined(__arm__)
264 int PlusOne(int arg) {
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.
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);
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(
290 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
291 Builder.CreateRet(result);
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());
300 // Test a function C which calls A and B which call each other.
301 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
302 TheJIT->DisableLazyCompilation(true);
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,
312 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
314 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
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);
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();
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();
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();
348 // Compile the function to native code
350 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
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);
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,
365 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
367 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
368 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
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);
375 // The second function just returns a constant
376 Builder.SetInsertPoint(Block2);
377 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
379 // Compile the function to native code
380 (void)TheJIT->getPointerToFunction(Func1);
382 // Free the JIT state for the functions
383 TheJIT->freeMachineCodeForFunction(Func1);
384 TheJIT->freeMachineCodeForFunction(Func2);
386 // Delete the first function (and show that is has no users)
387 EXPECT_EQ(Func1->getNumUses(), 0u);
388 Func1->eraseFromParent();
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();
396 TEST_F(JITTest, ModuleDeletion) {
397 TheJIT->DisableLazyCompilation(false);
398 LoadAssembly("define void @main() { "
399 " call i32 @computeVal() "
403 "define internal i32 @computeVal() { "
406 Function *func = M->getFunction("main");
407 TheJIT->getPointerToFunction(func);
408 TheJIT->removeModule(M);
411 SmallPtrSet<const void*, 2> FunctionsDeallocated;
412 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
414 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
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;
421 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
422 RJMM->deallocateFunctionBodyCalls.size());
424 #endif // !defined(__arm__)
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) ();
433 TEST_F(JITTest, NoStubs) {
434 LoadAssembly("define void @bar() {"
439 "define i32 @foo() {"
445 "define i32 @main() {"
447 "%0 = call i32 @foo()"
451 Function *foo = M->getFunction("foo");
452 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
453 FooPtr ptr = (FooPtr)(tmp);
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);
463 Function *bar = M->getFunction("bar");
464 TheJIT->getPointerToFunction(bar);
466 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
468 #endif // !ARM && !PPC
470 // Tests on ARM disabled as we're running the old jit
471 #if !defined(__arm__)
473 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
474 TheJIT->DisableLazyCompilation(true);
475 LoadAssembly("define i8()* @get_foo_addr() { "
479 "define i8 @foo() { "
482 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
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();
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);
493 // Check by calling the reported address of foo.
494 EXPECT_EQ(42, foo_addr());
496 // The reported address should also be the same as the result of a subsequent
497 // getPointerToFunction(foo).
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);
507 #endif //!defined(__arm__)
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);
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());
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
535 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
536 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
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";
543 #endif // !defined(__arm__)
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
549 extern "C" int32_t JITTest_AvailableExternallyGlobal;
550 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
553 // Tests on ARM disabled as we're running the old jit
554 #if !defined(__arm__)
556 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
557 TheJIT->DisableLazyCompilation(true);
558 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
559 " available_externally global i32 7 "
561 "define i32 @loader() { "
562 " %result = load i32* @JITTest_AvailableExternallyGlobal "
565 Function *loaderIR = M->getFunction("loader");
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.";
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
577 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
578 extern "C" int32_t JITTest_AvailableExternallyFunction() {
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() { "
592 "define i32 @func() { "
593 " %result = tail call i32 "
594 " @JITTest_AvailableExternallyFunction() "
597 Function *funcIR = M->getFunction("func");
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.";
605 TEST_F(JITTest, EscapedLazyStubStillCallable) {
606 TheJIT->DisableLazyCompilation(false);
607 LoadAssembly("define internal i32 @stubbed() { "
611 "define i32()* @get_stub() { "
612 " ret i32()* @stubbed "
614 typedef int32_t(*StubTy)();
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());
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)) {
637 raw_string_ostream OS(Result);
638 WriteBitcodeToFile(&TempModule, OS);
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
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");
653 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
655 ADD_FAILURE() << errMsg;
656 delete BitcodeBuffer;
659 ExecutionEngine *TheJIT = EngineBuilder(M)
660 .setEngineKind(EngineKind::JIT)
661 .setErrorStr(&errMsg)
663 if (TheJIT == NULL) {
664 ADD_FAILURE() << errMsg;
672 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
674 const std::string Bitcode =
675 AssembleToBitcode(Context,
676 "define available_externally i32 "
677 " @JITTest_AvailableExternallyFunction() { "
681 "define i32 @func() { "
682 " %result = tail call i32 "
683 " @JITTest_AvailableExternallyFunction() "
686 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
688 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
689 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
690 TheJIT->DisableLazyCompilation(true);
692 Function *funcIR = M->getFunction("func");
693 Function *availableFunctionIR =
694 M->getFunction("JITTest_AvailableExternallyFunction");
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());
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.";
706 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
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 "
716 " %am1 = sub i32 %a, 1 "
717 " %result = call i32 @recur2(i32 %am1) "
721 "define i32 @recur2(i32 %b) { "
722 " %result = call i32 @recur1(i32 %b) "
725 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
727 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
728 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
729 TheJIT->DisableLazyCompilation(true);
731 Function *recur1IR = M->getFunction("recur1");
732 Function *recur2IR = M->getFunction("recur2");
733 EXPECT_TRUE(recur1IR->isMaterializable());
734 EXPECT_TRUE(recur2IR->isMaterializable());
736 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
737 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
738 EXPECT_EQ(3, recur1(4));
740 #endif // !defined(__arm__)
741 #endif // !defined(__powerpc__) && !defined(__s390__)
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
746 class JITEnvironment : public testing::Environment {
747 virtual void SetUp() {
748 // Required to create a JIT.
749 InitializeNativeTarget();
752 testing::Environment* const jit_env =
753 testing::AddGlobalTestEnvironment(new JITEnvironment);