ParallelJIT.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Parallel JIT
  10. //
  11. // This test program creates two LLVM functions then calls them from three
  12. // separate threads. It requires the pthreads library.
  13. // The three threads are created and then block waiting on a condition variable.
  14. // Once all threads are blocked on the conditional variable, the main thread
  15. // wakes them up. This complicated work is performed so that all three threads
  16. // call into the JIT at the same time (or the best possible approximation of the
  17. // same time). This test had assertion errors until I got the locking right.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "llvm/ADT/APInt.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  23. #include "llvm/ExecutionEngine/GenericValue.h"
  24. #include "llvm/IR/Argument.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/InstrTypes.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/Type.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/TargetSelect.h"
  37. #include <algorithm>
  38. #include <cassert>
  39. #include <cstddef>
  40. #include <cstdint>
  41. #include <iostream>
  42. #include <memory>
  43. #include <vector>
  44. #include <pthread.h>
  45. using namespace llvm;
  46. static Function* createAdd1(Module *M) {
  47. LLVMContext &Context = M->getContext();
  48. // Create the add1 function entry and insert this entry into module M. The
  49. // function will have a return type of "int" and take an argument of "int".
  50. Function *Add1F =
  51. Function::Create(FunctionType::get(Type::getInt32Ty(Context),
  52. {Type::getInt32Ty(Context)}, false),
  53. Function::ExternalLinkage, "add1", M);
  54. // Add a basic block to the function. As before, it automatically inserts
  55. // because of the last argument.
  56. BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
  57. // Get pointers to the constant `1'.
  58. Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
  59. // Get pointers to the integer argument of the add1 function...
  60. assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
  61. Argument *ArgX = &*Add1F->arg_begin(); // Get the arg
  62. ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
  63. // Create the add instruction, inserting it into the end of BB.
  64. Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
  65. // Create the return instruction and add it to the basic block
  66. ReturnInst::Create(Context, Add, BB);
  67. // Now, function add1 is ready.
  68. return Add1F;
  69. }
  70. static Function *CreateFibFunction(Module *M) {
  71. LLVMContext &Context = M->getContext();
  72. // Create the fib function and insert it into module M. This function is said
  73. // to return an int and take an int parameter.
  74. FunctionType *FibFTy = FunctionType::get(Type::getInt32Ty(Context),
  75. {Type::getInt32Ty(Context)}, false);
  76. Function *FibF =
  77. Function::Create(FibFTy, Function::ExternalLinkage, "fib", M);
  78. // Add a basic block to the function.
  79. BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);
  80. // Get pointers to the constants.
  81. Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
  82. Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
  83. // Get pointer to the integer argument of the add1 function...
  84. Argument *ArgX = &*FibF->arg_begin(); // Get the arg.
  85. ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
  86. // Create the true_block.
  87. BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
  88. // Create an exit block.
  89. BasicBlock *RecurseBB = BasicBlock::Create(Context, "recurse", FibF);
  90. // Create the "if (arg < 2) goto exitbb"
  91. Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
  92. BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
  93. // Create: ret int 1
  94. ReturnInst::Create(Context, One, RetBB);
  95. // create fib(x-1)
  96. Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
  97. Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
  98. // create fib(x-2)
  99. Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
  100. Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
  101. // fib(x-1)+fib(x-2)
  102. Value *Sum =
  103. BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
  104. // Create the return instruction and add it to the basic block
  105. ReturnInst::Create(Context, Sum, RecurseBB);
  106. return FibF;
  107. }
  108. struct threadParams {
  109. ExecutionEngine* EE;
  110. Function* F;
  111. int value;
  112. };
  113. // We block the subthreads just before they begin to execute:
  114. // we want all of them to call into the JIT at the same time,
  115. // to verify that the locking is working correctly.
  116. class WaitForThreads
  117. {
  118. public:
  119. WaitForThreads()
  120. {
  121. n = 0;
  122. waitFor = 0;
  123. int result = pthread_cond_init( &condition, nullptr );
  124. (void)result;
  125. assert( result == 0 );
  126. result = pthread_mutex_init( &mutex, nullptr );
  127. assert( result == 0 );
  128. }
  129. ~WaitForThreads()
  130. {
  131. int result = pthread_cond_destroy( &condition );
  132. (void)result;
  133. assert( result == 0 );
  134. result = pthread_mutex_destroy( &mutex );
  135. assert( result == 0 );
  136. }
  137. // All threads will stop here until another thread calls releaseThreads
  138. void block()
  139. {
  140. int result = pthread_mutex_lock( &mutex );
  141. (void)result;
  142. assert( result == 0 );
  143. n ++;
  144. //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
  145. assert( waitFor == 0 || n <= waitFor );
  146. if ( waitFor > 0 && n == waitFor )
  147. {
  148. // There are enough threads blocked that we can release all of them
  149. std::cout << "Unblocking threads from block()" << std::endl;
  150. unblockThreads();
  151. }
  152. else
  153. {
  154. // We just need to wait until someone unblocks us
  155. result = pthread_cond_wait( &condition, &mutex );
  156. assert( result == 0 );
  157. }
  158. // unlock the mutex before returning
  159. result = pthread_mutex_unlock( &mutex );
  160. assert( result == 0 );
  161. }
  162. // If there are num or more threads blocked, it will signal them all
  163. // Otherwise, this thread blocks until there are enough OTHER threads
  164. // blocked
  165. void releaseThreads( size_t num )
  166. {
  167. int result = pthread_mutex_lock( &mutex );
  168. (void)result;
  169. assert( result == 0 );
  170. if ( n >= num ) {
  171. std::cout << "Unblocking threads from releaseThreads()" << std::endl;
  172. unblockThreads();
  173. }
  174. else
  175. {
  176. waitFor = num;
  177. pthread_cond_wait( &condition, &mutex );
  178. }
  179. // unlock the mutex before returning
  180. result = pthread_mutex_unlock( &mutex );
  181. assert( result == 0 );
  182. }
  183. private:
  184. void unblockThreads()
  185. {
  186. // Reset the counters to zero: this way, if any new threads
  187. // enter while threads are exiting, they will block instead
  188. // of triggering a new release of threads
  189. n = 0;
  190. // Reset waitFor to zero: this way, if waitFor threads enter
  191. // while threads are exiting, they will block instead of
  192. // triggering a new release of threads
  193. waitFor = 0;
  194. int result = pthread_cond_broadcast( &condition );
  195. (void)result;
  196. assert(result == 0);
  197. }
  198. size_t n;
  199. size_t waitFor;
  200. pthread_cond_t condition;
  201. pthread_mutex_t mutex;
  202. };
  203. static WaitForThreads synchronize;
  204. void* callFunc( void* param )
  205. {
  206. struct threadParams* p = (struct threadParams*) param;
  207. // Call the `foo' function with no arguments:
  208. std::vector<GenericValue> Args(1);
  209. Args[0].IntVal = APInt(32, p->value);
  210. synchronize.block(); // wait until other threads are at this point
  211. GenericValue gv = p->EE->runFunction(p->F, Args);
  212. return (void*)(intptr_t)gv.IntVal.getZExtValue();
  213. }
  214. int main() {
  215. InitializeNativeTarget();
  216. LLVMContext Context;
  217. // Create some module to put our function into it.
  218. std::unique_ptr<Module> Owner = std::make_unique<Module>("test", Context);
  219. Module *M = Owner.get();
  220. Function* add1F = createAdd1( M );
  221. Function* fibF = CreateFibFunction( M );
  222. // Now we create the JIT.
  223. ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
  224. //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
  225. //~ std::cout << "\n\nRunning foo: " << std::flush;
  226. // Create one thread for add1 and two threads for fib
  227. struct threadParams add1 = { EE, add1F, 1000 };
  228. struct threadParams fib1 = { EE, fibF, 39 };
  229. struct threadParams fib2 = { EE, fibF, 42 };
  230. pthread_t add1Thread;
  231. int result = pthread_create( &add1Thread, nullptr, callFunc, &add1 );
  232. if ( result != 0 ) {
  233. std::cerr << "Could not create thread" << std::endl;
  234. return 1;
  235. }
  236. pthread_t fibThread1;
  237. result = pthread_create( &fibThread1, nullptr, callFunc, &fib1 );
  238. if ( result != 0 ) {
  239. std::cerr << "Could not create thread" << std::endl;
  240. return 1;
  241. }
  242. pthread_t fibThread2;
  243. result = pthread_create( &fibThread2, nullptr, callFunc, &fib2 );
  244. if ( result != 0 ) {
  245. std::cerr << "Could not create thread" << std::endl;
  246. return 1;
  247. }
  248. synchronize.releaseThreads(3); // wait until other threads are at this point
  249. void* returnValue;
  250. result = pthread_join( add1Thread, &returnValue );
  251. if ( result != 0 ) {
  252. std::cerr << "Could not join thread" << std::endl;
  253. return 1;
  254. }
  255. std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
  256. result = pthread_join( fibThread1, &returnValue );
  257. if ( result != 0 ) {
  258. std::cerr << "Could not join thread" << std::endl;
  259. return 1;
  260. }
  261. std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
  262. result = pthread_join( fibThread2, &returnValue );
  263. if ( result != 0 ) {
  264. std::cerr << "Could not join thread" << std::endl;
  265. return 1;
  266. }
  267. std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
  268. return 0;
  269. }