source: icGREP/icgrep-devel/icgrep/kernels/pipeline.cpp @ 5266

Last change on this file since 5266 was 5266, checked in by cameron, 2 years ago

Fixes

File size: 14.5 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
6#include "pipeline.h"
7#include <toolchain.h>
8#include <IR_Gen/idisa_builder.h>
9#include <kernels/interface.h>
10#include <kernels/kernel.h>
11#include <iostream>
12#include <unordered_map>
13
14using namespace kernel;
15using namespace parabix;
16using namespace llvm;
17
18using ProducerTable = std::vector<std::vector<std::pair<unsigned, unsigned>>>;
19
20ProducerTable createProducerTable(const std::vector<KernelBuilder *> & kernels) {
21    ProducerTable producerTable(kernels.size());
22   
23    std::vector<std::vector<bool>> userTable(kernels.size());
24   
25    // First prepare a map from streamSet output buffers to their producing kernel and output index.
26    std::unordered_map<const StreamSetBuffer *, std::pair<unsigned, unsigned>> bufferMap;
27   
28    for (unsigned k = 0; k < kernels.size(); k++) {
29        auto outputSets = kernels[k]->getStreamSetOutputBuffers();
30        for (unsigned j = 0; j < outputSets.size(); j++) {
31            userTable[k].push_back(false);
32            bufferMap.insert(std::make_pair(outputSets[j], std::make_pair(k, j)));
33        }
34    }
35    for (unsigned k = 0; k < kernels.size(); k++) {
36        auto inputSets = kernels[k]->getStreamSetInputBuffers();
37        for (unsigned i = 0; i < inputSets.size(); i++) {
38            auto f = bufferMap.find(inputSets[i]);
39            if (f == bufferMap.end()) {
40                llvm::report_fatal_error("Pipeline error: input buffer #" + std::to_string(i) + " of " + kernels[k]->getName() + ": no corresponding output buffer. ");
41            }
42            producerTable[k].push_back(f->second);
43            unsigned sourceKernel, outputIndex;
44            std::tie(sourceKernel, outputIndex) = f->second;
45            if (sourceKernel >= k) {
46                llvm::report_fatal_error("Pipeline error: input buffer #" + std::to_string(i) + " of " + kernels[k]->getName() + ": not defined before use. ");
47            }
48            //errs() << "sourceKernel: " + std::to_string(sourceKernel) + ", outputIndex: " + std::to_string(outputIndex) + ", user: " + std::to_string(k) + "\n";
49            userTable[sourceKernel][outputIndex]= true;
50           
51        }
52    }
53    /*
54    for (unsigned k = 0; k < kernels.size(); k++) {
55        auto outputSets = kernels[k]->getStreamSetOutputBuffers();
56        //errs() << "kernel: " + kernels[k]->getName() + "\n";
57        for (unsigned j = 0; j < outputSets.size(); j++) {
58            if (userTable[k][j] == false) {
59                llvm::report_fatal_error("Pipeline error: output buffer #" + std::to_string(j) + " of " + kernels[k]->getName() + ": no users. ");
60            }
61        }
62    }
63    */
64    return producerTable;
65}
66
67
68Function * generateSegmentParallelPipelineThreadFunction(std::string name, IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels, Type * sharedStructType, ProducerTable & producerTable, int id) {
69   
70    // ProducerPos[k][i] will hold the producedItemCount of the i^th output stream
71    // set of the k^th kernel.  These values will be loaded immediately after the
72    // doSegment and finalSegment calls for kernel k and later used as the
73    // producer position arguments for later doSegment/finalSegment calls.
74   
75    std::vector<std::vector<Value *>> ProducerPos;
76   
77   
78    const auto ip = iBuilder->saveIP();
79   
80    Module * m = iBuilder->getModule();
81    Type * const size_ty = iBuilder->getSizeTy();
82    Type * const voidTy = iBuilder->getVoidTy();
83    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
84    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
85
86    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
87    threadFunc->setCallingConv(CallingConv::C);
88    Function::arg_iterator args = threadFunc->arg_begin();
89
90    Value * const input = &*(args++);
91    input->setName("input");
92
93    unsigned threadNum = codegen::ThreadNum;
94
95     // Create the basic blocks for the thread function.
96    BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc, 0);
97    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", threadFunc, 0);
98    BasicBlock * exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc, 0);
99   
100    std::vector<BasicBlock *> segmentWait;
101    std::vector<BasicBlock *> segmentLoopBody;
102    for (unsigned i = 0; i < kernels.size(); i++) {
103        std::string kname = kernels[i]->getName();
104        segmentWait.push_back(BasicBlock::Create(iBuilder->getContext(), kname + "Wait", threadFunc, 0));
105        segmentLoopBody.push_back(BasicBlock::Create(iBuilder->getContext(), "do_" + kname, threadFunc, 0));
106    }
107
108    iBuilder->SetInsertPoint(entryBlock);
109    Value * sharedStruct = iBuilder->CreateBitCast(input, PointerType::get(sharedStructType, 0));
110    Constant * myThreadId = ConstantInt::get(size_ty, id);
111    std::vector<Value *> instancePtrs;
112    for (unsigned i = 0; i < kernels.size(); i++) {
113        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
114        instancePtrs.push_back(iBuilder->CreateLoad(ptr));
115    }
116   
117    iBuilder->CreateBr(segmentLoop);
118
119    iBuilder->SetInsertPoint(segmentLoop);
120    PHINode * segNo = iBuilder->CreatePHI(size_ty, 2, "segNo");
121    segNo->addIncoming(myThreadId, entryBlock);
122    Value * nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
123    unsigned last_kernel = kernels.size() - 1;
124    Value * alreadyDone = kernels[last_kernel]->getTerminationSignal(instancePtrs[last_kernel]);
125    iBuilder->CreateCondBr(alreadyDone, exitThreadBlock, segmentWait[0]);
126   
127    Value * doFinal = ConstantInt::getNullValue(iBuilder->getInt1Ty());
128
129    for (unsigned k = 0; k < kernels.size(); k++) {
130        iBuilder->SetInsertPoint(segmentWait[k]);
131        Value * processedSegmentCount = kernels[k]->acquireLogicalSegmentNo(instancePtrs[k]);
132        Value * cond = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
133        iBuilder->CreateCondBr(cond, segmentLoopBody[k], segmentWait[k]);
134       
135        iBuilder->SetInsertPoint(segmentLoopBody[k]);
136       
137        //iBuilder->CallPrintInt(kernels[k]->getName() + " segment #", segNo);
138        if (k == last_kernel) {
139            segNo->addIncoming(iBuilder->CreateAdd(segNo, ConstantInt::get(size_ty, threadNum)), segmentLoopBody[last_kernel]);
140        }
141        std::vector<Value *> doSegmentArgs = {instancePtrs[k], doFinal};
142        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
143            unsigned producerKernel, outputIndex;
144            std::tie(producerKernel, outputIndex) = producerTable[k][j];
145            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
146            //iBuilder->CallPrintInt(kernels[k]->getName() + " producerPos[" + std::to_string(j) + "] ", doSegmentArgs.back());
147
148        }
149        kernels[k]->createDoSegmentCall(doSegmentArgs);
150        std::vector<Value *> produced;
151        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
152            produced.push_back(kernels[k]->getProducedItemCount(instancePtrs[k], kernels[k]->getStreamOutputs()[i].name));
153        }
154        ProducerPos.push_back(produced);
155        if (! (kernels[k]->hasNoTerminateAttribute())) {
156            Value * terminated = kernels[k]->getTerminationSignal(instancePtrs[k]);
157            doFinal = iBuilder->CreateOr(doFinal, terminated);
158        }
159        kernels[k]->releaseLogicalSegmentNo(instancePtrs[k], nextSegNo);
160        if (k == last_kernel) break;
161        iBuilder->CreateBr(segmentWait[k+1]);
162    }
163    iBuilder->CreateCondBr(doFinal, exitThreadBlock, segmentLoop);
164
165    iBuilder->SetInsertPoint(exitThreadBlock);
166    Value * nullVal = Constant::getNullValue(voidPtrTy);
167    iBuilder->CreatePThreadExitCall(nullVal);
168    iBuilder->CreateRetVoid();
169    iBuilder->restoreIP(ip);
170
171    return threadFunc;
172}
173
174// Given a computation expressed as a logical pipeline of K kernels k0, k_1, ...k_(K-1)
175// operating over an input stream set S, a segment-parallel implementation divides the input
176// into segments and coordinates a set of T <= K threads to each process one segment at a time.   
177// Let S_0, S_1, ... S_N be the segments of S.   Segments are assigned to threads in a round-robin
178// fashion such that processing of segment S_i by the full pipeline is carried out by thread i mod T.
179
180
181void generateSegmentParallelPipeline(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
182   
183    unsigned threadNum = codegen::ThreadNum;
184   
185    Module * m = iBuilder->getModule();
186   
187    Type * const size_ty = iBuilder->getSizeTy();
188    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
189    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
190   
191    for (auto k : kernels) k->createInstance();
192   
193    ProducerTable producerTable = createProducerTable(kernels);
194   
195    Type * const pthreadsTy = ArrayType::get(size_ty, threadNum);
196    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
197    std::vector<Value *> pthreadsPtrs;
198    for (unsigned i = 0; i < threadNum; i++) {
199        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
200    }
201    Value * nullVal = Constant::getNullValue(voidPtrTy);
202    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
203   
204    std::vector<Type *> structTypes;
205    for (unsigned i = 0; i < kernels.size(); i++) {
206        structTypes.push_back(kernels[i]->getInstance()->getType());
207    }
208    Type * sharedStructType = StructType::get(m->getContext(), structTypes);
209   
210    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
211    for (unsigned i = 0; i < kernels.size(); i++) {
212        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
213        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
214    }
215   
216    std::vector<Function *> thread_functions;
217    const auto ip = iBuilder->saveIP();
218    for (unsigned i = 0; i < threadNum; i++) {
219        thread_functions.push_back(generateSegmentParallelPipelineThreadFunction("thread"+std::to_string(i), iBuilder, kernels, sharedStructType, producerTable, i));
220    }
221    iBuilder->restoreIP(ip);
222   
223    for (unsigned i = 0; i < threadNum; i++) {
224        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, thread_functions[i], iBuilder->CreateBitCast(sharedStruct, int8PtrTy));
225    }
226   
227    std::vector<Value *> threadIDs;
228    for (unsigned i = 0; i < threadNum; i++) { 
229        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
230    }
231   
232    for (unsigned i = 0; i < threadNum; i++) { 
233        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
234    }
235   
236}
237
238void generatePipelineParallel(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
239   
240    Type * pthreadTy = iBuilder->getSizeTy();
241    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
242    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
243   
244    Type * const pthreadsTy = ArrayType::get(pthreadTy, kernels.size());
245   
246    for (auto k : kernels) k->createInstance();
247   
248    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
249    std::vector<Value *> pthreadsPtrs;
250    for (unsigned i = 0; i < kernels.size(); i++) {
251        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
252    }
253    Value * nullVal = Constant::getNullValue(voidPtrTy);
254    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
255   
256    std::vector<Function *> kernel_functions;
257    const auto ip = iBuilder->saveIP();
258    for (unsigned i = 0; i < kernels.size(); i++) {
259        kernel_functions.push_back(kernels[i]->generateThreadFunction("k_"+std::to_string(i)));
260    }
261    iBuilder->restoreIP(ip);
262   
263    for (unsigned i = 0; i < kernels.size(); i++) {
264        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, kernel_functions[i], iBuilder->CreateBitCast(kernels[i]->getInstance(), int8PtrTy));
265    }
266   
267    std::vector<Value *> threadIDs;
268    for (unsigned i = 0; i < kernels.size(); i++) { 
269        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
270    }
271   
272    for (unsigned i = 0; i < kernels.size(); i++) { 
273        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
274    }
275}
276
277
278void generatePipelineLoop(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
279    for (auto k : kernels) k->createInstance();
280   
281    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
282    Function * main = entryBlock->getParent();
283   
284    // Create the basic blocks for the loop.
285    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", main, 0);
286    BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), "exitBlock", main, 0);
287   
288    ProducerTable producerTable = createProducerTable(kernels);
289   
290    // ProducerPos[k][i] will hold the producedItemCount of the i^th output stream
291    // set of the k^th kernel.  These values will be loaded immediately after the
292    // doSegment and finalSegment calls for kernel k and later used as the
293    // producer position arguments for later doSegment/finalSegment calls.
294   
295    std::vector<std::vector<Value *>> ProducerPos;
296   
297    iBuilder->CreateBr(segmentLoop);
298    iBuilder->SetInsertPoint(segmentLoop);
299
300    Value * terminationFound = ConstantInt::getNullValue(iBuilder->getInt1Ty());
301    for (unsigned k = 0; k < kernels.size(); k++) {
302        Value * instance = kernels[k]->getInstance();
303        std::vector<Value *> doSegmentArgs = {instance, terminationFound};
304        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
305            unsigned producerKernel, outputIndex;
306            std::tie(producerKernel, outputIndex) = producerTable[k][j];
307            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
308        }
309        kernels[k]->createDoSegmentCall(doSegmentArgs);
310        if (! (kernels[k]->hasNoTerminateAttribute())) {
311            Value * terminated = kernels[k]->getTerminationSignal(instance);
312            terminationFound = iBuilder->CreateOr(terminationFound, terminated);
313        }
314        std::vector<Value *> produced;
315        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
316            produced.push_back(kernels[k]->getProducedItemCount(instance, kernels[k]->getStreamOutputs()[i].name));
317        }
318        ProducerPos.push_back(produced);
319        Value * segNo = kernels[k]->acquireLogicalSegmentNo(instance);
320        kernels[k]->releaseLogicalSegmentNo(instance, iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
321    }
322    iBuilder->CreateCondBr(terminationFound, exitBlock, segmentLoop);
323    iBuilder->SetInsertPoint(exitBlock);
324}
325
326   
Note: See TracBrowser for help on using the repository browser.