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 "gtest/gtest.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/Assembly/Parser.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Bitcode/ReaderWriter.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/ExecutionEngine/JIT.h"
20 #include "llvm/ExecutionEngine/JITMemoryManager.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/Module.h"
26 #include "llvm/ModuleProvider.h"
27 #include "llvm/Support/IRBuilder.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TypeBuilder.h"
31 #include "llvm/Target/TargetSelect.h"
32 #include "llvm/Type.h"
40 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
41 std::vector<const Type*> params;
42 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
44 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
45 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
46 IRBuilder<> builder(Entry);
47 Value *Load = builder.CreateLoad(G);
48 const Type *GTy = G->getType()->getElementType();
49 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
50 builder.CreateStore(Add, G);
51 builder.CreateRet(Add);
55 std::string DumpFunction(const Function *F) {
57 raw_string_ostream(Result) << "" << *F;
62 class RecordingJITMemoryManager : public JITMemoryManager {
63 const OwningPtr<JITMemoryManager> Base;
65 RecordingJITMemoryManager()
66 : Base(JITMemoryManager::CreateDefaultMemManager()) {
70 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
71 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
72 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
73 virtual void AllocateGOT() { Base->AllocateGOT(); }
74 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
75 struct StartFunctionBodyCall {
76 StartFunctionBodyCall(uint8_t *Result, const Function *F,
77 uintptr_t ActualSize, uintptr_t ActualSizeResult)
78 : Result(Result), F(F), F_dump(DumpFunction(F)),
79 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
84 uintptr_t ActualSizeResult;
86 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
87 virtual uint8_t *startFunctionBody(const Function *F,
88 uintptr_t &ActualSize) {
89 uintptr_t InitialActualSize = ActualSize;
90 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
91 startFunctionBodyCalls.push_back(
92 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
96 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
99 return Base->allocateStub(F, StubSize, Alignment);
101 struct EndFunctionBodyCall {
102 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
103 uint8_t *FunctionEnd)
104 : F(F), F_dump(DumpFunction(F)),
105 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
108 uint8_t *FunctionStart;
109 uint8_t *FunctionEnd;
111 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
112 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
113 uint8_t *FunctionEnd) {
114 endFunctionBodyCalls.push_back(
115 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
116 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
118 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
119 return Base->allocateSpace(Size, Alignment);
121 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
122 return Base->allocateGlobal(Size, Alignment);
124 struct DeallocateFunctionBodyCall {
125 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
128 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
129 virtual void deallocateFunctionBody(void *Body) {
130 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
131 Base->deallocateFunctionBody(Body);
133 struct DeallocateExceptionTableCall {
134 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
137 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
138 virtual void deallocateExceptionTable(void *ET) {
139 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
140 Base->deallocateExceptionTable(ET);
142 struct StartExceptionTableCall {
143 StartExceptionTableCall(uint8_t *Result, const Function *F,
144 uintptr_t ActualSize, uintptr_t ActualSizeResult)
145 : Result(Result), F(F), F_dump(DumpFunction(F)),
146 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
150 uintptr_t ActualSize;
151 uintptr_t ActualSizeResult;
153 std::vector<StartExceptionTableCall> startExceptionTableCalls;
154 virtual uint8_t* startExceptionTable(const Function* F,
155 uintptr_t &ActualSize) {
156 uintptr_t InitialActualSize = ActualSize;
157 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
158 startExceptionTableCalls.push_back(
159 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
162 struct EndExceptionTableCall {
163 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
164 uint8_t *TableEnd, uint8_t* FrameRegister)
165 : F(F), F_dump(DumpFunction(F)),
166 TableStart(TableStart), TableEnd(TableEnd),
167 FrameRegister(FrameRegister) {}
172 uint8_t *FrameRegister;
174 std::vector<EndExceptionTableCall> endExceptionTableCalls;
175 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
176 uint8_t *TableEnd, uint8_t* FrameRegister) {
177 endExceptionTableCalls.push_back(
178 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
179 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
184 bool LoadAssemblyInto(Module *M, const char *assembly) {
187 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
189 raw_string_ostream os(errMsg);
191 EXPECT_TRUE(success) << os.str();
195 class JITTest : public testing::Test {
197 virtual void SetUp() {
198 M = new Module("<main>", Context);
199 MP = new ExistingModuleProvider(M);
201 RJMM = new RecordingJITMemoryManager;
202 RJMM->setPoisonMemory(true);
205 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
207 .setJITMemoryManager(RJMM)
209 .setErrorStr(&Error).create());
210 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
213 void LoadAssembly(const char *assembly) {
214 LoadAssemblyInto(M, assembly);
218 Module *M; // Owned by MP.
219 ModuleProvider *MP; // Owned by ExecutionEngine.
221 RecordingJITMemoryManager *RJMM;
223 OwningPtr<ExecutionEngine> TheJIT;
226 // Regression test for a bug. The JIT used to allocate globals inside the same
227 // memory block used for the function, and when the function code was freed,
228 // the global was left in the same place. This test allocates a function
229 // that uses and global, deallocates it, and then makes sure that the global
230 // stays alive after that.
231 TEST(JIT, GlobalInFunction) {
233 Module *M = new Module("<main>", context);
234 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
236 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
237 // Tell the memory manager to poison freed memory so that accessing freed
238 // memory is more easily tested.
239 MemMgr->setPoisonMemory(true);
241 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
242 .setEngineKind(EngineKind::JIT)
244 .setJITMemoryManager(MemMgr)
245 // The next line enables the fix:
246 .setAllocateGVsWithCode(false)
248 ASSERT_EQ(Error, "");
250 // Create a global variable.
251 const Type *GTy = Type::getInt32Ty(context);
252 GlobalVariable *G = new GlobalVariable(
255 false, // Not constant.
256 GlobalValue::InternalLinkage,
257 Constant::getNullValue(GTy),
260 // Make a function that points to a global.
261 Function *F1 = makeReturnGlobal("F1", G, M);
263 // Get the pointer to the native code to force it to JIT the function and
264 // allocate space for the global.
266 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
268 // Since F1 was codegen'd, a pointer to G should be available.
269 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
270 ASSERT_NE((int32_t*)NULL, GPtr);
273 // F1() should increment G.
277 // Make a second function identical to the first, referring to the same
279 Function *F2 = makeReturnGlobal("F2", G, M);
281 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
283 // F2() should increment G.
288 JIT->freeMachineCodeForFunction(F1);
290 // F2() should *still* increment G.
295 int PlusOne(int arg) {
299 TEST_F(JITTest, FarCallToKnownFunction) {
300 // x86-64 can only make direct calls to functions within 32 bits of
301 // the current PC. To call anything farther away, we have to load
302 // the address into a register and call through the register. The
303 // current JIT does this by allocating a stub for any far call.
304 // There was a bug in which the JIT tried to emit a direct call when
305 // the target was already in the JIT's global mappings and lazy
306 // compilation was disabled.
308 Function *KnownFunction = Function::Create(
309 TypeBuilder<int(int), false>::get(Context),
310 GlobalValue::ExternalLinkage, "known", M);
311 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
313 // int test() { return known(7); }
314 Function *TestFunction = Function::Create(
315 TypeBuilder<int(), false>::get(Context),
316 GlobalValue::ExternalLinkage, "test", M);
317 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
318 IRBuilder<> Builder(Entry);
319 Value *result = Builder.CreateCall(
321 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
322 Builder.CreateRet(result);
324 TheJIT->DisableLazyCompilation(true);
325 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
326 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
327 // This used to crash in trying to call PlusOne().
328 EXPECT_EQ(8, TestFunctionPtr());
331 // Test a function C which calls A and B which call each other.
332 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
333 TheJIT->DisableLazyCompilation(true);
335 const FunctionType *Func1Ty =
336 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
337 std::vector<const Type*> arg_types;
338 arg_types.push_back(Type::getInt1Ty(Context));
339 const FunctionType *FuncTy = FunctionType::get(
340 Type::getVoidTy(Context), arg_types, false);
341 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
343 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
345 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
347 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
348 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
349 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
350 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
351 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
352 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
353 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
355 // Make Func1 call Func2(0) and Func3(0).
356 IRBuilder<> Builder(Block1);
357 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
358 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
359 Builder.CreateRetVoid();
361 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
362 Builder.SetInsertPoint(Block2);
363 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
364 Builder.SetInsertPoint(True2);
365 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
366 Builder.CreateRetVoid();
367 Builder.SetInsertPoint(False2);
368 Builder.CreateRetVoid();
370 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
371 Builder.SetInsertPoint(Block3);
372 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
373 Builder.SetInsertPoint(True3);
374 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
375 Builder.CreateRetVoid();
376 Builder.SetInsertPoint(False3);
377 Builder.CreateRetVoid();
379 // Compile the function to native code
381 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
386 // Regression test for PR5162. This used to trigger an AssertingVH inside the
387 // JIT's Function to stub mapping.
388 TEST_F(JITTest, NonLazyLeaksNoStubs) {
389 TheJIT->DisableLazyCompilation(true);
391 // Create two functions with a single basic block each.
392 const FunctionType *FuncTy =
393 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
394 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
396 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
398 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
399 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
401 // The first function calls the second and returns the result
402 IRBuilder<> Builder(Block1);
403 Value *Result = Builder.CreateCall(Func2);
404 Builder.CreateRet(Result);
406 // The second function just returns a constant
407 Builder.SetInsertPoint(Block2);
408 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
410 // Compile the function to native code
411 (void)TheJIT->getPointerToFunction(Func1);
413 // Free the JIT state for the functions
414 TheJIT->freeMachineCodeForFunction(Func1);
415 TheJIT->freeMachineCodeForFunction(Func2);
417 // Delete the first function (and show that is has no users)
418 EXPECT_EQ(Func1->getNumUses(), 0u);
419 Func1->eraseFromParent();
421 // Delete the second function (and show that it has no users - it had one,
422 // func1 but that's gone now)
423 EXPECT_EQ(Func2->getNumUses(), 0u);
424 Func2->eraseFromParent();
427 TEST_F(JITTest, ModuleDeletion) {
428 TheJIT->DisableLazyCompilation(false);
429 LoadAssembly("define void @main() { "
430 " call i32 @computeVal() "
434 "define internal i32 @computeVal() { "
437 Function *func = M->getFunction("main");
438 TheJIT->getPointerToFunction(func);
439 TheJIT->deleteModuleProvider(MP);
442 SmallPtrSet<const void*, 2> FunctionsDeallocated;
443 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
445 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
447 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
448 EXPECT_TRUE(FunctionsDeallocated.count(
449 RJMM->startFunctionBodyCalls[i].Result))
450 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
452 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
453 RJMM->deallocateFunctionBodyCalls.size());
455 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
456 unsigned NumTablesDeallocated = 0;
457 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
459 ExceptionTablesDeallocated.insert(
460 RJMM->deallocateExceptionTableCalls[i].ET);
461 if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
462 // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
463 // appear in startExceptionTableCalls.
464 NumTablesDeallocated++;
467 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
468 EXPECT_TRUE(ExceptionTablesDeallocated.count(
469 RJMM->startExceptionTableCalls[i].Result))
470 << "Function's exception table leaked: \n"
471 << RJMM->startExceptionTableCalls[i].F_dump;
473 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
474 NumTablesDeallocated);
478 // ARM and PPC still emit stubs for calls since the target may be too far away
479 // to call directly. This #if can probably be removed when
480 // http://llvm.org/PR5201 is fixed.
481 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__ppc__)
482 typedef int (*FooPtr) ();
484 TEST_F(JITTest, NoStubs) {
485 LoadAssembly("define void @bar() {"
490 "define i32 @foo() {"
496 "define i32 @main() {"
498 "%0 = call i32 @foo()"
502 Function *foo = M->getFunction("foo");
503 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
504 FooPtr ptr = (FooPtr)(tmp);
508 // We should now allocate no more stubs, we have the code to foo
509 // and the existing stub for bar.
511 int stubsBefore = RJMM->stubsAllocated;
513 Function *func = M->getFunction("main");
514 TheJIT->getPointerToFunction(func);
516 Function *bar = M->getFunction("bar");
517 TheJIT->getPointerToFunction(bar);
520 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
523 #endif // !ARM && !PPC
525 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
526 TheJIT->DisableLazyCompilation(true);
527 LoadAssembly("define i8()* @get_foo_addr() { "
531 "define i8 @foo() { "
534 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
536 typedef char(*fooT)();
537 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
538 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
539 fooT foo_addr = get_foo_addr();
541 // Now free get_foo_addr. This should not free the machine code for foo or
542 // any call stub returned as foo's canonical address.
543 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
545 // Check by calling the reported address of foo.
546 EXPECT_EQ(42, foo_addr());
548 // The reported address should also be the same as the result of a subsequent
549 // getPointerToFunction(foo).
551 // Fails until PR5126 is fixed:
552 Function *F_foo = M->getFunction("foo");
553 fooT foo = reinterpret_cast<fooT>(
554 (intptr_t)TheJIT->getPointerToFunction(F_foo));
555 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
559 // ARM doesn't have an implementation of replaceMachineCodeForFunction(), so
560 // recompileAndRelinkFunction doesn't work.
561 #if !defined(__arm__)
562 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
563 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
564 GlobalValue::ExternalLinkage, "test", M);
565 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
566 IRBuilder<> Builder(Entry);
567 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
568 Builder.CreateRet(Val);
570 TheJIT->DisableLazyCompilation(true);
571 // Compile the function once, and make sure it works.
572 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
573 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
574 EXPECT_EQ(1, OrigFPtr());
576 // Now change the function to return a different value.
577 Entry->eraseFromParent();
578 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
579 Builder.SetInsertPoint(NewEntry);
580 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
581 Builder.CreateRet(Val);
582 // Recompile it, which should produce a new function pointer _and_ update the
584 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
585 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
587 EXPECT_EQ(2, NewFPtr())
588 << "The new pointer should call the new version of the function";
589 EXPECT_EQ(2, OrigFPtr())
590 << "The old pointer's target should now jump to the new version";
592 #endif // !defined(__arm__)
594 } // anonymous namespace
595 // This variable is intentionally defined differently in the statically-compiled
596 // program from the IR input to the JIT to assert that the JIT doesn't use its
598 extern "C" int32_t JITTest_AvailableExternallyGlobal;
599 int32_t JITTest_AvailableExternallyGlobal = 42;
602 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
603 TheJIT->DisableLazyCompilation(true);
604 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
605 " available_externally global i32 7 "
607 "define i32 @loader() { "
608 " %result = load i32* @JITTest_AvailableExternallyGlobal "
611 Function *loaderIR = M->getFunction("loader");
613 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
614 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
615 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
616 << " not 7 from the IR version.";
619 } // anonymous namespace
620 // This function is intentionally defined differently in the statically-compiled
621 // program from the IR input to the JIT to assert that the JIT doesn't use its
623 extern "C" int32_t JITTest_AvailableExternallyFunction() {
628 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
629 TheJIT->DisableLazyCompilation(true);
630 LoadAssembly("define available_externally i32 "
631 " @JITTest_AvailableExternallyFunction() { "
635 "define i32 @func() { "
636 " %result = tail call i32 "
637 " @JITTest_AvailableExternallyFunction() "
640 Function *funcIR = M->getFunction("func");
642 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
643 (intptr_t)TheJIT->getPointerToFunction(funcIR));
644 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
645 << " not 7 from the IR version.";
648 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
649 // empty string indicates an error.
650 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
651 Module TempModule("TempModule", Context);
652 if (!LoadAssemblyInto(&TempModule, Assembly)) {
657 raw_string_ostream OS(Result);
658 WriteBitcodeToFile(&TempModule, OS);
663 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
664 // lazily. The associated ModuleProvider (owned by the ExecutionEngine) is
665 // returned in MP. Both will be NULL on an error. Bitcode must live at least
666 // as long as the ExecutionEngine.
667 ExecutionEngine *getJITFromBitcode(
668 LLVMContext &Context, const std::string &Bitcode, ModuleProvider *&MP) {
669 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
670 MemoryBuffer *BitcodeBuffer =
671 MemoryBuffer::getMemBuffer(Bitcode.c_str(),
672 Bitcode.c_str() + Bitcode.size(),
675 MP = getBitcodeModuleProvider(BitcodeBuffer, Context, &errMsg);
677 ADD_FAILURE() << errMsg;
678 delete BitcodeBuffer;
681 ExecutionEngine *TheJIT = EngineBuilder(MP)
682 .setEngineKind(EngineKind::JIT)
683 .setErrorStr(&errMsg)
685 if (TheJIT == NULL) {
686 ADD_FAILURE() << errMsg;
694 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
696 const std::string Bitcode =
697 AssembleToBitcode(Context,
698 "define i32 @recur1(i32 %a) { "
699 " %zero = icmp eq i32 %a, 0 "
700 " br i1 %zero, label %done, label %notdone "
704 " %am1 = sub i32 %a, 1 "
705 " %result = call i32 @recur2(i32 %am1) "
709 "define i32 @recur2(i32 %b) { "
710 " %result = call i32 @recur1(i32 %b) "
713 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
715 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, MP));
716 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
717 TheJIT->DisableLazyCompilation(true);
719 Module *M = MP->getModule();
720 Function *recur1IR = M->getFunction("recur1");
721 Function *recur2IR = M->getFunction("recur2");
722 EXPECT_TRUE(recur1IR->hasNotBeenReadFromBitcode());
723 EXPECT_TRUE(recur2IR->hasNotBeenReadFromBitcode());
725 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
726 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
727 EXPECT_EQ(3, recur1(4));
730 // This code is copied from JITEventListenerTest, but it only runs once for all
731 // the tests in this directory. Everything seems fine, but that's strange
733 class JITEnvironment : public testing::Environment {
734 virtual void SetUp() {
735 // Required to create a JIT.
736 InitializeNativeTarget();
739 testing::Environment* const jit_env =
740 testing::AddGlobalTestEnvironment(new JITEnvironment);