1 //===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/ModuleProvider.h"
27 #include "llvm/ExecutionEngine/JIT.h"
28 #include "llvm/ExecutionEngine/Interpreter.h"
29 #include "llvm/ExecutionEngine/GenericValue.h"
30 #include "llvm/Target/TargetSelect.h"
34 static Function* createAdd1(Module *M) {
35 // Create the add1 function entry and insert this entry into module M. The
36 // function will have a return type of "int" and take an argument of "int".
37 // The '0' terminates the list of argument types.
39 cast<Function>(M->getOrInsertFunction("add1", Type::Int32Ty, Type::Int32Ty,
42 // Add a basic block to the function. As before, it automatically inserts
43 // because of the last argument.
44 BasicBlock *BB = BasicBlock::Create("EntryBlock", Add1F);
46 // Get pointers to the constant `1'.
47 Value *One = ConstantInt::get(Type::Int32Ty, 1);
49 // Get pointers to the integer argument of the add1 function...
50 assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
51 Argument *ArgX = Add1F->arg_begin(); // Get the arg
52 ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
54 // Create the add instruction, inserting it into the end of BB.
55 Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
57 // Create the return instruction and add it to the basic block
58 ReturnInst::Create(Add, BB);
60 // Now, function add1 is ready.
64 static Function *CreateFibFunction(Module *M) {
65 // Create the fib function and insert it into module M. This function is said
66 // to return an int and take an int parameter.
68 cast<Function>(M->getOrInsertFunction("fib", Type::Int32Ty, Type::Int32Ty,
71 // Add a basic block to the function.
72 BasicBlock *BB = BasicBlock::Create("EntryBlock", FibF);
74 // Get pointers to the constants.
75 Value *One = ConstantInt::get(Type::Int32Ty, 1);
76 Value *Two = ConstantInt::get(Type::Int32Ty, 2);
78 // Get pointer to the integer argument of the add1 function...
79 Argument *ArgX = FibF->arg_begin(); // Get the arg.
80 ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
82 // Create the true_block.
83 BasicBlock *RetBB = BasicBlock::Create("return", FibF);
84 // Create an exit block.
85 BasicBlock* RecurseBB = BasicBlock::Create("recurse", FibF);
87 // Create the "if (arg < 2) goto exitbb"
88 Value *CondInst = new ICmpInst(ICmpInst::ICMP_SLE, ArgX, Two, "cond", BB);
89 BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
92 ReturnInst::Create(One, RetBB);
95 Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
96 Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
99 Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
100 Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
104 BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
106 // Create the return instruction and add it to the basic block
107 ReturnInst::Create(Sum, RecurseBB);
112 struct threadParams {
118 // We block the subthreads just before they begin to execute:
119 // we want all of them to call into the JIT at the same time,
120 // to verify that the locking is working correctly.
129 int result = pthread_cond_init( &condition, NULL );
130 assert( result == 0 );
132 result = pthread_mutex_init( &mutex, NULL );
133 assert( result == 0 );
138 int result = pthread_cond_destroy( &condition );
139 assert( result == 0 );
141 result = pthread_mutex_destroy( &mutex );
142 assert( result == 0 );
145 // All threads will stop here until another thread calls releaseThreads
148 int result = pthread_mutex_lock( &mutex );
149 assert( result == 0 );
151 //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
153 assert( waitFor == 0 || n <= waitFor );
154 if ( waitFor > 0 && n == waitFor )
156 // There are enough threads blocked that we can release all of them
157 std::cout << "Unblocking threads from block()" << std::endl;
162 // We just need to wait until someone unblocks us
163 result = pthread_cond_wait( &condition, &mutex );
164 assert( result == 0 );
167 // unlock the mutex before returning
168 result = pthread_mutex_unlock( &mutex );
169 assert( result == 0 );
172 // If there are num or more threads blocked, it will signal them all
173 // Otherwise, this thread blocks until there are enough OTHER threads
175 void releaseThreads( size_t num )
177 int result = pthread_mutex_lock( &mutex );
178 assert( result == 0 );
181 std::cout << "Unblocking threads from releaseThreads()" << std::endl;
187 pthread_cond_wait( &condition, &mutex );
190 // unlock the mutex before returning
191 result = pthread_mutex_unlock( &mutex );
192 assert( result == 0 );
196 void unblockThreads()
198 // Reset the counters to zero: this way, if any new threads
199 // enter while threads are exiting, they will block instead
200 // of triggering a new release of threads
203 // Reset waitFor to zero: this way, if waitFor threads enter
204 // while threads are exiting, they will block instead of
205 // triggering a new release of threads
208 int result = pthread_cond_broadcast( &condition );
209 assert(result == 0); result=result;
214 pthread_cond_t condition;
215 pthread_mutex_t mutex;
218 static WaitForThreads synchronize;
220 void* callFunc( void* param )
222 struct threadParams* p = (struct threadParams*) param;
224 // Call the `foo' function with no arguments:
225 std::vector<GenericValue> Args(1);
226 Args[0].IntVal = APInt(32, p->value);
228 synchronize.block(); // wait until other threads are at this point
229 GenericValue gv = p->EE->runFunction(p->F, Args);
231 return (void*)(intptr_t)gv.IntVal.getZExtValue();
235 InitializeNativeTarget();
238 // Create some module to put our function into it.
239 Module *M = new Module("test", &Context);
241 Function* add1F = createAdd1( M );
242 Function* fibF = CreateFibFunction( M );
244 // Now we create the JIT.
245 ExistingModuleProvider* MP = new ExistingModuleProvider(M);
246 ExecutionEngine* EE = ExecutionEngine::create(MP, false);
248 //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
249 //~ std::cout << "\n\nRunning foo: " << std::flush;
251 // Create one thread for add1 and two threads for fib
252 struct threadParams add1 = { EE, add1F, 1000 };
253 struct threadParams fib1 = { EE, fibF, 39 };
254 struct threadParams fib2 = { EE, fibF, 42 };
256 pthread_t add1Thread;
257 int result = pthread_create( &add1Thread, NULL, callFunc, &add1 );
259 std::cerr << "Could not create thread" << std::endl;
263 pthread_t fibThread1;
264 result = pthread_create( &fibThread1, NULL, callFunc, &fib1 );
266 std::cerr << "Could not create thread" << std::endl;
270 pthread_t fibThread2;
271 result = pthread_create( &fibThread2, NULL, callFunc, &fib2 );
273 std::cerr << "Could not create thread" << std::endl;
277 synchronize.releaseThreads(3); // wait until other threads are at this point
280 result = pthread_join( add1Thread, &returnValue );
282 std::cerr << "Could not join thread" << std::endl;
285 std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
287 result = pthread_join( fibThread1, &returnValue );
289 std::cerr << "Could not join thread" << std::endl;
292 std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
294 result = pthread_join( fibThread2, &returnValue );
296 std::cerr << "Could not join thread" << std::endl;
299 std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;