JITTest.cpp 27 KB

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