blob: 83e2640636f5329f5859aaa589e0acba9dd54764 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner45ca7c12007-12-29 20:37:57 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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>
Owen Anderson25209b42009-07-01 16:58:40 +000021#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#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"
Chris Lattner8ed24c52009-06-17 16:48:44 +000030#include "llvm/Target/TargetSelect.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include <iostream>
32using namespace llvm;
33
34static 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.
38 Function *Add1F =
39 cast<Function>(M->getOrInsertFunction("add1", Type::Int32Ty, Type::Int32Ty,
40 (Type *)0));
41
42 // Add a basic block to the function. As before, it automatically inserts
43 // because of the last argument.
Gabor Greifd6da1d02008-04-06 20:25:17 +000044 BasicBlock *BB = BasicBlock::Create("EntryBlock", Add1F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045
46 // Get pointers to the constant `1'.
Owen Andersoneacb44d2009-07-24 23:12:02 +000047 Value *One = ConstantInt::get(Type::Int32Ty, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
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.
53
54 // Create the add instruction, inserting it into the end of BB.
Gabor Greifa645dd32008-05-16 19:29:10 +000055 Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056
57 // Create the return instruction and add it to the basic block
Gabor Greifd6da1d02008-04-06 20:25:17 +000058 ReturnInst::Create(Add, BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60 // Now, function add1 is ready.
61 return Add1F;
62}
63
64static 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.
67 Function *FibF =
68 cast<Function>(M->getOrInsertFunction("fib", Type::Int32Ty, Type::Int32Ty,
69 (Type *)0));
70
71 // Add a basic block to the function.
Gabor Greifd6da1d02008-04-06 20:25:17 +000072 BasicBlock *BB = BasicBlock::Create("EntryBlock", FibF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073
74 // Get pointers to the constants.
Owen Andersoneacb44d2009-07-24 23:12:02 +000075 Value *One = ConstantInt::get(Type::Int32Ty, 1);
76 Value *Two = ConstantInt::get(Type::Int32Ty, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077
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.
81
82 // Create the true_block.
Gabor Greifd6da1d02008-04-06 20:25:17 +000083 BasicBlock *RetBB = BasicBlock::Create("return", FibF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 // Create an exit block.
Gabor Greifd6da1d02008-04-06 20:25:17 +000085 BasicBlock* RecurseBB = BasicBlock::Create("recurse", FibF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
87 // Create the "if (arg < 2) goto exitbb"
Owen Anderson6601fcd2009-07-09 23:48:35 +000088 Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
Gabor Greifd6da1d02008-04-06 20:25:17 +000089 BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090
91 // Create: ret int 1
Gabor Greifd6da1d02008-04-06 20:25:17 +000092 ReturnInst::Create(One, RetBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093
94 // create fib(x-1)
Gabor Greifa645dd32008-05-16 19:29:10 +000095 Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
Gabor Greifd6da1d02008-04-06 20:25:17 +000096 Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097
98 // create fib(x-2)
Gabor Greifa645dd32008-05-16 19:29:10 +000099 Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000100 Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101
102 // fib(x-1)+fib(x-2)
103 Value *Sum =
Gabor Greifa645dd32008-05-16 19:29:10 +0000104 BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105
106 // Create the return instruction and add it to the basic block
Gabor Greifd6da1d02008-04-06 20:25:17 +0000107 ReturnInst::Create(Sum, RecurseBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
109 return FibF;
110}
111
112struct threadParams {
113 ExecutionEngine* EE;
114 Function* F;
115 int value;
116};
117
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.
121class WaitForThreads
122{
123public:
124 WaitForThreads()
125 {
126 n = 0;
127 waitFor = 0;
128
129 int result = pthread_cond_init( &condition, NULL );
130 assert( result == 0 );
131
132 result = pthread_mutex_init( &mutex, NULL );
133 assert( result == 0 );
134 }
135
136 ~WaitForThreads()
137 {
138 int result = pthread_cond_destroy( &condition );
139 assert( result == 0 );
140
141 result = pthread_mutex_destroy( &mutex );
142 assert( result == 0 );
143 }
144
145 // All threads will stop here until another thread calls releaseThreads
146 void block()
147 {
148 int result = pthread_mutex_lock( &mutex );
149 assert( result == 0 );
150 n ++;
151 //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
152
153 assert( waitFor == 0 || n <= waitFor );
154 if ( waitFor > 0 && n == waitFor )
155 {
156 // There are enough threads blocked that we can release all of them
157 std::cout << "Unblocking threads from block()" << std::endl;
158 unblockThreads();
159 }
160 else
161 {
162 // We just need to wait until someone unblocks us
163 result = pthread_cond_wait( &condition, &mutex );
164 assert( result == 0 );
165 }
166
167 // unlock the mutex before returning
168 result = pthread_mutex_unlock( &mutex );
169 assert( result == 0 );
170 }
171
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
174 // blocked
175 void releaseThreads( size_t num )
176 {
177 int result = pthread_mutex_lock( &mutex );
178 assert( result == 0 );
179
180 if ( n >= num ) {
181 std::cout << "Unblocking threads from releaseThreads()" << std::endl;
182 unblockThreads();
183 }
184 else
185 {
186 waitFor = num;
187 pthread_cond_wait( &condition, &mutex );
188 }
189
190 // unlock the mutex before returning
191 result = pthread_mutex_unlock( &mutex );
192 assert( result == 0 );
193 }
194
195private:
196 void unblockThreads()
197 {
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
201 n = 0;
202
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
206 waitFor = 0;
207
208 int result = pthread_cond_broadcast( &condition );
Chris Lattnerbc610fc2008-04-08 05:49:09 +0000209 assert(result == 0); result=result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 }
211
212 size_t n;
213 size_t waitFor;
214 pthread_cond_t condition;
215 pthread_mutex_t mutex;
216};
217
218static WaitForThreads synchronize;
219
220void* callFunc( void* param )
221{
222 struct threadParams* p = (struct threadParams*) param;
223
224 // Call the `foo' function with no arguments:
225 std::vector<GenericValue> Args(1);
226 Args[0].IntVal = APInt(32, p->value);
227
228 synchronize.block(); // wait until other threads are at this point
229 GenericValue gv = p->EE->runFunction(p->F, Args);
230
231 return (void*)(intptr_t)gv.IntVal.getZExtValue();
232}
233
Chris Lattner8ed24c52009-06-17 16:48:44 +0000234int main() {
235 InitializeNativeTarget();
Owen Anderson25209b42009-07-01 16:58:40 +0000236 LLVMContext Context;
Chris Lattner8ed24c52009-06-17 16:48:44 +0000237
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 // Create some module to put our function into it.
Owen Andersona148fdd2009-07-01 21:22:36 +0000239 Module *M = new Module("test", Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 Function* add1F = createAdd1( M );
242 Function* fibF = CreateFibFunction( M );
243
244 // Now we create the JIT.
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000245 ExecutionEngine* EE = EngineBuilder(M).create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
247 //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
248 //~ std::cout << "\n\nRunning foo: " << std::flush;
249
250 // Create one thread for add1 and two threads for fib
251 struct threadParams add1 = { EE, add1F, 1000 };
252 struct threadParams fib1 = { EE, fibF, 39 };
253 struct threadParams fib2 = { EE, fibF, 42 };
254
255 pthread_t add1Thread;
256 int result = pthread_create( &add1Thread, NULL, callFunc, &add1 );
257 if ( result != 0 ) {
258 std::cerr << "Could not create thread" << std::endl;
259 return 1;
260 }
261
262 pthread_t fibThread1;
263 result = pthread_create( &fibThread1, NULL, callFunc, &fib1 );
264 if ( result != 0 ) {
265 std::cerr << "Could not create thread" << std::endl;
266 return 1;
267 }
268
269 pthread_t fibThread2;
270 result = pthread_create( &fibThread2, NULL, callFunc, &fib2 );
271 if ( result != 0 ) {
272 std::cerr << "Could not create thread" << std::endl;
273 return 1;
274 }
275
276 synchronize.releaseThreads(3); // wait until other threads are at this point
277
278 void* returnValue;
279 result = pthread_join( add1Thread, &returnValue );
280 if ( result != 0 ) {
281 std::cerr << "Could not join thread" << std::endl;
282 return 1;
283 }
284 std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
285
286 result = pthread_join( fibThread1, &returnValue );
287 if ( result != 0 ) {
288 std::cerr << "Could not join thread" << std::endl;
289 return 1;
290 }
291 std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
292
293 result = pthread_join( fibThread2, &returnValue );
294 if ( result != 0 ) {
295 std::cerr << "Could not join thread" << std::endl;
296 return 1;
297 }
298 std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
299
300 return 0;
301}