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