blob: e47a4370aea0b4286b17bd8e8e704f1a924b8988 [file] [log] [blame]
Reid Kleckner4b1511b2009-07-18 00:42:18 +00001//===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
Jeffrey Yasskin489393d2009-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 Yasskin23e5fcf2009-10-23 22:37:43 +000012#include "llvm/Assembly/Parser.h"
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000013#include "llvm/BasicBlock.h"
14#include "llvm/Constant.h"
15#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/ExecutionEngine/JIT.h"
18#include "llvm/ExecutionEngine/JITMemoryManager.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalValue.h"
21#include "llvm/GlobalVariable.h"
Reid Kleckner4b1511b2009-07-18 00:42:18 +000022#include "llvm/LLVMContext.h"
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000023#include "llvm/Module.h"
24#include "llvm/ModuleProvider.h"
25#include "llvm/Support/IRBuilder.h"
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000026#include "llvm/Support/SourceMgr.h"
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000027#include "llvm/Support/TypeBuilder.h"
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000028#include "llvm/Target/TargetSelect.h"
29#include "llvm/Type.h"
30
31using namespace llvm;
32
33namespace {
34
35Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
36 std::vector<const Type*> params;
Owen Andersondebcb012009-07-29 22:17:13 +000037 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
Dan Gohmanc6f40b62009-07-11 13:56:14 +000038 params, false);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000039 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
Owen Anderson1d0be152009-08-13 21:58:54 +000040 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000041 IRBuilder<> builder(Entry);
42 Value *Load = builder.CreateLoad(G);
43 const Type *GTy = G->getType()->getElementType();
Owen Andersoneed707b2009-07-24 23:12:02 +000044 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000045 builder.CreateStore(Add, G);
46 builder.CreateRet(Add);
47 return F;
48}
49
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000050class JITTest : public testing::Test {
51 protected:
52 virtual void SetUp() {
53 M = new Module("<main>", Context);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000054 MP = new ExistingModuleProvider(M);
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000055 std::string Error;
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000056 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000057 .setErrorStr(&Error).create());
58 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
59 }
60
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000061 void LoadAssembly(const char *assembly) {
62 SMDiagnostic Error;
63 bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
64 std::string errMsg;
65 raw_string_ostream os(errMsg);
66 Error.Print("", os);
67 ASSERT_TRUE(success) << os.str();
68 }
69
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000070 LLVMContext Context;
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000071 Module *M; // Owned by MP.
72 ModuleProvider *MP; // Owned by ExecutionEngine.
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +000073 OwningPtr<ExecutionEngine> TheJIT;
74};
75
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000076// Regression test for a bug. The JIT used to allocate globals inside the same
77// memory block used for the function, and when the function code was freed,
78// the global was left in the same place. This test allocates a function
79// that uses and global, deallocates it, and then makes sure that the global
80// stays alive after that.
81TEST(JIT, GlobalInFunction) {
82 LLVMContext context;
83 Module *M = new Module("<main>", context);
84 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
85
86 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
87 // Tell the memory manager to poison freed memory so that accessing freed
88 // memory is more easily tested.
89 MemMgr->setPoisonMemory(true);
90 std::string Error;
Reid Kleckner4b1511b2009-07-18 00:42:18 +000091 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
Daniel Dunbard370d772009-07-18 06:08:49 +000092 .setEngineKind(EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +000093 .setErrorStr(&Error)
94 .setJITMemoryManager(MemMgr)
95 // The next line enables the fix:
96 .setAllocateGVsWithCode(false)
97 .create());
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000098 ASSERT_EQ(Error, "");
99
100 // Create a global variable.
Owen Anderson1d0be152009-08-13 21:58:54 +0000101 const Type *GTy = Type::getInt32Ty(context);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000102 GlobalVariable *G = new GlobalVariable(
103 *M,
104 GTy,
105 false, // Not constant.
106 GlobalValue::InternalLinkage,
Benjamin Kramerfeba7562009-07-31 20:56:31 +0000107 Constant::getNullValue(GTy),
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000108 "myglobal");
109
110 // Make a function that points to a global.
111 Function *F1 = makeReturnGlobal("F1", G, M);
112
113 // Get the pointer to the native code to force it to JIT the function and
114 // allocate space for the global.
Jeffrey Yasskin0f2ba782009-10-06 19:06:16 +0000115 void (*F1Ptr)() =
116 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000117
118 // Since F1 was codegen'd, a pointer to G should be available.
119 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
120 ASSERT_NE((int32_t*)NULL, GPtr);
121 EXPECT_EQ(0, *GPtr);
122
123 // F1() should increment G.
124 F1Ptr();
125 EXPECT_EQ(1, *GPtr);
126
127 // Make a second function identical to the first, referring to the same
128 // global.
129 Function *F2 = makeReturnGlobal("F2", G, M);
Jeffrey Yasskin0f2ba782009-10-06 19:06:16 +0000130 void (*F2Ptr)() =
131 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000132
133 // F2() should increment G.
134 F2Ptr();
135 EXPECT_EQ(2, *GPtr);
136
137 // Deallocate F1.
138 JIT->freeMachineCodeForFunction(F1);
139
140 // F2() should *still* increment G.
141 F2Ptr();
142 EXPECT_EQ(3, *GPtr);
143}
144
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000145int PlusOne(int arg) {
146 return arg + 1;
147}
148
149TEST_F(JITTest, FarCallToKnownFunction) {
150 // x86-64 can only make direct calls to functions within 32 bits of
151 // the current PC. To call anything farther away, we have to load
152 // the address into a register and call through the register. The
153 // current JIT does this by allocating a stub for any far call.
154 // There was a bug in which the JIT tried to emit a direct call when
155 // the target was already in the JIT's global mappings and lazy
156 // compilation was disabled.
157
158 Function *KnownFunction = Function::Create(
159 TypeBuilder<int(int), false>::get(Context),
160 GlobalValue::ExternalLinkage, "known", M);
161 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
162
163 // int test() { return known(7); }
164 Function *TestFunction = Function::Create(
165 TypeBuilder<int(), false>::get(Context),
166 GlobalValue::ExternalLinkage, "test", M);
167 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
168 IRBuilder<> Builder(Entry);
169 Value *result = Builder.CreateCall(
170 KnownFunction,
171 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
172 Builder.CreateRet(result);
173
174 TheJIT->EnableDlsymStubs(false);
175 TheJIT->DisableLazyCompilation();
176 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
177 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
178 // This used to crash in trying to call PlusOne().
179 EXPECT_EQ(8, TestFunctionPtr());
180}
181
Daniel Dunbarb576bea2009-10-20 05:33:23 +0000182#if !defined(__arm__) && !defined(__powerpc__) && !defined(__ppc__)
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000183// Test a function C which calls A and B which call each other.
184TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
185 TheJIT->DisableLazyCompilation();
186
187 const FunctionType *Func1Ty =
188 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
189 std::vector<const Type*> arg_types;
190 arg_types.push_back(Type::getInt1Ty(Context));
191 const FunctionType *FuncTy = FunctionType::get(
192 Type::getVoidTy(Context), arg_types, false);
193 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
194 "func1", M);
195 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
196 "func2", M);
197 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
198 "func3", M);
199 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
200 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
201 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
202 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
203 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
204 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
205 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
206
207 // Make Func1 call Func2(0) and Func3(0).
208 IRBuilder<> Builder(Block1);
209 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
210 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
211 Builder.CreateRetVoid();
212
213 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
214 Builder.SetInsertPoint(Block2);
215 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
216 Builder.SetInsertPoint(True2);
217 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
218 Builder.CreateRetVoid();
219 Builder.SetInsertPoint(False2);
220 Builder.CreateRetVoid();
221
222 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
223 Builder.SetInsertPoint(Block3);
224 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
225 Builder.SetInsertPoint(True3);
226 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
227 Builder.CreateRetVoid();
228 Builder.SetInsertPoint(False3);
229 Builder.CreateRetVoid();
230
231 // Compile the function to native code
232 void (*F1Ptr)() =
233 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
234
235 F1Ptr();
236}
237
238// Regression test for PR5162. This used to trigger an AssertingVH inside the
239// JIT's Function to stub mapping.
240TEST_F(JITTest, NonLazyLeaksNoStubs) {
241 TheJIT->DisableLazyCompilation();
242
243 // Create two functions with a single basic block each.
244 const FunctionType *FuncTy =
245 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
246 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
247 "func1", M);
248 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
249 "func2", M);
250 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
251 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
252
253 // The first function calls the second and returns the result
254 IRBuilder<> Builder(Block1);
255 Value *Result = Builder.CreateCall(Func2);
256 Builder.CreateRet(Result);
257
258 // The second function just returns a constant
259 Builder.SetInsertPoint(Block2);
260 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
261
262 // Compile the function to native code
263 (void)TheJIT->getPointerToFunction(Func1);
264
265 // Free the JIT state for the functions
266 TheJIT->freeMachineCodeForFunction(Func1);
267 TheJIT->freeMachineCodeForFunction(Func2);
268
269 // Delete the first function (and show that is has no users)
270 EXPECT_EQ(Func1->getNumUses(), 0u);
271 Func1->eraseFromParent();
272
273 // Delete the second function (and show that it has no users - it had one,
274 // func1 but that's gone now)
275 EXPECT_EQ(Func2->getNumUses(), 0u);
276 Func2->eraseFromParent();
277}
Benjamin Kramer06b386a2009-10-15 16:49:16 +0000278#endif
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000279
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000280TEST_F(JITTest, ModuleDeletion) {
281 LoadAssembly("define void @main() { "
282 " call i32 @computeVal() "
283 " ret void "
284 "} "
285 " "
286 "define internal i32 @computeVal() { "
287 " ret i32 0 "
288 "} ");
289 Function *func = M->getFunction("main");
290 TheJIT->getPointerToFunction(func);
291 TheJIT->deleteModuleProvider(MP);
292}
293
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000294// This code is copied from JITEventListenerTest, but it only runs once for all
295// the tests in this directory. Everything seems fine, but that's strange
296// behavior.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000297class JITEnvironment : public testing::Environment {
298 virtual void SetUp() {
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000299 // Required to create a JIT.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000300 InitializeNativeTarget();
301 }
302};
303testing::Environment* const jit_env =
304 testing::AddGlobalTestEnvironment(new JITEnvironment);
305
306}