JITTest.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. //===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
  2. //
  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. #include "llvm/ExecutionEngine/JIT.h"
  10. #include "llvm/ADT/OwningPtr.h"
  11. #include "llvm/ADT/SmallPtrSet.h"
  12. #include "llvm/Assembly/Parser.h"
  13. #include "llvm/BasicBlock.h"
  14. #include "llvm/Bitcode/ReaderWriter.h"
  15. #include "llvm/Constant.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  19. #include "llvm/Function.h"
  20. #include "llvm/GlobalValue.h"
  21. #include "llvm/GlobalVariable.h"
  22. #include "llvm/IRBuilder.h"
  23. #include "llvm/LLVMContext.h"
  24. #include "llvm/Module.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/SourceMgr.h"
  27. #include "llvm/Support/TargetSelect.h"
  28. #include "llvm/Type.h"
  29. #include "llvm/TypeBuilder.h"
  30. #include "gtest/gtest.h"
  31. #include <vector>
  32. using namespace llvm;
  33. namespace {
  34. Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
  35. std::vector<Type*> params;
  36. FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
  37. params, false);
  38. Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
  39. BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
  40. IRBuilder<> builder(Entry);
  41. Value *Load = builder.CreateLoad(G);
  42. Type *GTy = G->getType()->getElementType();
  43. Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
  44. builder.CreateStore(Add, G);
  45. builder.CreateRet(Add);
  46. return F;
  47. }
  48. std::string DumpFunction(const Function *F) {
  49. std::string Result;
  50. raw_string_ostream(Result) << "" << *F;
  51. return Result;
  52. }
  53. class RecordingJITMemoryManager : public JITMemoryManager {
  54. const OwningPtr<JITMemoryManager> Base;
  55. public:
  56. RecordingJITMemoryManager()
  57. : Base(JITMemoryManager::CreateDefaultMemManager()) {
  58. stubsAllocated = 0;
  59. }
  60. virtual void *getPointerToNamedFunction(const std::string &Name,
  61. bool AbortOnFailure = true) {
  62. return Base->getPointerToNamedFunction(Name, AbortOnFailure);
  63. }
  64. virtual void setMemoryWritable() { Base->setMemoryWritable(); }
  65. virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
  66. virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
  67. virtual void AllocateGOT() { Base->AllocateGOT(); }
  68. virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
  69. struct StartFunctionBodyCall {
  70. StartFunctionBodyCall(uint8_t *Result, const Function *F,
  71. uintptr_t ActualSize, uintptr_t ActualSizeResult)
  72. : Result(Result), F(F), F_dump(DumpFunction(F)),
  73. ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
  74. uint8_t *Result;
  75. const Function *F;
  76. std::string F_dump;
  77. uintptr_t ActualSize;
  78. uintptr_t ActualSizeResult;
  79. };
  80. std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
  81. virtual uint8_t *startFunctionBody(const Function *F,
  82. uintptr_t &ActualSize) {
  83. uintptr_t InitialActualSize = ActualSize;
  84. uint8_t *Result = Base->startFunctionBody(F, ActualSize);
  85. startFunctionBodyCalls.push_back(
  86. StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
  87. return Result;
  88. }
  89. int stubsAllocated;
  90. virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
  91. unsigned Alignment) {
  92. stubsAllocated++;
  93. return Base->allocateStub(F, StubSize, Alignment);
  94. }
  95. struct EndFunctionBodyCall {
  96. EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
  97. uint8_t *FunctionEnd)
  98. : F(F), F_dump(DumpFunction(F)),
  99. FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
  100. const Function *F;
  101. std::string F_dump;
  102. uint8_t *FunctionStart;
  103. uint8_t *FunctionEnd;
  104. };
  105. std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
  106. virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
  107. uint8_t *FunctionEnd) {
  108. endFunctionBodyCalls.push_back(
  109. EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
  110. Base->endFunctionBody(F, FunctionStart, FunctionEnd);
  111. }
  112. virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  113. unsigned SectionID, bool IsReadOnly) {
  114. return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
  115. }
  116. virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  117. unsigned SectionID) {
  118. return Base->allocateCodeSection(Size, Alignment, SectionID);
  119. }
  120. virtual bool applyPermissions(std::string *ErrMsg) { return false; }
  121. virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
  122. return Base->allocateSpace(Size, Alignment);
  123. }
  124. virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
  125. return Base->allocateGlobal(Size, Alignment);
  126. }
  127. struct DeallocateFunctionBodyCall {
  128. DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
  129. const void *Body;
  130. };
  131. std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
  132. virtual void deallocateFunctionBody(void *Body) {
  133. deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
  134. Base->deallocateFunctionBody(Body);
  135. }
  136. struct DeallocateExceptionTableCall {
  137. DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
  138. const void *ET;
  139. };
  140. std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
  141. virtual void deallocateExceptionTable(void *ET) {
  142. deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
  143. Base->deallocateExceptionTable(ET);
  144. }
  145. struct StartExceptionTableCall {
  146. StartExceptionTableCall(uint8_t *Result, const Function *F,
  147. uintptr_t ActualSize, uintptr_t ActualSizeResult)
  148. : Result(Result), F(F), F_dump(DumpFunction(F)),
  149. ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
  150. uint8_t *Result;
  151. const Function *F;
  152. std::string F_dump;
  153. uintptr_t ActualSize;
  154. uintptr_t ActualSizeResult;
  155. };
  156. std::vector<StartExceptionTableCall> startExceptionTableCalls;
  157. virtual uint8_t* startExceptionTable(const Function* F,
  158. uintptr_t &ActualSize) {
  159. uintptr_t InitialActualSize = ActualSize;
  160. uint8_t *Result = Base->startExceptionTable(F, ActualSize);
  161. startExceptionTableCalls.push_back(
  162. StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
  163. return Result;
  164. }
  165. struct EndExceptionTableCall {
  166. EndExceptionTableCall(const Function *F, uint8_t *TableStart,
  167. uint8_t *TableEnd, uint8_t* FrameRegister)
  168. : F(F), F_dump(DumpFunction(F)),
  169. TableStart(TableStart), TableEnd(TableEnd),
  170. FrameRegister(FrameRegister) {}
  171. const Function *F;
  172. std::string F_dump;
  173. uint8_t *TableStart;
  174. uint8_t *TableEnd;
  175. uint8_t *FrameRegister;
  176. };
  177. std::vector<EndExceptionTableCall> endExceptionTableCalls;
  178. virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
  179. uint8_t *TableEnd, uint8_t* FrameRegister) {
  180. endExceptionTableCalls.push_back(
  181. EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
  182. return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
  183. }
  184. };
  185. bool LoadAssemblyInto(Module *M, const char *assembly) {
  186. SMDiagnostic Error;
  187. bool success =
  188. NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
  189. std::string errMsg;
  190. raw_string_ostream os(errMsg);
  191. Error.print("", os);
  192. EXPECT_TRUE(success) << os.str();
  193. return success;
  194. }
  195. class JITTest : public testing::Test {
  196. protected:
  197. virtual void SetUp() {
  198. M = new Module("<main>", Context);
  199. RJMM = new RecordingJITMemoryManager;
  200. RJMM->setPoisonMemory(true);
  201. std::string Error;
  202. TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
  203. .setJITMemoryManager(RJMM)
  204. .setErrorStr(&Error).create());
  205. ASSERT_TRUE(TheJIT.get() != NULL) << Error;
  206. }
  207. void LoadAssembly(const char *assembly) {
  208. LoadAssemblyInto(M, assembly);
  209. }
  210. LLVMContext Context;
  211. Module *M; // Owned by ExecutionEngine.
  212. RecordingJITMemoryManager *RJMM;
  213. OwningPtr<ExecutionEngine> TheJIT;
  214. };
  215. // Tests on ARM and PowerPC disabled as we're running the old jit
  216. #if !defined(__arm__) && !defined(__powerpc__)
  217. // Regression test for a bug. The JIT used to allocate globals inside the same
  218. // memory block used for the function, and when the function code was freed,
  219. // the global was left in the same place. This test allocates a function
  220. // that uses and global, deallocates it, and then makes sure that the global
  221. // stays alive after that.
  222. TEST(JIT, GlobalInFunction) {
  223. LLVMContext context;
  224. Module *M = new Module("<main>", context);
  225. JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
  226. // Tell the memory manager to poison freed memory so that accessing freed
  227. // memory is more easily tested.
  228. MemMgr->setPoisonMemory(true);
  229. std::string Error;
  230. OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
  231. .setEngineKind(EngineKind::JIT)
  232. .setErrorStr(&Error)
  233. .setJITMemoryManager(MemMgr)
  234. // The next line enables the fix:
  235. .setAllocateGVsWithCode(false)
  236. .create());
  237. ASSERT_EQ(Error, "");
  238. // Create a global variable.
  239. Type *GTy = Type::getInt32Ty(context);
  240. GlobalVariable *G = new GlobalVariable(
  241. *M,
  242. GTy,
  243. false, // Not constant.
  244. GlobalValue::InternalLinkage,
  245. Constant::getNullValue(GTy),
  246. "myglobal");
  247. // Make a function that points to a global.
  248. Function *F1 = makeReturnGlobal("F1", G, M);
  249. // Get the pointer to the native code to force it to JIT the function and
  250. // allocate space for the global.
  251. void (*F1Ptr)() =
  252. reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
  253. // Since F1 was codegen'd, a pointer to G should be available.
  254. int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
  255. ASSERT_NE((int32_t*)NULL, GPtr);
  256. EXPECT_EQ(0, *GPtr);
  257. // F1() should increment G.
  258. F1Ptr();
  259. EXPECT_EQ(1, *GPtr);
  260. // Make a second function identical to the first, referring to the same
  261. // global.
  262. Function *F2 = makeReturnGlobal("F2", G, M);
  263. void (*F2Ptr)() =
  264. reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
  265. // F2() should increment G.
  266. F2Ptr();
  267. EXPECT_EQ(2, *GPtr);
  268. // Deallocate F1.
  269. JIT->freeMachineCodeForFunction(F1);
  270. // F2() should *still* increment G.
  271. F2Ptr();
  272. EXPECT_EQ(3, *GPtr);
  273. }
  274. #endif // !defined(__arm__) && !defined(__powerpc__)
  275. int PlusOne(int arg) {
  276. return arg + 1;
  277. }
  278. // ARM and PowerPC tests disabled pending fix for PR10783.
  279. #if !defined(__arm__) && !defined(__powerpc__)
  280. TEST_F(JITTest, FarCallToKnownFunction) {
  281. // x86-64 can only make direct calls to functions within 32 bits of
  282. // the current PC. To call anything farther away, we have to load
  283. // the address into a register and call through the register. The
  284. // current JIT does this by allocating a stub for any far call.
  285. // There was a bug in which the JIT tried to emit a direct call when
  286. // the target was already in the JIT's global mappings and lazy
  287. // compilation was disabled.
  288. Function *KnownFunction = Function::Create(
  289. TypeBuilder<int(int), false>::get(Context),
  290. GlobalValue::ExternalLinkage, "known", M);
  291. TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
  292. // int test() { return known(7); }
  293. Function *TestFunction = Function::Create(
  294. TypeBuilder<int(), false>::get(Context),
  295. GlobalValue::ExternalLinkage, "test", M);
  296. BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
  297. IRBuilder<> Builder(Entry);
  298. Value *result = Builder.CreateCall(
  299. KnownFunction,
  300. ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
  301. Builder.CreateRet(result);
  302. TheJIT->DisableLazyCompilation(true);
  303. int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
  304. (intptr_t)TheJIT->getPointerToFunction(TestFunction));
  305. // This used to crash in trying to call PlusOne().
  306. EXPECT_EQ(8, TestFunctionPtr());
  307. }
  308. // Test a function C which calls A and B which call each other.
  309. TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
  310. TheJIT->DisableLazyCompilation(true);
  311. FunctionType *Func1Ty =
  312. cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
  313. std::vector<Type*> arg_types;
  314. arg_types.push_back(Type::getInt1Ty(Context));
  315. FunctionType *FuncTy = FunctionType::get(
  316. Type::getVoidTy(Context), arg_types, false);
  317. Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
  318. "func1", M);
  319. Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
  320. "func2", M);
  321. Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
  322. "func3", M);
  323. BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
  324. BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
  325. BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
  326. BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
  327. BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
  328. BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
  329. BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
  330. // Make Func1 call Func2(0) and Func3(0).
  331. IRBuilder<> Builder(Block1);
  332. Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
  333. Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
  334. Builder.CreateRetVoid();
  335. // void Func2(bool b) { if (b) { Func3(false); return; } return; }
  336. Builder.SetInsertPoint(Block2);
  337. Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
  338. Builder.SetInsertPoint(True2);
  339. Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
  340. Builder.CreateRetVoid();
  341. Builder.SetInsertPoint(False2);
  342. Builder.CreateRetVoid();
  343. // void Func3(bool b) { if (b) { Func2(false); return; } return; }
  344. Builder.SetInsertPoint(Block3);
  345. Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
  346. Builder.SetInsertPoint(True3);
  347. Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
  348. Builder.CreateRetVoid();
  349. Builder.SetInsertPoint(False3);
  350. Builder.CreateRetVoid();
  351. // Compile the function to native code
  352. void (*F1Ptr)() =
  353. reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
  354. F1Ptr();
  355. }
  356. // Regression test for PR5162. This used to trigger an AssertingVH inside the
  357. // JIT's Function to stub mapping.
  358. TEST_F(JITTest, NonLazyLeaksNoStubs) {
  359. TheJIT->DisableLazyCompilation(true);
  360. // Create two functions with a single basic block each.
  361. FunctionType *FuncTy =
  362. cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
  363. Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
  364. "func1", M);
  365. Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
  366. "func2", M);
  367. BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
  368. BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
  369. // The first function calls the second and returns the result
  370. IRBuilder<> Builder(Block1);
  371. Value *Result = Builder.CreateCall(Func2);
  372. Builder.CreateRet(Result);
  373. // The second function just returns a constant
  374. Builder.SetInsertPoint(Block2);
  375. Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
  376. // Compile the function to native code
  377. (void)TheJIT->getPointerToFunction(Func1);
  378. // Free the JIT state for the functions
  379. TheJIT->freeMachineCodeForFunction(Func1);
  380. TheJIT->freeMachineCodeForFunction(Func2);
  381. // Delete the first function (and show that is has no users)
  382. EXPECT_EQ(Func1->getNumUses(), 0u);
  383. Func1->eraseFromParent();
  384. // Delete the second function (and show that it has no users - it had one,
  385. // func1 but that's gone now)
  386. EXPECT_EQ(Func2->getNumUses(), 0u);
  387. Func2->eraseFromParent();
  388. }
  389. TEST_F(JITTest, ModuleDeletion) {
  390. TheJIT->DisableLazyCompilation(false);
  391. LoadAssembly("define void @main() { "
  392. " call i32 @computeVal() "
  393. " ret void "
  394. "} "
  395. " "
  396. "define internal i32 @computeVal() { "
  397. " ret i32 0 "
  398. "} ");
  399. Function *func = M->getFunction("main");
  400. TheJIT->getPointerToFunction(func);
  401. TheJIT->removeModule(M);
  402. delete M;
  403. SmallPtrSet<const void*, 2> FunctionsDeallocated;
  404. for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
  405. i != e; ++i) {
  406. FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
  407. }
  408. for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
  409. EXPECT_TRUE(FunctionsDeallocated.count(
  410. RJMM->startFunctionBodyCalls[i].Result))
  411. << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
  412. }
  413. EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
  414. RJMM->deallocateFunctionBodyCalls.size());
  415. SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
  416. unsigned NumTablesDeallocated = 0;
  417. for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
  418. i != e; ++i) {
  419. ExceptionTablesDeallocated.insert(
  420. RJMM->deallocateExceptionTableCalls[i].ET);
  421. if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
  422. // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
  423. // appear in startExceptionTableCalls.
  424. NumTablesDeallocated++;
  425. }
  426. }
  427. for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
  428. EXPECT_TRUE(ExceptionTablesDeallocated.count(
  429. RJMM->startExceptionTableCalls[i].Result))
  430. << "Function's exception table leaked: \n"
  431. << RJMM->startExceptionTableCalls[i].F_dump;
  432. }
  433. EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
  434. NumTablesDeallocated);
  435. }
  436. #endif // !defined(__arm__) && !defined(__powerpc__)
  437. // ARM, MIPS and PPC still emit stubs for calls since the target may be
  438. // too far away to call directly. This #if can probably be removed when
  439. // http://llvm.org/PR5201 is fixed.
  440. #if !defined(__arm__) && !defined(__mips__) && \
  441. !defined(__powerpc__) && !defined(__ppc__)
  442. typedef int (*FooPtr) ();
  443. TEST_F(JITTest, NoStubs) {
  444. LoadAssembly("define void @bar() {"
  445. "entry: "
  446. "ret void"
  447. "}"
  448. " "
  449. "define i32 @foo() {"
  450. "entry:"
  451. "call void @bar()"
  452. "ret i32 undef"
  453. "}"
  454. " "
  455. "define i32 @main() {"
  456. "entry:"
  457. "%0 = call i32 @foo()"
  458. "call void @bar()"
  459. "ret i32 undef"
  460. "}");
  461. Function *foo = M->getFunction("foo");
  462. uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
  463. FooPtr ptr = (FooPtr)(tmp);
  464. (ptr)();
  465. // We should now allocate no more stubs, we have the code to foo
  466. // and the existing stub for bar.
  467. int stubsBefore = RJMM->stubsAllocated;
  468. Function *func = M->getFunction("main");
  469. TheJIT->getPointerToFunction(func);
  470. Function *bar = M->getFunction("bar");
  471. TheJIT->getPointerToFunction(bar);
  472. ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
  473. }
  474. #endif // !ARM && !PPC
  475. // Tests on ARM and PowerPC disabled as we're running the old jit
  476. #if !defined(__arm__) && !defined(__powerpc__)
  477. TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
  478. TheJIT->DisableLazyCompilation(true);
  479. LoadAssembly("define i8()* @get_foo_addr() { "
  480. " ret i8()* @foo "
  481. "} "
  482. " "
  483. "define i8 @foo() { "
  484. " ret i8 42 "
  485. "} ");
  486. Function *F_get_foo_addr = M->getFunction("get_foo_addr");
  487. typedef char(*fooT)();
  488. fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
  489. (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
  490. fooT foo_addr = get_foo_addr();
  491. // Now free get_foo_addr. This should not free the machine code for foo or
  492. // any call stub returned as foo's canonical address.
  493. TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
  494. // Check by calling the reported address of foo.
  495. EXPECT_EQ(42, foo_addr());
  496. // The reported address should also be the same as the result of a subsequent
  497. // getPointerToFunction(foo).
  498. #if 0
  499. // Fails until PR5126 is fixed:
  500. Function *F_foo = M->getFunction("foo");
  501. fooT foo = reinterpret_cast<fooT>(
  502. (intptr_t)TheJIT->getPointerToFunction(F_foo));
  503. EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
  504. #endif
  505. }
  506. #endif //!defined(__arm__) && !defined(__powerpc__)
  507. // Tests on ARM and PowerPC disabled as we're running the old jit
  508. // In addition, ARM does not have an implementation
  509. // of replaceMachineCodeForFunction(), so recompileAndRelinkFunction
  510. // doesn't work.
  511. #if !defined(__arm__) && !defined(__powerpc__)
  512. TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
  513. Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
  514. GlobalValue::ExternalLinkage, "test", M);
  515. BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
  516. IRBuilder<> Builder(Entry);
  517. Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
  518. Builder.CreateRet(Val);
  519. TheJIT->DisableLazyCompilation(true);
  520. // Compile the function once, and make sure it works.
  521. int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
  522. (intptr_t)TheJIT->recompileAndRelinkFunction(F));
  523. EXPECT_EQ(1, OrigFPtr());
  524. // Now change the function to return a different value.
  525. Entry->eraseFromParent();
  526. BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
  527. Builder.SetInsertPoint(NewEntry);
  528. Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
  529. Builder.CreateRet(Val);
  530. // Recompile it, which should produce a new function pointer _and_ update the
  531. // old one.
  532. int (*NewFPtr)() = reinterpret_cast<int(*)()>(
  533. (intptr_t)TheJIT->recompileAndRelinkFunction(F));
  534. EXPECT_EQ(2, NewFPtr())
  535. << "The new pointer should call the new version of the function";
  536. EXPECT_EQ(2, OrigFPtr())
  537. << "The old pointer's target should now jump to the new version";
  538. }
  539. #endif // !defined(__arm__) && !defined(__powerpc__)
  540. } // anonymous namespace
  541. // This variable is intentionally defined differently in the statically-compiled
  542. // program from the IR input to the JIT to assert that the JIT doesn't use its
  543. // definition.
  544. extern "C" int32_t JITTest_AvailableExternallyGlobal;
  545. int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
  546. namespace {
  547. // Tests on ARM and PowerPC disabled as we're running the old jit
  548. #if !defined(__arm__) && !defined(__powerpc__)
  549. TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
  550. TheJIT->DisableLazyCompilation(true);
  551. LoadAssembly("@JITTest_AvailableExternallyGlobal = "
  552. " available_externally global i32 7 "
  553. " "
  554. "define i32 @loader() { "
  555. " %result = load i32* @JITTest_AvailableExternallyGlobal "
  556. " ret i32 %result "
  557. "} ");
  558. Function *loaderIR = M->getFunction("loader");
  559. int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
  560. (intptr_t)TheJIT->getPointerToFunction(loaderIR));
  561. EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
  562. << " not 7 from the IR version.";
  563. }
  564. #endif //!defined(__arm__) && !defined(__powerpc__)
  565. } // anonymous namespace
  566. // This function is intentionally defined differently in the statically-compiled
  567. // program from the IR input to the JIT to assert that the JIT doesn't use its
  568. // definition.
  569. extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
  570. extern "C" int32_t JITTest_AvailableExternallyFunction() {
  571. return 42;
  572. }
  573. namespace {
  574. // ARM and PowerPC tests disabled pending fix for PR10783.
  575. #if !defined(__arm__) && !defined(__powerpc__)
  576. TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
  577. TheJIT->DisableLazyCompilation(true);
  578. LoadAssembly("define available_externally i32 "
  579. " @JITTest_AvailableExternallyFunction() { "
  580. " ret i32 7 "
  581. "} "
  582. " "
  583. "define i32 @func() { "
  584. " %result = tail call i32 "
  585. " @JITTest_AvailableExternallyFunction() "
  586. " ret i32 %result "
  587. "} ");
  588. Function *funcIR = M->getFunction("func");
  589. int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
  590. (intptr_t)TheJIT->getPointerToFunction(funcIR));
  591. EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
  592. << " not 7 from the IR version.";
  593. }
  594. TEST_F(JITTest, EscapedLazyStubStillCallable) {
  595. TheJIT->DisableLazyCompilation(false);
  596. LoadAssembly("define internal i32 @stubbed() { "
  597. " ret i32 42 "
  598. "} "
  599. " "
  600. "define i32()* @get_stub() { "
  601. " ret i32()* @stubbed "
  602. "} ");
  603. typedef int32_t(*StubTy)();
  604. // Call get_stub() to get the address of @stubbed without actually JITting it.
  605. Function *get_stubIR = M->getFunction("get_stub");
  606. StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
  607. (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
  608. StubTy stubbed = get_stub();
  609. // Now get_stubIR is the only reference to stubbed's stub.
  610. get_stubIR->eraseFromParent();
  611. // Now there are no references inside the JIT, but we've got a pointer outside
  612. // it. The stub should be callable and return the right value.
  613. EXPECT_EQ(42, stubbed());
  614. }
  615. // Converts the LLVM assembly to bitcode and returns it in a std::string. An
  616. // empty string indicates an error.
  617. std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
  618. Module TempModule("TempModule", Context);
  619. if (!LoadAssemblyInto(&TempModule, Assembly)) {
  620. return "";
  621. }
  622. std::string Result;
  623. raw_string_ostream OS(Result);
  624. WriteBitcodeToFile(&TempModule, OS);
  625. OS.flush();
  626. return Result;
  627. }
  628. // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
  629. // lazily. The associated Module (owned by the ExecutionEngine) is returned in
  630. // M. Both will be NULL on an error. Bitcode must live at least as long as the
  631. // ExecutionEngine.
  632. ExecutionEngine *getJITFromBitcode(
  633. LLVMContext &Context, const std::string &Bitcode, Module *&M) {
  634. // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
  635. MemoryBuffer *BitcodeBuffer =
  636. MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
  637. std::string errMsg;
  638. M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
  639. if (M == NULL) {
  640. ADD_FAILURE() << errMsg;
  641. delete BitcodeBuffer;
  642. return NULL;
  643. }
  644. ExecutionEngine *TheJIT = EngineBuilder(M)
  645. .setEngineKind(EngineKind::JIT)
  646. .setErrorStr(&errMsg)
  647. .create();
  648. if (TheJIT == NULL) {
  649. ADD_FAILURE() << errMsg;
  650. delete M;
  651. M = NULL;
  652. return NULL;
  653. }
  654. return TheJIT;
  655. }
  656. TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
  657. LLVMContext Context;
  658. const std::string Bitcode =
  659. AssembleToBitcode(Context,
  660. "define available_externally i32 "
  661. " @JITTest_AvailableExternallyFunction() { "
  662. " ret i32 7 "
  663. "} "
  664. " "
  665. "define i32 @func() { "
  666. " %result = tail call i32 "
  667. " @JITTest_AvailableExternallyFunction() "
  668. " ret i32 %result "
  669. "} ");
  670. ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
  671. Module *M;
  672. OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
  673. ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
  674. TheJIT->DisableLazyCompilation(true);
  675. Function *funcIR = M->getFunction("func");
  676. Function *availableFunctionIR =
  677. M->getFunction("JITTest_AvailableExternallyFunction");
  678. // Double-check that the available_externally function is still unmaterialized
  679. // when getPointerToFunction needs to find out if it's available_externally.
  680. EXPECT_TRUE(availableFunctionIR->isMaterializable());
  681. int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
  682. (intptr_t)TheJIT->getPointerToFunction(funcIR));
  683. EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
  684. << " not 7 from the IR version.";
  685. }
  686. TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
  687. LLVMContext Context;
  688. const std::string Bitcode =
  689. AssembleToBitcode(Context,
  690. "define i32 @recur1(i32 %a) { "
  691. " %zero = icmp eq i32 %a, 0 "
  692. " br i1 %zero, label %done, label %notdone "
  693. "done: "
  694. " ret i32 3 "
  695. "notdone: "
  696. " %am1 = sub i32 %a, 1 "
  697. " %result = call i32 @recur2(i32 %am1) "
  698. " ret i32 %result "
  699. "} "
  700. " "
  701. "define i32 @recur2(i32 %b) { "
  702. " %result = call i32 @recur1(i32 %b) "
  703. " ret i32 %result "
  704. "} ");
  705. ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
  706. Module *M;
  707. OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
  708. ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
  709. TheJIT->DisableLazyCompilation(true);
  710. Function *recur1IR = M->getFunction("recur1");
  711. Function *recur2IR = M->getFunction("recur2");
  712. EXPECT_TRUE(recur1IR->isMaterializable());
  713. EXPECT_TRUE(recur2IR->isMaterializable());
  714. int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
  715. (intptr_t)TheJIT->getPointerToFunction(recur1IR));
  716. EXPECT_EQ(3, recur1(4));
  717. }
  718. #endif // !defined(__arm__) && !defined(__powerpc__)
  719. // This code is copied from JITEventListenerTest, but it only runs once for all
  720. // the tests in this directory. Everything seems fine, but that's strange
  721. // behavior.
  722. class JITEnvironment : public testing::Environment {
  723. virtual void SetUp() {
  724. // Required to create a JIT.
  725. InitializeNativeTarget();
  726. }
  727. };
  728. testing::Environment* const jit_env =
  729. testing::AddGlobalTestEnvironment(new JITEnvironment);
  730. }