blob: 30bfffbf93bf163a3c04c84556008a2fbb610f93 [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
Chandler Carruth5a88dda2012-12-04 10:23:08 +000010#include "llvm/ExecutionEngine/JIT.h"
11#include "llvm/ADT/OwningPtr.h"
12#include "llvm/ADT/SmallPtrSet.h"
13#include "llvm/Assembly/Parser.h"
Chandler Carruth5a88dda2012-12-04 10:23:08 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chandler Carruth5a88dda2012-12-04 10:23:08 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#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"
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +000028#include "llvm/Support/MemoryBuffer.h"
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000029#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000030#include "llvm/Support/TargetSelect.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000031#include "gtest/gtest.h"
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +000032#include <vector>
33
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000034using namespace llvm;
35
36namespace {
37
Ulrich Weigand1218bc42013-05-06 16:10:35 +000038// Tests on ARM and PowerPC disabled as we're running the old jit
39#if !defined(__arm__) && !defined(__powerpc__)
40
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000041Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
Jay Foad5fdd6c82011-07-12 14:06:48 +000042 std::vector<Type*> params;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000043 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
Dan Gohmanc6f40b62009-07-11 13:56:14 +000044 params, false);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000045 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
Owen Anderson1d0be152009-08-13 21:58:54 +000046 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000047 IRBuilder<> builder(Entry);
48 Value *Load = builder.CreateLoad(G);
Chris Lattnerdb125cf2011-07-18 04:54:35 +000049 Type *GTy = G->getType()->getElementType();
Owen Andersoneed707b2009-07-24 23:12:02 +000050 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +000051 builder.CreateStore(Add, G);
52 builder.CreateRet(Add);
53 return F;
54}
55
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +000056std::string DumpFunction(const Function *F) {
57 std::string Result;
58 raw_string_ostream(Result) << "" << *F;
59 return Result;
60}
61
62class RecordingJITMemoryManager : public JITMemoryManager {
63 const OwningPtr<JITMemoryManager> Base;
64public:
65 RecordingJITMemoryManager()
66 : Base(JITMemoryManager::CreateDefaultMemManager()) {
Eric Christopher116664a2009-11-12 03:12:18 +000067 stubsAllocated = 0;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +000068 }
Danil Malyshev30b9e322012-03-28 21:46:36 +000069 virtual void *getPointerToNamedFunction(const std::string &Name,
70 bool AbortOnFailure = true) {
71 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
72 }
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +000073
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(); }
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +000079 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) {}
84 uint8_t *Result;
85 const Function *F;
86 std::string F_dump;
87 uintptr_t ActualSize;
88 uintptr_t ActualSizeResult;
89 };
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));
97 return Result;
98 }
Eric Christopher116664a2009-11-12 03:12:18 +000099 int stubsAllocated;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000100 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
101 unsigned Alignment) {
Eric Christopher116664a2009-11-12 03:12:18 +0000102 stubsAllocated++;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000103 return Base->allocateStub(F, StubSize, Alignment);
104 }
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) {}
110 const Function *F;
111 std::string F_dump;
112 uint8_t *FunctionStart;
113 uint8_t *FunctionEnd;
114 };
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);
121 }
Jim Grosbach61425c02012-01-16 22:26:39 +0000122 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Andrew Kaylor53608a32012-11-15 23:50:01 +0000123 unsigned SectionID, bool IsReadOnly) {
124 return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
Jim Grosbach61425c02012-01-16 22:26:39 +0000125 }
126 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
127 unsigned SectionID) {
128 return Base->allocateCodeSection(Size, Alignment, SectionID);
129 }
Andrew Kaylor53608a32012-11-15 23:50:01 +0000130 virtual bool applyPermissions(std::string *ErrMsg) { return false; }
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000131 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
132 return Base->allocateSpace(Size, Alignment);
133 }
134 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
135 return Base->allocateGlobal(Size, Alignment);
136 }
137 struct DeallocateFunctionBodyCall {
138 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
139 const void *Body;
140 };
141 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
142 virtual void deallocateFunctionBody(void *Body) {
143 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
144 Base->deallocateFunctionBody(Body);
145 }
146 struct DeallocateExceptionTableCall {
147 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
148 const void *ET;
149 };
150 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
151 virtual void deallocateExceptionTable(void *ET) {
152 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
153 Base->deallocateExceptionTable(ET);
154 }
155 struct StartExceptionTableCall {
156 StartExceptionTableCall(uint8_t *Result, const Function *F,
157 uintptr_t ActualSize, uintptr_t ActualSizeResult)
158 : Result(Result), F(F), F_dump(DumpFunction(F)),
159 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
160 uint8_t *Result;
161 const Function *F;
162 std::string F_dump;
163 uintptr_t ActualSize;
164 uintptr_t ActualSizeResult;
165 };
166 std::vector<StartExceptionTableCall> startExceptionTableCalls;
Eli Benderskydced3cd2013-01-11 16:33:30 +0000167 virtual uint8_t *startExceptionTable(const Function *F,
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000168 uintptr_t &ActualSize) {
169 uintptr_t InitialActualSize = ActualSize;
170 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
171 startExceptionTableCalls.push_back(
172 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
173 return Result;
174 }
175 struct EndExceptionTableCall {
176 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
177 uint8_t *TableEnd, uint8_t* FrameRegister)
178 : F(F), F_dump(DumpFunction(F)),
179 TableStart(TableStart), TableEnd(TableEnd),
180 FrameRegister(FrameRegister) {}
181 const Function *F;
182 std::string F_dump;
183 uint8_t *TableStart;
184 uint8_t *TableEnd;
185 uint8_t *FrameRegister;
186 };
187 std::vector<EndExceptionTableCall> endExceptionTableCalls;
188 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
189 uint8_t *TableEnd, uint8_t* FrameRegister) {
190 endExceptionTableCalls.push_back(
191 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
192 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
193 }
194};
195
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000196bool LoadAssemblyInto(Module *M, const char *assembly) {
197 SMDiagnostic Error;
198 bool success =
199 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
200 std::string errMsg;
201 raw_string_ostream os(errMsg);
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000202 Error.print("", os);
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000203 EXPECT_TRUE(success) << os.str();
204 return success;
205}
206
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000207class JITTest : public testing::Test {
208 protected:
Eli Benderskydced3cd2013-01-11 16:33:30 +0000209 virtual RecordingJITMemoryManager *createMemoryManager() {
210 return new RecordingJITMemoryManager;
211 }
212
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000213 virtual void SetUp() {
214 M = new Module("<main>", Context);
Eli Benderskydced3cd2013-01-11 16:33:30 +0000215 RJMM = createMemoryManager();
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000216 RJMM->setPoisonMemory(true);
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000217 std::string Error;
Eli Benderskydced3cd2013-01-11 16:33:30 +0000218 TargetOptions Options;
219 Options.JITExceptionHandling = true;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000220 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000221 .setJITMemoryManager(RJMM)
Eli Benderskydced3cd2013-01-11 16:33:30 +0000222 .setErrorStr(&Error)
223 .setTargetOptions(Options).create());
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000224 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
225 }
226
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000227 void LoadAssembly(const char *assembly) {
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000228 LoadAssemblyInto(M, assembly);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000229 }
230
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000231 LLVMContext Context;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000232 Module *M; // Owned by ExecutionEngine.
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000233 RecordingJITMemoryManager *RJMM;
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000234 OwningPtr<ExecutionEngine> TheJIT;
235};
236
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000237// Regression test for a bug. The JIT used to allocate globals inside the same
238// memory block used for the function, and when the function code was freed,
239// the global was left in the same place. This test allocates a function
240// that uses and global, deallocates it, and then makes sure that the global
241// stays alive after that.
242TEST(JIT, GlobalInFunction) {
243 LLVMContext context;
244 Module *M = new Module("<main>", context);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000245
246 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
247 // Tell the memory manager to poison freed memory so that accessing freed
248 // memory is more easily tested.
249 MemMgr->setPoisonMemory(true);
250 std::string Error;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000251 OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
Daniel Dunbard370d772009-07-18 06:08:49 +0000252 .setEngineKind(EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000253 .setErrorStr(&Error)
254 .setJITMemoryManager(MemMgr)
255 // The next line enables the fix:
256 .setAllocateGVsWithCode(false)
257 .create());
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000258 ASSERT_EQ(Error, "");
259
260 // Create a global variable.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261 Type *GTy = Type::getInt32Ty(context);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000262 GlobalVariable *G = new GlobalVariable(
263 *M,
264 GTy,
265 false, // Not constant.
266 GlobalValue::InternalLinkage,
Benjamin Kramerfeba7562009-07-31 20:56:31 +0000267 Constant::getNullValue(GTy),
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000268 "myglobal");
269
270 // Make a function that points to a global.
271 Function *F1 = makeReturnGlobal("F1", G, M);
272
273 // Get the pointer to the native code to force it to JIT the function and
274 // allocate space for the global.
Jeffrey Yasskin0f2ba782009-10-06 19:06:16 +0000275 void (*F1Ptr)() =
276 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000277
278 // Since F1 was codegen'd, a pointer to G should be available.
279 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
280 ASSERT_NE((int32_t*)NULL, GPtr);
281 EXPECT_EQ(0, *GPtr);
282
283 // F1() should increment G.
284 F1Ptr();
285 EXPECT_EQ(1, *GPtr);
286
287 // Make a second function identical to the first, referring to the same
288 // global.
289 Function *F2 = makeReturnGlobal("F2", G, M);
Jeffrey Yasskin0f2ba782009-10-06 19:06:16 +0000290 void (*F2Ptr)() =
291 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000292
293 // F2() should increment G.
294 F2Ptr();
295 EXPECT_EQ(2, *GPtr);
296
297 // Deallocate F1.
298 JIT->freeMachineCodeForFunction(F1);
299
300 // F2() should *still* increment G.
301 F2Ptr();
302 EXPECT_EQ(3, *GPtr);
303}
304
Eli Benderskydced3cd2013-01-11 16:33:30 +0000305// Regression test for a bug. The JITEmitter wasn't checking to verify that
306// it hadn't run out of space while generating the DWARF exception information
307// for an emitted function.
308
309class ExceptionMemoryManagerMock : public RecordingJITMemoryManager {
310 public:
311 virtual uint8_t *startExceptionTable(const Function *F,
312 uintptr_t &ActualSize) {
313 // force an insufficient size the first time through.
314 bool ChangeActualSize = false;
315 if (ActualSize == 0)
316 ChangeActualSize = true;;
317 uint8_t *result =
318 RecordingJITMemoryManager::startExceptionTable(F, ActualSize);
319 if (ChangeActualSize)
320 ActualSize = 1;
321 return result;
322 }
323};
324
325class JITExceptionMemoryTest : public JITTest {
326 protected:
327 virtual RecordingJITMemoryManager *createMemoryManager() {
328 return new ExceptionMemoryManagerMock;
329 }
330};
331
332TEST_F(JITExceptionMemoryTest, ExceptionTableOverflow) {
333 Function *F = Function::Create(TypeBuilder<void(void), false>::get(Context),
334 Function::ExternalLinkage,
335 "func1", M);
336 BasicBlock *Block = BasicBlock::Create(Context, "block", F);
337 IRBuilder<> Builder(Block);
338 Builder.CreateRetVoid();
339 TheJIT->getPointerToFunction(F);
340 ASSERT_TRUE(RJMM->startExceptionTableCalls.size() == 2);
341 ASSERT_TRUE(RJMM->deallocateExceptionTableCalls.size() == 1);
342 ASSERT_TRUE(RJMM->endExceptionTableCalls.size() == 1);
343}
344
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000345int PlusOne(int arg) {
346 return arg + 1;
347}
348
349TEST_F(JITTest, FarCallToKnownFunction) {
350 // x86-64 can only make direct calls to functions within 32 bits of
351 // the current PC. To call anything farther away, we have to load
352 // the address into a register and call through the register. The
353 // current JIT does this by allocating a stub for any far call.
354 // There was a bug in which the JIT tried to emit a direct call when
355 // the target was already in the JIT's global mappings and lazy
356 // compilation was disabled.
357
358 Function *KnownFunction = Function::Create(
359 TypeBuilder<int(int), false>::get(Context),
360 GlobalValue::ExternalLinkage, "known", M);
361 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
362
363 // int test() { return known(7); }
364 Function *TestFunction = Function::Create(
365 TypeBuilder<int(), false>::get(Context),
366 GlobalValue::ExternalLinkage, "test", M);
367 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
368 IRBuilder<> Builder(Entry);
369 Value *result = Builder.CreateCall(
370 KnownFunction,
371 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
372 Builder.CreateRet(result);
373
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000374 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000375 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
376 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
377 // This used to crash in trying to call PlusOne().
378 EXPECT_EQ(8, TestFunctionPtr());
379}
380
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000381// Test a function C which calls A and B which call each other.
382TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000383 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000384
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000385 FunctionType *Func1Ty =
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000386 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
Jay Foad5fdd6c82011-07-12 14:06:48 +0000387 std::vector<Type*> arg_types;
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000388 arg_types.push_back(Type::getInt1Ty(Context));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000389 FunctionType *FuncTy = FunctionType::get(
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000390 Type::getVoidTy(Context), arg_types, false);
391 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
392 "func1", M);
393 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
394 "func2", M);
395 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
396 "func3", M);
397 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
398 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
399 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
400 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
401 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
402 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
403 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
404
405 // Make Func1 call Func2(0) and Func3(0).
406 IRBuilder<> Builder(Block1);
407 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
408 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
409 Builder.CreateRetVoid();
410
411 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
412 Builder.SetInsertPoint(Block2);
413 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
414 Builder.SetInsertPoint(True2);
415 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
416 Builder.CreateRetVoid();
417 Builder.SetInsertPoint(False2);
418 Builder.CreateRetVoid();
419
420 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
421 Builder.SetInsertPoint(Block3);
422 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
423 Builder.SetInsertPoint(True3);
424 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
425 Builder.CreateRetVoid();
426 Builder.SetInsertPoint(False3);
427 Builder.CreateRetVoid();
428
429 // Compile the function to native code
430 void (*F1Ptr)() =
431 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
432
433 F1Ptr();
434}
435
436// Regression test for PR5162. This used to trigger an AssertingVH inside the
437// JIT's Function to stub mapping.
438TEST_F(JITTest, NonLazyLeaksNoStubs) {
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000439 TheJIT->DisableLazyCompilation(true);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000440
441 // Create two functions with a single basic block each.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000442 FunctionType *FuncTy =
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000443 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
444 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
445 "func1", M);
446 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
447 "func2", M);
448 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
449 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
450
451 // The first function calls the second and returns the result
452 IRBuilder<> Builder(Block1);
453 Value *Result = Builder.CreateCall(Func2);
454 Builder.CreateRet(Result);
455
456 // The second function just returns a constant
457 Builder.SetInsertPoint(Block2);
458 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
459
460 // Compile the function to native code
461 (void)TheJIT->getPointerToFunction(Func1);
462
463 // Free the JIT state for the functions
464 TheJIT->freeMachineCodeForFunction(Func1);
465 TheJIT->freeMachineCodeForFunction(Func2);
466
467 // Delete the first function (and show that is has no users)
468 EXPECT_EQ(Func1->getNumUses(), 0u);
469 Func1->eraseFromParent();
470
471 // Delete the second function (and show that it has no users - it had one,
472 // func1 but that's gone now)
473 EXPECT_EQ(Func2->getNumUses(), 0u);
474 Func2->eraseFromParent();
475}
476
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000477TEST_F(JITTest, ModuleDeletion) {
Jeffrey Yasskinb2352242009-10-28 00:28:31 +0000478 TheJIT->DisableLazyCompilation(false);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000479 LoadAssembly("define void @main() { "
480 " call i32 @computeVal() "
481 " ret void "
482 "} "
483 " "
484 "define internal i32 @computeVal() { "
485 " ret i32 0 "
486 "} ");
487 Function *func = M->getFunction("main");
488 TheJIT->getPointerToFunction(func);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000489 TheJIT->removeModule(M);
490 delete M;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000491
492 SmallPtrSet<const void*, 2> FunctionsDeallocated;
493 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
494 i != e; ++i) {
495 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
496 }
497 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
498 EXPECT_TRUE(FunctionsDeallocated.count(
499 RJMM->startFunctionBodyCalls[i].Result))
500 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
501 }
502 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
503 RJMM->deallocateFunctionBodyCalls.size());
504
505 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
Jeffrey Yasskinb069c912009-11-11 05:30:02 +0000506 unsigned NumTablesDeallocated = 0;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000507 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
508 i != e; ++i) {
509 ExceptionTablesDeallocated.insert(
510 RJMM->deallocateExceptionTableCalls[i].ET);
Jeffrey Yasskinb069c912009-11-11 05:30:02 +0000511 if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
512 // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
513 // appear in startExceptionTableCalls.
514 NumTablesDeallocated++;
515 }
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000516 }
517 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
518 EXPECT_TRUE(ExceptionTablesDeallocated.count(
519 RJMM->startExceptionTableCalls[i].Result))
520 << "Function's exception table leaked: \n"
521 << RJMM->startExceptionTableCalls[i].F_dump;
522 }
523 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
Jeffrey Yasskinb069c912009-11-11 05:30:02 +0000524 NumTablesDeallocated);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000525}
526
Simon Atanasyand9389352012-05-16 19:07:55 +0000527// ARM, MIPS and PPC still emit stubs for calls since the target may be
528// too far away to call directly. This #if can probably be removed when
Jeffrey Yasskin630382a2009-11-24 02:11:14 +0000529// http://llvm.org/PR5201 is fixed.
Simon Atanasyand9389352012-05-16 19:07:55 +0000530#if !defined(__arm__) && !defined(__mips__) && \
531 !defined(__powerpc__) && !defined(__ppc__)
Eric Christopher116664a2009-11-12 03:12:18 +0000532typedef int (*FooPtr) ();
533
534TEST_F(JITTest, NoStubs) {
535 LoadAssembly("define void @bar() {"
536 "entry: "
537 "ret void"
538 "}"
539 " "
540 "define i32 @foo() {"
541 "entry:"
542 "call void @bar()"
543 "ret i32 undef"
544 "}"
545 " "
546 "define i32 @main() {"
547 "entry:"
548 "%0 = call i32 @foo()"
549 "call void @bar()"
550 "ret i32 undef"
551 "}");
552 Function *foo = M->getFunction("foo");
553 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
554 FooPtr ptr = (FooPtr)(tmp);
555
556 (ptr)();
557
558 // We should now allocate no more stubs, we have the code to foo
559 // and the existing stub for bar.
560 int stubsBefore = RJMM->stubsAllocated;
561 Function *func = M->getFunction("main");
562 TheJIT->getPointerToFunction(func);
563
564 Function *bar = M->getFunction("bar");
565 TheJIT->getPointerToFunction(bar);
566
567 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
568}
Jeffrey Yasskin630382a2009-11-24 02:11:14 +0000569#endif // !ARM && !PPC
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000570
571TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
572 TheJIT->DisableLazyCompilation(true);
573 LoadAssembly("define i8()* @get_foo_addr() { "
574 " ret i8()* @foo "
575 "} "
576 " "
577 "define i8 @foo() { "
578 " ret i8 42 "
579 "} ");
580 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
581
582 typedef char(*fooT)();
583 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
584 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
585 fooT foo_addr = get_foo_addr();
586
587 // Now free get_foo_addr. This should not free the machine code for foo or
588 // any call stub returned as foo's canonical address.
589 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
590
591 // Check by calling the reported address of foo.
592 EXPECT_EQ(42, foo_addr());
593
594 // The reported address should also be the same as the result of a subsequent
595 // getPointerToFunction(foo).
596#if 0
597 // Fails until PR5126 is fixed:
598 Function *F_foo = M->getFunction("foo");
599 fooT foo = reinterpret_cast<fooT>(
600 (intptr_t)TheJIT->getPointerToFunction(F_foo));
601 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
Bill Wendling0c2749f2009-11-13 21:58:54 +0000602#endif
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000603}
Eric Christopher116664a2009-11-12 03:12:18 +0000604
Ulrich Weigand1218bc42013-05-06 16:10:35 +0000605// ARM does not have an implementation of replaceMachineCodeForFunction(),
606// so recompileAndRelinkFunction doesn't work.
607#if !defined(__arm__)
Jeffrey Yasskin92fdf452009-12-22 23:18:18 +0000608TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
609 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
610 GlobalValue::ExternalLinkage, "test", M);
611 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
612 IRBuilder<> Builder(Entry);
613 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
614 Builder.CreateRet(Val);
615
616 TheJIT->DisableLazyCompilation(true);
617 // Compile the function once, and make sure it works.
618 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
619 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
620 EXPECT_EQ(1, OrigFPtr());
621
622 // Now change the function to return a different value.
623 Entry->eraseFromParent();
624 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
625 Builder.SetInsertPoint(NewEntry);
626 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
627 Builder.CreateRet(Val);
628 // Recompile it, which should produce a new function pointer _and_ update the
629 // old one.
630 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
631 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
632
633 EXPECT_EQ(2, NewFPtr())
634 << "The new pointer should call the new version of the function";
635 EXPECT_EQ(2, OrigFPtr())
636 << "The old pointer's target should now jump to the new version";
637}
Ulrich Weigand1218bc42013-05-06 16:10:35 +0000638#endif // !defined(__arm__)
Jeffrey Yasskin92fdf452009-12-22 23:18:18 +0000639
Jeffrey Yasskin898e9df2009-12-13 20:30:32 +0000640} // anonymous namespace
641// This variable is intentionally defined differently in the statically-compiled
642// program from the IR input to the JIT to assert that the JIT doesn't use its
643// definition.
644extern "C" int32_t JITTest_AvailableExternallyGlobal;
Bill Wendling80668fb2012-10-17 08:08:06 +0000645int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
Jeffrey Yasskin898e9df2009-12-13 20:30:32 +0000646namespace {
647
648TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
649 TheJIT->DisableLazyCompilation(true);
650 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
651 " available_externally global i32 7 "
652 " "
653 "define i32 @loader() { "
654 " %result = load i32* @JITTest_AvailableExternallyGlobal "
655 " ret i32 %result "
656 "} ");
657 Function *loaderIR = M->getFunction("loader");
658
659 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
660 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
661 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
662 << " not 7 from the IR version.";
663}
Jeffrey Yasskinaad0d522009-12-17 21:35:29 +0000664} // anonymous namespace
665// This function is intentionally defined differently in the statically-compiled
666// program from the IR input to the JIT to assert that the JIT doesn't use its
667// definition.
NAKAMURA Takumi8ab27a32012-10-12 08:09:29 +0000668extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
NAKAMURA Takumi97eb05b2012-10-12 01:34:07 +0000669extern "C" int32_t JITTest_AvailableExternallyFunction() {
Jeffrey Yasskinaad0d522009-12-17 21:35:29 +0000670 return 42;
671}
672namespace {
673
674TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
675 TheJIT->DisableLazyCompilation(true);
676 LoadAssembly("define available_externally i32 "
677 " @JITTest_AvailableExternallyFunction() { "
678 " ret i32 7 "
679 "} "
680 " "
681 "define i32 @func() { "
682 " %result = tail call i32 "
683 " @JITTest_AvailableExternallyFunction() "
684 " ret i32 %result "
685 "} ");
686 Function *funcIR = M->getFunction("func");
687
688 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
689 (intptr_t)TheJIT->getPointerToFunction(funcIR));
690 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
691 << " not 7 from the IR version.";
692}
693
Jeffrey Yasskin39c75f22010-03-04 19:45:09 +0000694TEST_F(JITTest, EscapedLazyStubStillCallable) {
695 TheJIT->DisableLazyCompilation(false);
696 LoadAssembly("define internal i32 @stubbed() { "
697 " ret i32 42 "
698 "} "
699 " "
700 "define i32()* @get_stub() { "
701 " ret i32()* @stubbed "
702 "} ");
703 typedef int32_t(*StubTy)();
704
705 // Call get_stub() to get the address of @stubbed without actually JITting it.
706 Function *get_stubIR = M->getFunction("get_stub");
707 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
708 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
709 StubTy stubbed = get_stub();
710 // Now get_stubIR is the only reference to stubbed's stub.
711 get_stubIR->eraseFromParent();
712 // Now there are no references inside the JIT, but we've got a pointer outside
713 // it. The stub should be callable and return the right value.
714 EXPECT_EQ(42, stubbed());
715}
716
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000717// Converts the LLVM assembly to bitcode and returns it in a std::string. An
718// empty string indicates an error.
719std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
720 Module TempModule("TempModule", Context);
721 if (!LoadAssemblyInto(&TempModule, Assembly)) {
722 return "";
723 }
724
725 std::string Result;
726 raw_string_ostream OS(Result);
727 WriteBitcodeToFile(&TempModule, OS);
728 OS.flush();
729 return Result;
730}
731
732// Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000733// lazily. The associated Module (owned by the ExecutionEngine) is returned in
734// M. Both will be NULL on an error. Bitcode must live at least as long as the
735// ExecutionEngine.
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000736ExecutionEngine *getJITFromBitcode(
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000737 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000738 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
739 MemoryBuffer *BitcodeBuffer =
Chris Lattner796e64b2010-04-05 22:49:48 +0000740 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000741 std::string errMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000742 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
743 if (M == NULL) {
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000744 ADD_FAILURE() << errMsg;
745 delete BitcodeBuffer;
746 return NULL;
747 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000748 ExecutionEngine *TheJIT = EngineBuilder(M)
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000749 .setEngineKind(EngineKind::JIT)
750 .setErrorStr(&errMsg)
751 .create();
752 if (TheJIT == NULL) {
753 ADD_FAILURE() << errMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000754 delete M;
755 M = NULL;
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000756 return NULL;
757 }
758 return TheJIT;
759}
760
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000761TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
762 LLVMContext Context;
763 const std::string Bitcode =
764 AssembleToBitcode(Context,
765 "define available_externally i32 "
766 " @JITTest_AvailableExternallyFunction() { "
767 " ret i32 7 "
768 "} "
769 " "
770 "define i32 @func() { "
771 " %result = tail call i32 "
772 " @JITTest_AvailableExternallyFunction() "
773 " ret i32 %result "
774 "} ");
775 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
776 Module *M;
777 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
778 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
779 TheJIT->DisableLazyCompilation(true);
780
781 Function *funcIR = M->getFunction("func");
782 Function *availableFunctionIR =
783 M->getFunction("JITTest_AvailableExternallyFunction");
784
785 // Double-check that the available_externally function is still unmaterialized
786 // when getPointerToFunction needs to find out if it's available_externally.
787 EXPECT_TRUE(availableFunctionIR->isMaterializable());
788
789 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
790 (intptr_t)TheJIT->getPointerToFunction(funcIR));
791 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
792 << " not 7 from the IR version.";
793}
794
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000795TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
796 LLVMContext Context;
797 const std::string Bitcode =
798 AssembleToBitcode(Context,
799 "define i32 @recur1(i32 %a) { "
800 " %zero = icmp eq i32 %a, 0 "
801 " br i1 %zero, label %done, label %notdone "
802 "done: "
803 " ret i32 3 "
804 "notdone: "
805 " %am1 = sub i32 %a, 1 "
806 " %result = call i32 @recur2(i32 %am1) "
807 " ret i32 %result "
808 "} "
809 " "
810 "define i32 @recur2(i32 %b) { "
811 " %result = call i32 @recur1(i32 %b) "
812 " ret i32 %result "
813 "} ");
814 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000815 Module *M;
816 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000817 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
818 TheJIT->DisableLazyCompilation(true);
819
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000820 Function *recur1IR = M->getFunction("recur1");
821 Function *recur2IR = M->getFunction("recur2");
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000822 EXPECT_TRUE(recur1IR->isMaterializable());
823 EXPECT_TRUE(recur2IR->isMaterializable());
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000824
825 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
826 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
827 EXPECT_EQ(3, recur1(4));
828}
Ulrich Weigandf772f072012-10-31 16:18:02 +0000829#endif // !defined(__arm__) && !defined(__powerpc__)
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000830
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000831// This code is copied from JITEventListenerTest, but it only runs once for all
832// the tests in this directory. Everything seems fine, but that's strange
833// behavior.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000834class JITEnvironment : public testing::Environment {
835 virtual void SetUp() {
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000836 // Required to create a JIT.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000837 InitializeNativeTarget();
838 }
839};
840testing::Environment* const jit_env =
841 testing::AddGlobalTestEnvironment(new JITEnvironment);
842
843}