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/BasicBlock.h"
13 #include "llvm/Constant.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/ExecutionEngine/JIT.h"
17 #include "llvm/ExecutionEngine/JITMemoryManager.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalValue.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/ModuleProvider.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Support/TypeBuilder.h"
26 #include "llvm/Target/TargetSelect.h"
27 #include "llvm/Type.h"
33 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
34 std::vector<const Type*> params;
35 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
37 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
38 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
39 IRBuilder<> builder(Entry);
40 Value *Load = builder.CreateLoad(G);
41 const Type *GTy = G->getType()->getElementType();
42 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
43 builder.CreateStore(Add, G);
44 builder.CreateRet(Add);
48 class JITTest : public testing::Test {
50 virtual void SetUp() {
51 M = new Module("<main>", Context);
53 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
54 .setErrorStr(&Error).create());
55 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
59 Module *M; // Owned by ExecutionEngine.
60 OwningPtr<ExecutionEngine> TheJIT;
63 // Regression test for a bug. The JIT used to allocate globals inside the same
64 // memory block used for the function, and when the function code was freed,
65 // the global was left in the same place. This test allocates a function
66 // that uses and global, deallocates it, and then makes sure that the global
67 // stays alive after that.
68 TEST(JIT, GlobalInFunction) {
70 Module *M = new Module("<main>", context);
71 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
73 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
74 // Tell the memory manager to poison freed memory so that accessing freed
75 // memory is more easily tested.
76 MemMgr->setPoisonMemory(true);
78 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
79 .setEngineKind(EngineKind::JIT)
81 .setJITMemoryManager(MemMgr)
82 // The next line enables the fix:
83 .setAllocateGVsWithCode(false)
87 // Create a global variable.
88 const Type *GTy = Type::getInt32Ty(context);
89 GlobalVariable *G = new GlobalVariable(
92 false, // Not constant.
93 GlobalValue::InternalLinkage,
94 Constant::getNullValue(GTy),
97 // Make a function that points to a global.
98 Function *F1 = makeReturnGlobal("F1", G, M);
100 // Get the pointer to the native code to force it to JIT the function and
101 // allocate space for the global.
103 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
105 // Since F1 was codegen'd, a pointer to G should be available.
106 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
107 ASSERT_NE((int32_t*)NULL, GPtr);
110 // F1() should increment G.
114 // Make a second function identical to the first, referring to the same
116 Function *F2 = makeReturnGlobal("F2", G, M);
118 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
120 // F2() should increment G.
125 JIT->freeMachineCodeForFunction(F1);
127 // F2() should *still* increment G.
132 int PlusOne(int arg) {
136 TEST_F(JITTest, FarCallToKnownFunction) {
137 // x86-64 can only make direct calls to functions within 32 bits of
138 // the current PC. To call anything farther away, we have to load
139 // the address into a register and call through the register. The
140 // current JIT does this by allocating a stub for any far call.
141 // There was a bug in which the JIT tried to emit a direct call when
142 // the target was already in the JIT's global mappings and lazy
143 // compilation was disabled.
145 Function *KnownFunction = Function::Create(
146 TypeBuilder<int(int), false>::get(Context),
147 GlobalValue::ExternalLinkage, "known", M);
148 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
150 // int test() { return known(7); }
151 Function *TestFunction = Function::Create(
152 TypeBuilder<int(), false>::get(Context),
153 GlobalValue::ExternalLinkage, "test", M);
154 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
155 IRBuilder<> Builder(Entry);
156 Value *result = Builder.CreateCall(
158 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
159 Builder.CreateRet(result);
161 TheJIT->EnableDlsymStubs(false);
162 TheJIT->DisableLazyCompilation();
163 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
164 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
165 // This used to crash in trying to call PlusOne().
166 EXPECT_EQ(8, TestFunctionPtr());
169 #if !defined(__arm__) && !defined(__ppc__)
170 // Test a function C which calls A and B which call each other.
171 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
172 TheJIT->DisableLazyCompilation();
174 const FunctionType *Func1Ty =
175 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
176 std::vector<const Type*> arg_types;
177 arg_types.push_back(Type::getInt1Ty(Context));
178 const FunctionType *FuncTy = FunctionType::get(
179 Type::getVoidTy(Context), arg_types, false);
180 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
182 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
184 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
186 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
187 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
188 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
189 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
190 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
191 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
192 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
194 // Make Func1 call Func2(0) and Func3(0).
195 IRBuilder<> Builder(Block1);
196 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
197 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
198 Builder.CreateRetVoid();
200 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
201 Builder.SetInsertPoint(Block2);
202 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
203 Builder.SetInsertPoint(True2);
204 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
205 Builder.CreateRetVoid();
206 Builder.SetInsertPoint(False2);
207 Builder.CreateRetVoid();
209 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
210 Builder.SetInsertPoint(Block3);
211 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
212 Builder.SetInsertPoint(True3);
213 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
214 Builder.CreateRetVoid();
215 Builder.SetInsertPoint(False3);
216 Builder.CreateRetVoid();
218 // Compile the function to native code
220 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
226 // Regression test for PR5162. This used to trigger an AssertingVH inside the
227 // JIT's Function to stub mapping.
228 TEST_F(JITTest, NonLazyLeaksNoStubs) {
229 TheJIT->DisableLazyCompilation();
231 // Create two functions with a single basic block each.
232 const FunctionType *FuncTy =
233 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
234 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
236 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
238 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
239 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
241 // The first function calls the second and returns the result
242 IRBuilder<> Builder(Block1);
243 Value *Result = Builder.CreateCall(Func2);
244 Builder.CreateRet(Result);
246 // The second function just returns a constant
247 Builder.SetInsertPoint(Block2);
248 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
250 // Compile the function to native code
251 (void)TheJIT->getPointerToFunction(Func1);
253 // Free the JIT state for the functions
254 TheJIT->freeMachineCodeForFunction(Func1);
255 TheJIT->freeMachineCodeForFunction(Func2);
257 // Delete the first function (and show that is has no users)
258 EXPECT_EQ(Func1->getNumUses(), 0u);
259 Func1->eraseFromParent();
261 // Delete the second function (and show that it has no users - it had one,
262 // func1 but that's gone now)
263 EXPECT_EQ(Func2->getNumUses(), 0u);
264 Func2->eraseFromParent();
267 // This code is copied from JITEventListenerTest, but it only runs once for all
268 // the tests in this directory. Everything seems fine, but that's strange
270 class JITEnvironment : public testing::Environment {
271 virtual void SetUp() {
272 // Required to create a JIT.
273 InitializeNativeTarget();
276 testing::Environment* const jit_env =
277 testing::AddGlobalTestEnvironment(new JITEnvironment);