16855097cSReid Spencer //===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
26855097cSReid Spencer //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66855097cSReid Spencer //
76855097cSReid Spencer //===----------------------------------------------------------------------===//
86855097cSReid Spencer //
96855097cSReid Spencer // Parallel JIT
106855097cSReid Spencer //
116855097cSReid Spencer // This test program creates two LLVM functions then calls them from three
126855097cSReid Spencer // separate threads. It requires the pthreads library.
136855097cSReid Spencer // The three threads are created and then block waiting on a condition variable.
146855097cSReid Spencer // Once all threads are blocked on the conditional variable, the main thread
156855097cSReid Spencer // wakes them up. This complicated work is performed so that all three threads
166855097cSReid Spencer // call into the JIT at the same time (or the best possible approximation of the
176855097cSReid Spencer // same time). This test had assertion errors until I got the locking right.
182b8e4170SEugene Zelenko //
192b8e4170SEugene Zelenko //===----------------------------------------------------------------------===//
206855097cSReid Spencer
212b8e4170SEugene Zelenko #include "llvm/ADT/APInt.h"
2285c9bacaSNAKAMURA Takumi #include "llvm/ADT/STLExtras.h"
232b8e4170SEugene Zelenko #include "llvm/ExecutionEngine/ExecutionEngine.h"
246855097cSReid Spencer #include "llvm/ExecutionEngine/GenericValue.h"
25*01b3627cSxgupta #include "llvm/ExecutionEngine/MCJIT.h"
262b8e4170SEugene Zelenko #include "llvm/IR/Argument.h"
272b8e4170SEugene Zelenko #include "llvm/IR/BasicBlock.h"
28005f27a0SChandler Carruth #include "llvm/IR/Constants.h"
29005f27a0SChandler Carruth #include "llvm/IR/DerivedTypes.h"
302b8e4170SEugene Zelenko #include "llvm/IR/Function.h"
312b8e4170SEugene Zelenko #include "llvm/IR/InstrTypes.h"
322b8e4170SEugene Zelenko #include "llvm/IR/Instruction.h"
33005f27a0SChandler Carruth #include "llvm/IR/Instructions.h"
34005f27a0SChandler Carruth #include "llvm/IR/LLVMContext.h"
35005f27a0SChandler Carruth #include "llvm/IR/Module.h"
362b8e4170SEugene Zelenko #include "llvm/IR/Type.h"
372b8e4170SEugene Zelenko #include "llvm/Support/Casting.h"
382bb40357SEvan Cheng #include "llvm/Support/TargetSelect.h"
392b8e4170SEugene Zelenko #include <algorithm>
402b8e4170SEugene Zelenko #include <cassert>
412b8e4170SEugene Zelenko #include <cstddef>
422b8e4170SEugene Zelenko #include <cstdint>
436855097cSReid Spencer #include <iostream>
442b8e4170SEugene Zelenko #include <memory>
452b8e4170SEugene Zelenko #include <vector>
46605e30e9SChandler Carruth #include <pthread.h>
47cc9deb48SHans Wennborg
486855097cSReid Spencer using namespace llvm;
496855097cSReid Spencer
createAdd1(Module * M)50b800b392SChris Lattner static Function* createAdd1(Module *M) {
51473e3420SJames Y Knight LLVMContext &Context = M->getContext();
526855097cSReid Spencer // Create the add1 function entry and insert this entry into module M. The
536855097cSReid Spencer // function will have a return type of "int" and take an argument of "int".
54b800b392SChris Lattner Function *Add1F =
5513680223SJames Y Knight Function::Create(FunctionType::get(Type::getInt32Ty(Context),
5613680223SJames Y Knight {Type::getInt32Ty(Context)}, false),
5713680223SJames Y Knight Function::ExternalLinkage, "add1", M);
586855097cSReid Spencer
596855097cSReid Spencer // Add a basic block to the function. As before, it automatically inserts
606855097cSReid Spencer // because of the last argument.
61473e3420SJames Y Knight BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
626855097cSReid Spencer
636855097cSReid Spencer // Get pointers to the constant `1'.
64473e3420SJames Y Knight Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
656855097cSReid Spencer
666855097cSReid Spencer // Get pointers to the integer argument of the add1 function...
676855097cSReid Spencer assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
685717ecbaSDuncan P. N. Exon Smith Argument *ArgX = &*Add1F->arg_begin(); // Get the arg
696855097cSReid Spencer ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
706855097cSReid Spencer
716855097cSReid Spencer // Create the add instruction, inserting it into the end of BB.
72e1f6e4b2SGabor Greif Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
736855097cSReid Spencer
746855097cSReid Spencer // Create the return instruction and add it to the basic block
75473e3420SJames Y Knight ReturnInst::Create(Context, Add, BB);
766855097cSReid Spencer
776855097cSReid Spencer // Now, function add1 is ready.
786855097cSReid Spencer return Add1F;
796855097cSReid Spencer }
806855097cSReid Spencer
CreateFibFunction(Module * M)81b800b392SChris Lattner static Function *CreateFibFunction(Module *M) {
82473e3420SJames Y Knight LLVMContext &Context = M->getContext();
836855097cSReid Spencer // Create the fib function and insert it into module M. This function is said
846855097cSReid Spencer // to return an int and take an int parameter.
8513680223SJames Y Knight FunctionType *FibFTy = FunctionType::get(Type::getInt32Ty(Context),
8613680223SJames Y Knight {Type::getInt32Ty(Context)}, false);
87b800b392SChris Lattner Function *FibF =
8813680223SJames Y Knight Function::Create(FibFTy, Function::ExternalLinkage, "fib", M);
896855097cSReid Spencer
906855097cSReid Spencer // Add a basic block to the function.
91473e3420SJames Y Knight BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);
926855097cSReid Spencer
936855097cSReid Spencer // Get pointers to the constants.
94473e3420SJames Y Knight Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
95473e3420SJames Y Knight Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
966855097cSReid Spencer
976855097cSReid Spencer // Get pointer to the integer argument of the add1 function...
985717ecbaSDuncan P. N. Exon Smith Argument *ArgX = &*FibF->arg_begin(); // Get the arg.
996855097cSReid Spencer ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
1006855097cSReid Spencer
1016855097cSReid Spencer // Create the true_block.
102473e3420SJames Y Knight BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
1036855097cSReid Spencer // Create an exit block.
104473e3420SJames Y Knight BasicBlock *RecurseBB = BasicBlock::Create(Context, "recurse", FibF);
1056855097cSReid Spencer
1066855097cSReid Spencer // Create the "if (arg < 2) goto exitbb"
1071e5f00e7SOwen Anderson Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
108e9ecc68dSGabor Greif BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
1096855097cSReid Spencer
1106855097cSReid Spencer // Create: ret int 1
111473e3420SJames Y Knight ReturnInst::Create(Context, One, RetBB);
1126855097cSReid Spencer
1136855097cSReid Spencer // create fib(x-1)
114e1f6e4b2SGabor Greif Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
115e9ecc68dSGabor Greif Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
1166855097cSReid Spencer
1176855097cSReid Spencer // create fib(x-2)
118e1f6e4b2SGabor Greif Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
119e9ecc68dSGabor Greif Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
1206855097cSReid Spencer
1216855097cSReid Spencer // fib(x-1)+fib(x-2)
1226855097cSReid Spencer Value *Sum =
123e1f6e4b2SGabor Greif BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
1246855097cSReid Spencer
1256855097cSReid Spencer // Create the return instruction and add it to the basic block
126473e3420SJames Y Knight ReturnInst::Create(Context, Sum, RecurseBB);
1276855097cSReid Spencer
1286855097cSReid Spencer return FibF;
1296855097cSReid Spencer }
1306855097cSReid Spencer
1316855097cSReid Spencer struct threadParams {
1326855097cSReid Spencer ExecutionEngine* EE;
1336855097cSReid Spencer Function* F;
1346855097cSReid Spencer int value;
1356855097cSReid Spencer };
1366855097cSReid Spencer
1376855097cSReid Spencer // We block the subthreads just before they begin to execute:
1386855097cSReid Spencer // we want all of them to call into the JIT at the same time,
1396855097cSReid Spencer // to verify that the locking is working correctly.
1406855097cSReid Spencer class WaitForThreads
1416855097cSReid Spencer {
1426855097cSReid Spencer public:
WaitForThreads()1436855097cSReid Spencer WaitForThreads()
1446855097cSReid Spencer {
1456855097cSReid Spencer n = 0;
1466855097cSReid Spencer waitFor = 0;
1476855097cSReid Spencer
148cc9deb48SHans Wennborg int result = pthread_cond_init( &condition, nullptr );
149e7a411dfSHans Wennborg (void)result;
1506855097cSReid Spencer assert( result == 0 );
1516855097cSReid Spencer
152cc9deb48SHans Wennborg result = pthread_mutex_init( &mutex, nullptr );
1536855097cSReid Spencer assert( result == 0 );
1546855097cSReid Spencer }
1556855097cSReid Spencer
~WaitForThreads()1566855097cSReid Spencer ~WaitForThreads()
1576855097cSReid Spencer {
1586855097cSReid Spencer int result = pthread_cond_destroy( &condition );
159de14dcc2SAhmed Charles (void)result;
1606855097cSReid Spencer assert( result == 0 );
1616855097cSReid Spencer
1626855097cSReid Spencer result = pthread_mutex_destroy( &mutex );
1636855097cSReid Spencer assert( result == 0 );
1646855097cSReid Spencer }
1656855097cSReid Spencer
1666855097cSReid Spencer // All threads will stop here until another thread calls releaseThreads
block()1676855097cSReid Spencer void block()
1686855097cSReid Spencer {
1696855097cSReid Spencer int result = pthread_mutex_lock( &mutex );
170de14dcc2SAhmed Charles (void)result;
1716855097cSReid Spencer assert( result == 0 );
1726855097cSReid Spencer n ++;
1736855097cSReid Spencer //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
1746855097cSReid Spencer
1756855097cSReid Spencer assert( waitFor == 0 || n <= waitFor );
1766855097cSReid Spencer if ( waitFor > 0 && n == waitFor )
1776855097cSReid Spencer {
1786855097cSReid Spencer // There are enough threads blocked that we can release all of them
1796855097cSReid Spencer std::cout << "Unblocking threads from block()" << std::endl;
1806855097cSReid Spencer unblockThreads();
1816855097cSReid Spencer }
1826855097cSReid Spencer else
1836855097cSReid Spencer {
1846855097cSReid Spencer // We just need to wait until someone unblocks us
1856855097cSReid Spencer result = pthread_cond_wait( &condition, &mutex );
1866855097cSReid Spencer assert( result == 0 );
1876855097cSReid Spencer }
1886855097cSReid Spencer
1896855097cSReid Spencer // unlock the mutex before returning
1906855097cSReid Spencer result = pthread_mutex_unlock( &mutex );
1916855097cSReid Spencer assert( result == 0 );
1926855097cSReid Spencer }
1936855097cSReid Spencer
1946855097cSReid Spencer // If there are num or more threads blocked, it will signal them all
1956855097cSReid Spencer // Otherwise, this thread blocks until there are enough OTHER threads
1966855097cSReid Spencer // blocked
releaseThreads(size_t num)1976855097cSReid Spencer void releaseThreads( size_t num )
1986855097cSReid Spencer {
1996855097cSReid Spencer int result = pthread_mutex_lock( &mutex );
200de14dcc2SAhmed Charles (void)result;
2016855097cSReid Spencer assert( result == 0 );
2026855097cSReid Spencer
2036855097cSReid Spencer if ( n >= num ) {
2046855097cSReid Spencer std::cout << "Unblocking threads from releaseThreads()" << std::endl;
2056855097cSReid Spencer unblockThreads();
2066855097cSReid Spencer }
2076855097cSReid Spencer else
2086855097cSReid Spencer {
2096855097cSReid Spencer waitFor = num;
2106855097cSReid Spencer pthread_cond_wait( &condition, &mutex );
2116855097cSReid Spencer }
2126855097cSReid Spencer
2136855097cSReid Spencer // unlock the mutex before returning
2146855097cSReid Spencer result = pthread_mutex_unlock( &mutex );
2156855097cSReid Spencer assert( result == 0 );
2166855097cSReid Spencer }
2176855097cSReid Spencer
2186855097cSReid Spencer private:
unblockThreads()2196855097cSReid Spencer void unblockThreads()
2206855097cSReid Spencer {
2216855097cSReid Spencer // Reset the counters to zero: this way, if any new threads
2226855097cSReid Spencer // enter while threads are exiting, they will block instead
2236855097cSReid Spencer // of triggering a new release of threads
2246855097cSReid Spencer n = 0;
2256855097cSReid Spencer
2266855097cSReid Spencer // Reset waitFor to zero: this way, if waitFor threads enter
2276855097cSReid Spencer // while threads are exiting, they will block instead of
2286855097cSReid Spencer // triggering a new release of threads
2296855097cSReid Spencer waitFor = 0;
2306855097cSReid Spencer
2316855097cSReid Spencer int result = pthread_cond_broadcast( &condition );
2323bb7d41aSChandler Carruth (void)result;
2333bb7d41aSChandler Carruth assert(result == 0);
2346855097cSReid Spencer }
2356855097cSReid Spencer
2366855097cSReid Spencer size_t n;
2376855097cSReid Spencer size_t waitFor;
2386855097cSReid Spencer pthread_cond_t condition;
2396855097cSReid Spencer pthread_mutex_t mutex;
2406855097cSReid Spencer };
2416855097cSReid Spencer
2426855097cSReid Spencer static WaitForThreads synchronize;
2436855097cSReid Spencer
callFunc(void * param)2446855097cSReid Spencer void* callFunc( void* param )
2456855097cSReid Spencer {
2466855097cSReid Spencer struct threadParams* p = (struct threadParams*) param;
2476855097cSReid Spencer
2486855097cSReid Spencer // Call the `foo' function with no arguments:
2496855097cSReid Spencer std::vector<GenericValue> Args(1);
2508a9ae48dSReid Spencer Args[0].IntVal = APInt(32, p->value);
2516855097cSReid Spencer
2526855097cSReid Spencer synchronize.block(); // wait until other threads are at this point
2536855097cSReid Spencer GenericValue gv = p->EE->runFunction(p->F, Args);
2546855097cSReid Spencer
2558a9ae48dSReid Spencer return (void*)(intptr_t)gv.IntVal.getZExtValue();
2566855097cSReid Spencer }
2576855097cSReid Spencer
main()258d24df245SChris Lattner int main() {
259d24df245SChris Lattner InitializeNativeTarget();
260*01b3627cSxgupta LLVMInitializeNativeAsmPrinter();
2616773d388SOwen Anderson LLVMContext Context;
262d24df245SChris Lattner
2636855097cSReid Spencer // Create some module to put our function into it.
2640eaee545SJonas Devlieghere std::unique_ptr<Module> Owner = std::make_unique<Module>("test", Context);
2652a8a2795SRafael Espindola Module *M = Owner.get();
2666855097cSReid Spencer
2676855097cSReid Spencer Function* add1F = createAdd1( M );
2686855097cSReid Spencer Function* fibF = CreateFibFunction( M );
2696855097cSReid Spencer
2706855097cSReid Spencer // Now we create the JIT.
2712a8a2795SRafael Espindola ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
2726855097cSReid Spencer
2736855097cSReid Spencer //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
2746855097cSReid Spencer //~ std::cout << "\n\nRunning foo: " << std::flush;
2756855097cSReid Spencer
2766855097cSReid Spencer // Create one thread for add1 and two threads for fib
2776855097cSReid Spencer struct threadParams add1 = { EE, add1F, 1000 };
2786855097cSReid Spencer struct threadParams fib1 = { EE, fibF, 39 };
2796855097cSReid Spencer struct threadParams fib2 = { EE, fibF, 42 };
2806855097cSReid Spencer
2816855097cSReid Spencer pthread_t add1Thread;
282cc9deb48SHans Wennborg int result = pthread_create( &add1Thread, nullptr, callFunc, &add1 );
2836855097cSReid Spencer if ( result != 0 ) {
2846855097cSReid Spencer std::cerr << "Could not create thread" << std::endl;
2856855097cSReid Spencer return 1;
2866855097cSReid Spencer }
2876855097cSReid Spencer
2886855097cSReid Spencer pthread_t fibThread1;
289cc9deb48SHans Wennborg result = pthread_create( &fibThread1, nullptr, callFunc, &fib1 );
2906855097cSReid Spencer if ( result != 0 ) {
2916855097cSReid Spencer std::cerr << "Could not create thread" << std::endl;
2926855097cSReid Spencer return 1;
2936855097cSReid Spencer }
2946855097cSReid Spencer
2956855097cSReid Spencer pthread_t fibThread2;
296cc9deb48SHans Wennborg result = pthread_create( &fibThread2, nullptr, callFunc, &fib2 );
2976855097cSReid Spencer if ( result != 0 ) {
2986855097cSReid Spencer std::cerr << "Could not create thread" << std::endl;
2996855097cSReid Spencer return 1;
3006855097cSReid Spencer }
3016855097cSReid Spencer
3026855097cSReid Spencer synchronize.releaseThreads(3); // wait until other threads are at this point
3036855097cSReid Spencer
3046855097cSReid Spencer void* returnValue;
3056855097cSReid Spencer result = pthread_join( add1Thread, &returnValue );
3066855097cSReid Spencer if ( result != 0 ) {
3076855097cSReid Spencer std::cerr << "Could not join thread" << std::endl;
3086855097cSReid Spencer return 1;
3096855097cSReid Spencer }
3108640f2bdSReid Spencer std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
3116855097cSReid Spencer
3126855097cSReid Spencer result = pthread_join( fibThread1, &returnValue );
3136855097cSReid Spencer if ( result != 0 ) {
3146855097cSReid Spencer std::cerr << "Could not join thread" << std::endl;
3156855097cSReid Spencer return 1;
3166855097cSReid Spencer }
3178640f2bdSReid Spencer std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
3186855097cSReid Spencer
3196855097cSReid Spencer result = pthread_join( fibThread2, &returnValue );
3206855097cSReid Spencer if ( result != 0 ) {
3216855097cSReid Spencer std::cerr << "Could not join thread" << std::endl;
3226855097cSReid Spencer return 1;
3236855097cSReid Spencer }
3248640f2bdSReid Spencer std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
3256855097cSReid Spencer
3266855097cSReid Spencer return 0;
3276855097cSReid Spencer }
328