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