blob: bed2d22f1cfa01e3146eabbe88a1cb36ba38ec5d [file] [log] [blame]
Reid Klecknerfa3585b2009-07-18 00:42:18 +00001//===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
Jeffrey Yasskin892956a2009-07-08 21:59:57 +00002//
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 "gtest/gtest.h"
11#include "llvm/ADT/OwningPtr.h"
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000012#include "llvm/ADT/SmallPtrSet.h"
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +000013#include "llvm/Assembly/Parser.h"
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000014#include "llvm/BasicBlock.h"
Jeffrey Yasskin922a76e2009-12-22 23:47:23 +000015#include "llvm/Bitcode/ReaderWriter.h"
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000016#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"
Reid Klecknerfa3585b2009-07-18 00:42:18 +000024#include "llvm/LLVMContext.h"
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000025#include "llvm/Module.h"
26#include "llvm/ModuleProvider.h"
27#include "llvm/Support/IRBuilder.h"
Jeffrey Yasskin922a76e2009-12-22 23:47:23 +000028#include "llvm/Support/MemoryBuffer.h"
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +000029#include "llvm/Support/SourceMgr.h"
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +000030#include "llvm/Support/TypeBuilder.h"
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000031#include "llvm/Target/TargetSelect.h"
32#include "llvm/Type.h"
33
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000034#include <vector>
35
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000036using namespace llvm;
37
38namespace {
39
40Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
41 std::vector<const Type*> params;
Owen Anderson6b6e2d92009-07-29 22:17:13 +000042 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
Dan Gohman1ee5b3b2009-07-11 13:56:14 +000043 params, false);
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000044 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
Owen Anderson35b47072009-08-13 21:58:54 +000045 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000046 IRBuilder<> builder(Entry);
47 Value *Load = builder.CreateLoad(G);
48 const Type *GTy = G->getType()->getElementType();
Owen Andersoneacb44d2009-07-24 23:12:02 +000049 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
Jeffrey Yasskin892956a2009-07-08 21:59:57 +000050 builder.CreateStore(Add, G);
51 builder.CreateRet(Add);
52 return F;
53}
54
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000055std::string DumpFunction(const Function *F) {
56 std::string Result;
57 raw_string_ostream(Result) << "" << *F;
58 return Result;
59}
60
Chris Lattner5c804552010-01-22 06:49:46 +000061#if 0
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000062class RecordingJITMemoryManager : public JITMemoryManager {
63 const OwningPtr<JITMemoryManager> Base;
64public:
65 RecordingJITMemoryManager()
66 : Base(JITMemoryManager::CreateDefaultMemManager()) {
Eric Christopherea644f72009-11-12 03:12:18 +000067 stubsAllocated = 0;
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000068 }
69
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(); }
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000075 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) {}
80 uint8_t *Result;
81 const Function *F;
82 std::string F_dump;
83 uintptr_t ActualSize;
84 uintptr_t ActualSizeResult;
85 };
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));
93 return Result;
94 }
Eric Christopherea644f72009-11-12 03:12:18 +000095 int stubsAllocated;
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000096 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
97 unsigned Alignment) {
Eric Christopherea644f72009-11-12 03:12:18 +000098 stubsAllocated++;
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +000099 return Base->allocateStub(F, StubSize, Alignment);
100 }
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) {}
106 const Function *F;
107 std::string F_dump;
108 uint8_t *FunctionStart;
109 uint8_t *FunctionEnd;
110 };
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);
117 }
118 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
119 return Base->allocateSpace(Size, Alignment);
120 }
121 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
122 return Base->allocateGlobal(Size, Alignment);
123 }
124 struct DeallocateFunctionBodyCall {
125 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
126 const void *Body;
127 };
128 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
129 virtual void deallocateFunctionBody(void *Body) {
130 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
131 Base->deallocateFunctionBody(Body);
132 }
133 struct DeallocateExceptionTableCall {
134 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
135 const void *ET;
136 };
137 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
138 virtual void deallocateExceptionTable(void *ET) {
139 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
140 Base->deallocateExceptionTable(ET);
141 }
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) {}
147 uint8_t *Result;
148 const Function *F;
149 std::string F_dump;
150 uintptr_t ActualSize;
151 uintptr_t ActualSizeResult;
152 };
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));
160 return Result;
161 }
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) {}
168 const Function *F;
169 std::string F_dump;
170 uint8_t *TableStart;
171 uint8_t *TableEnd;
172 uint8_t *FrameRegister;
173 };
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);
180 }
181};
Chris Lattner5c804552010-01-22 06:49:46 +0000182#endif
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000183
Jeffrey Yasskin922a76e2009-12-22 23:47:23 +0000184bool LoadAssemblyInto(Module *M, const char *assembly) {
185 SMDiagnostic Error;
186 bool success =
187 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
188 std::string errMsg;
189 raw_string_ostream os(errMsg);
190 Error.Print("", os);
191 EXPECT_TRUE(success) << os.str();
192 return success;
193}
194
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000195class JITTest : public testing::Test {
196 protected:
197 virtual void SetUp() {
198 M = new Module("<main>", Context);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000199 MP = new ExistingModuleProvider(M);
Chris Lattner5c804552010-01-22 06:49:46 +0000200#if 0
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000201 RJMM = new RecordingJITMemoryManager;
Jeffrey Yasskinf8f9acf2009-11-23 23:35:19 +0000202 RJMM->setPoisonMemory(true);
Chris Lattner5c804552010-01-22 06:49:46 +0000203#endif
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000204 std::string Error;
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000205 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
Chris Lattner5c804552010-01-22 06:49:46 +0000206#if 0
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000207 .setJITMemoryManager(RJMM)
Chris Lattner5c804552010-01-22 06:49:46 +0000208#endif
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000209 .setErrorStr(&Error).create());
210 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
211 }
212
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000213 void LoadAssembly(const char *assembly) {
Jeffrey Yasskin922a76e2009-12-22 23:47:23 +0000214 LoadAssemblyInto(M, assembly);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000215 }
216
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000217 LLVMContext Context;
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000218 Module *M; // Owned by MP.
219 ModuleProvider *MP; // Owned by ExecutionEngine.
Chris Lattner5c804552010-01-22 06:49:46 +0000220#if 0
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000221 RecordingJITMemoryManager *RJMM;
Chris Lattner5c804552010-01-22 06:49:46 +0000222#endif
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000223 OwningPtr<ExecutionEngine> TheJIT;
224};
225
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000226// 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.
231TEST(JIT, GlobalInFunction) {
232 LLVMContext context;
233 Module *M = new Module("<main>", context);
234 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
235
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);
240 std::string Error;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000241 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
Daniel Dunbarf32df062009-07-18 06:08:49 +0000242 .setEngineKind(EngineKind::JIT)
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000243 .setErrorStr(&Error)
244 .setJITMemoryManager(MemMgr)
245 // The next line enables the fix:
246 .setAllocateGVsWithCode(false)
247 .create());
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000248 ASSERT_EQ(Error, "");
249
250 // Create a global variable.
Owen Anderson35b47072009-08-13 21:58:54 +0000251 const Type *GTy = Type::getInt32Ty(context);
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000252 GlobalVariable *G = new GlobalVariable(
253 *M,
254 GTy,
255 false, // Not constant.
256 GlobalValue::InternalLinkage,
Benjamin Kramer76034802009-07-31 20:56:31 +0000257 Constant::getNullValue(GTy),
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000258 "myglobal");
259
260 // Make a function that points to a global.
261 Function *F1 = makeReturnGlobal("F1", G, M);
262
263 // Get the pointer to the native code to force it to JIT the function and
264 // allocate space for the global.
Jeffrey Yasskinabf70f82009-10-06 19:06:16 +0000265 void (*F1Ptr)() =
266 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000267
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);
271 EXPECT_EQ(0, *GPtr);
272
273 // F1() should increment G.
274 F1Ptr();
275 EXPECT_EQ(1, *GPtr);
276
277 // Make a second function identical to the first, referring to the same
278 // global.
279 Function *F2 = makeReturnGlobal("F2", G, M);
Jeffrey Yasskinabf70f82009-10-06 19:06:16 +0000280 void (*F2Ptr)() =
281 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000282
283 // F2() should increment G.
284 F2Ptr();
285 EXPECT_EQ(2, *GPtr);
286
287 // Deallocate F1.
288 JIT->freeMachineCodeForFunction(F1);
289
290 // F2() should *still* increment G.
291 F2Ptr();
292 EXPECT_EQ(3, *GPtr);
293}
294
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000295int PlusOne(int arg) {
296 return arg + 1;
297}
298
299TEST_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.
307
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);
312
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(
320 KnownFunction,
321 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
322 Builder.CreateRet(result);
323
Jeffrey Yasskin8c4e2232009-10-27 22:39:42 +0000324 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000325 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());
329}
330
Jeffrey Yasskinf9057462009-10-13 21:32:57 +0000331// Test a function C which calls A and B which call each other.
332TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
Jeffrey Yasskin8c4e2232009-10-27 22:39:42 +0000333 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskinf9057462009-10-13 21:32:57 +0000334
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,
342 "func1", M);
343 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
344 "func2", M);
345 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
346 "func3", M);
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);
354
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();
360
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();
369
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();
378
379 // Compile the function to native code
380 void (*F1Ptr)() =
381 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
382
383 F1Ptr();
384}
385
386// Regression test for PR5162. This used to trigger an AssertingVH inside the
387// JIT's Function to stub mapping.
388TEST_F(JITTest, NonLazyLeaksNoStubs) {
Jeffrey Yasskin8c4e2232009-10-27 22:39:42 +0000389 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskinf9057462009-10-13 21:32:57 +0000390
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,
395 "func1", M);
396 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
397 "func2", M);
398 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
399 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
400
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);
405
406 // The second function just returns a constant
407 Builder.SetInsertPoint(Block2);
408 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
409
410 // Compile the function to native code
411 (void)TheJIT->getPointerToFunction(Func1);
412
413 // Free the JIT state for the functions
414 TheJIT->freeMachineCodeForFunction(Func1);
415 TheJIT->freeMachineCodeForFunction(Func2);
416
417 // Delete the first function (and show that is has no users)
418 EXPECT_EQ(Func1->getNumUses(), 0u);
419 Func1->eraseFromParent();
420
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();
425}
426
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000427TEST_F(JITTest, ModuleDeletion) {
Jeffrey Yasskin52352152009-10-28 00:28:31 +0000428 TheJIT->DisableLazyCompilation(false);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000429 LoadAssembly("define void @main() { "
430 " call i32 @computeVal() "
431 " ret void "
432 "} "
433 " "
434 "define internal i32 @computeVal() { "
435 " ret i32 0 "
436 "} ");
437 Function *func = M->getFunction("main");
438 TheJIT->getPointerToFunction(func);
439 TheJIT->deleteModuleProvider(MP);
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000440
Chris Lattner5c804552010-01-22 06:49:46 +0000441#if 0
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000442 SmallPtrSet<const void*, 2> FunctionsDeallocated;
443 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
444 i != e; ++i) {
445 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
446 }
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;
451 }
452 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
453 RJMM->deallocateFunctionBodyCalls.size());
454
455 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
Jeffrey Yasskin223f53f2009-11-11 05:30:02 +0000456 unsigned NumTablesDeallocated = 0;
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000457 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
458 i != e; ++i) {
459 ExceptionTablesDeallocated.insert(
460 RJMM->deallocateExceptionTableCalls[i].ET);
Jeffrey Yasskin223f53f2009-11-11 05:30:02 +0000461 if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
462 // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
463 // appear in startExceptionTableCalls.
464 NumTablesDeallocated++;
465 }
Jeffrey Yasskin1291fce62009-10-27 00:03:05 +0000466 }
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;
472 }
473 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
Jeffrey Yasskin223f53f2009-11-11 05:30:02 +0000474 NumTablesDeallocated);
Chris Lattner5c804552010-01-22 06:49:46 +0000475#endif
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000476}
477
Jeffrey Yasskinde17b232009-11-24 02:11:14 +0000478// 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__)
Eric Christopherea644f72009-11-12 03:12:18 +0000482typedef int (*FooPtr) ();
483
484TEST_F(JITTest, NoStubs) {
485 LoadAssembly("define void @bar() {"
486 "entry: "
487 "ret void"
488 "}"
489 " "
490 "define i32 @foo() {"
491 "entry:"
492 "call void @bar()"
493 "ret i32 undef"
494 "}"
495 " "
496 "define i32 @main() {"
497 "entry:"
498 "%0 = call i32 @foo()"
499 "call void @bar()"
500 "ret i32 undef"
501 "}");
502 Function *foo = M->getFunction("foo");
503 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
504 FooPtr ptr = (FooPtr)(tmp);
505
506 (ptr)();
507
508 // We should now allocate no more stubs, we have the code to foo
509 // and the existing stub for bar.
Chris Lattner5c804552010-01-22 06:49:46 +0000510#if 0
Eric Christopherea644f72009-11-12 03:12:18 +0000511 int stubsBefore = RJMM->stubsAllocated;
Chris Lattner5c804552010-01-22 06:49:46 +0000512#endif
Eric Christopherea644f72009-11-12 03:12:18 +0000513 Function *func = M->getFunction("main");
514 TheJIT->getPointerToFunction(func);
515
516 Function *bar = M->getFunction("bar");
517 TheJIT->getPointerToFunction(bar);
518
Chris Lattner5c804552010-01-22 06:49:46 +0000519#if 0
Eric Christopherea644f72009-11-12 03:12:18 +0000520 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
Chris Lattner5c804552010-01-22 06:49:46 +0000521#endif
Eric Christopherea644f72009-11-12 03:12:18 +0000522}
Jeffrey Yasskinde17b232009-11-24 02:11:14 +0000523#endif // !ARM && !PPC
Jeffrey Yasskinf8f9acf2009-11-23 23:35:19 +0000524
525TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
526 TheJIT->DisableLazyCompilation(true);
527 LoadAssembly("define i8()* @get_foo_addr() { "
528 " ret i8()* @foo "
529 "} "
530 " "
531 "define i8 @foo() { "
532 " ret i8 42 "
533 "} ");
534 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
535
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();
540
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);
544
545 // Check by calling the reported address of foo.
546 EXPECT_EQ(42, foo_addr());
547
548 // The reported address should also be the same as the result of a subsequent
549 // getPointerToFunction(foo).
550#if 0
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);
Bill Wendlingee787d22009-11-13 21:58:54 +0000556#endif
Jeffrey Yasskinf8f9acf2009-11-23 23:35:19 +0000557}
Eric Christopherea644f72009-11-12 03:12:18 +0000558
Jeffrey Yasskind2329aa2009-12-23 00:58:02 +0000559// ARM doesn't have an implementation of replaceMachineCodeForFunction(), so
560// recompileAndRelinkFunction doesn't work.
561#if !defined(__arm__)
Jeffrey Yasskine4184542009-12-22 23:18:18 +0000562TEST_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);
569
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());
575
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
583 // old one.
584 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
585 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
586
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";
591}
Jeffrey Yasskind2329aa2009-12-23 00:58:02 +0000592#endif // !defined(__arm__)
Jeffrey Yasskine4184542009-12-22 23:18:18 +0000593
Jeffrey Yasskin7fe6f872009-12-13 20:30:32 +0000594} // 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
597// definition.
598extern "C" int32_t JITTest_AvailableExternallyGlobal;
599int32_t JITTest_AvailableExternallyGlobal = 42;
600namespace {
601
602TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
603 TheJIT->DisableLazyCompilation(true);
604 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
605 " available_externally global i32 7 "
606 " "
607 "define i32 @loader() { "
608 " %result = load i32* @JITTest_AvailableExternallyGlobal "
609 " ret i32 %result "
610 "} ");
611 Function *loaderIR = M->getFunction("loader");
612
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.";
617}
618
Jeffrey Yasskin898fb792009-12-17 21:35:29 +0000619} // 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
622// definition.
623extern "C" int32_t JITTest_AvailableExternallyFunction() {
624 return 42;
625}
626namespace {
627
628TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
629 TheJIT->DisableLazyCompilation(true);
630 LoadAssembly("define available_externally i32 "
631 " @JITTest_AvailableExternallyFunction() { "
632 " ret i32 7 "
633 "} "
634 " "
635 "define i32 @func() { "
636 " %result = tail call i32 "
637 " @JITTest_AvailableExternallyFunction() "
638 " ret i32 %result "
639 "} ");
640 Function *funcIR = M->getFunction("func");
641
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.";
646}
647
Jeffrey Yasskin922a76e2009-12-22 23:47:23 +0000648// Converts the LLVM assembly to bitcode and returns it in a std::string. An
649// empty string indicates an error.
650std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
651 Module TempModule("TempModule", Context);
652 if (!LoadAssemblyInto(&TempModule, Assembly)) {
653 return "";
654 }
655
656 std::string Result;
657 raw_string_ostream OS(Result);
658 WriteBitcodeToFile(&TempModule, OS);
659 OS.flush();
660 return Result;
661}
662
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.
667ExecutionEngine *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(),
673 "Bitcode for test");
674 std::string errMsg;
675 MP = getBitcodeModuleProvider(BitcodeBuffer, Context, &errMsg);
676 if (MP == NULL) {
677 ADD_FAILURE() << errMsg;
678 delete BitcodeBuffer;
679 return NULL;
680 }
681 ExecutionEngine *TheJIT = EngineBuilder(MP)
682 .setEngineKind(EngineKind::JIT)
683 .setErrorStr(&errMsg)
684 .create();
685 if (TheJIT == NULL) {
686 ADD_FAILURE() << errMsg;
687 delete MP;
688 MP = NULL;
689 return NULL;
690 }
691 return TheJIT;
692}
693
694TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
695 LLVMContext Context;
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 "
701 "done: "
702 " ret i32 3 "
703 "notdone: "
704 " %am1 = sub i32 %a, 1 "
705 " %result = call i32 @recur2(i32 %am1) "
706 " ret i32 %result "
707 "} "
708 " "
709 "define i32 @recur2(i32 %b) { "
710 " %result = call i32 @recur1(i32 %b) "
711 " ret i32 %result "
712 "} ");
713 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
714 ModuleProvider *MP;
715 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, MP));
716 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
717 TheJIT->DisableLazyCompilation(true);
718
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());
724
725 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
726 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
727 EXPECT_EQ(3, recur1(4));
728}
729
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000730// 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
732// behavior.
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000733class JITEnvironment : public testing::Environment {
734 virtual void SetUp() {
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000735 // Required to create a JIT.
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000736 InitializeNativeTarget();
737 }
738};
739testing::Environment* const jit_env =
740 testing::AddGlobalTestEnvironment(new JITEnvironment);
741
742}