source: icGREP/icgrep-devel/icgrep/toolchain/pipeline.cpp @ 5615

Last change on this file since 5615 was 5615, checked in by cameron, 21 months ago

Automatic expansion of dynamic buffers in pipeline

File size: 29.2 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/toolchain.h>
8#include <kernels/kernel.h>
9#include <kernels/streamset.h>
10#include <llvm/IR/Module.h>
11#include <boost/container/flat_set.hpp>
12#include <boost/container/flat_map.hpp>
13#include <llvm/Support/CommandLine.h>
14#include <kernels/kernel_builder.h>
15
16#include <llvm/Support/raw_ostream.h>
17
18using namespace kernel;
19using namespace parabix;
20using namespace llvm;
21
22// static cl::opt<bool> UseYield("yield", cl::desc("yield after waiting"), cl::init(false));
23
24template <typename Value>
25using StreamSetBufferMap = boost::container::flat_map<const StreamSetBuffer *, Value>;
26
27template <typename Value>
28using FlatSet = boost::container::flat_set<Value>;
29
30Function * makeThreadFunction(const std::unique_ptr<kernel::KernelBuilder> & b, const std::string & name) {
31    Function * const f = Function::Create(FunctionType::get(b->getVoidTy(), {b->getVoidPtrTy()}, false), Function::InternalLinkage, name, b->getModule());
32    f->setCallingConv(CallingConv::C);
33    f->arg_begin()->setName("input");
34    return f;
35}
36
37/** ------------------------------------------------------------------------------------------------------------- *
38 * @brief generateSegmentParallelPipeline
39 *
40 * Given a computation expressed as a logical pipeline of K kernels k0, k_1, ...k_(K-1)
41 * operating over an input stream set S, a segment-parallel implementation divides the input
42 * into segments and coordinates a set of T <= K threads to each process one segment at a time.
43 * Let S_0, S_1, ... S_N be the segments of S.   Segments are assigned to threads in a round-robin
44 * fashion such that processing of segment S_i by the full pipeline is carried out by thread i mod T.
45 ** ------------------------------------------------------------------------------------------------------------- */
46void generateSegmentParallelPipeline(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> & kernels) {
47
48    const unsigned n = kernels.size();
49    Module * const m = iBuilder->getModule();
50    IntegerType * const sizeTy = iBuilder->getSizeTy();
51    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
52    Constant * nullVoidPtrVal = ConstantPointerNull::getNullValue(voidPtrTy);
53    std::vector<Type *> structTypes;
54
55    codegen::BufferSegments = std::max(codegen::BufferSegments, codegen::ThreadNum);
56
57    Value * instance[n];
58    for (unsigned i = 0; i < n; ++i) {
59        instance[i] = kernels[i]->getInstance();
60        structTypes.push_back(instance[i]->getType());
61    }
62    StructType * const sharedStructType = StructType::get(m->getContext(), structTypes);
63    StructType * const threadStructType = StructType::get(sharedStructType->getPointerTo(), sizeTy, nullptr);
64
65    Function * const threadFunc = makeThreadFunction(iBuilder, "segment");
66
67    // -------------------------------------------------------------------------------------------------------------------------
68    // MAKE SEGMENT PARALLEL PIPELINE THREAD
69    // -------------------------------------------------------------------------------------------------------------------------
70    const auto ip = iBuilder->saveIP();
71
72     // Create the basic blocks for the thread function.
73    BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc);
74    iBuilder->SetInsertPoint(entryBlock);
75    Value * const input = &threadFunc->getArgumentList().front();
76    Value * const threadStruct = iBuilder->CreatePointerCast(input, threadStructType->getPointerTo());
77    Value * const sharedStatePtr = iBuilder->CreateLoad(iBuilder->CreateGEP(threadStruct, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
78    for (unsigned k = 0; k < n; ++k) {
79        Value * ptr = iBuilder->CreateLoad(iBuilder->CreateGEP(sharedStatePtr, {iBuilder->getInt32(0), iBuilder->getInt32(k)}));
80        kernels[k]->setInstance(ptr);
81    }
82    Value * const segOffset = iBuilder->CreateLoad(iBuilder->CreateGEP(threadStruct, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
83
84    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", threadFunc);
85    iBuilder->CreateBr(segmentLoop);
86
87    iBuilder->SetInsertPoint(segmentLoop);
88    PHINode * const segNo = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "segNo");
89    segNo->addIncoming(segOffset, entryBlock);
90
91    Value * terminated = iBuilder->getFalse();
92    Value * const nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
93
94    BasicBlock * segmentLoopBody = nullptr;
95    BasicBlock * const exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc);
96
97    StreamSetBufferMap<Value *> producedPos;
98    StreamSetBufferMap<Value *> consumedPos;
99
100    Value * cycleCountStart = nullptr;
101    Value * cycleCountEnd = nullptr;
102    if (codegen::EnableCycleCounter) {
103        cycleCountStart = iBuilder->CreateReadCycleCounter();
104    }
105
106    for (unsigned k = 0; k < n; ++k) {
107
108        const auto & kernel = kernels[k];
109
110        BasicBlock * const segmentWait = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Wait", threadFunc);
111
112        BasicBlock * segmentYield = segmentWait;
113//        if (UseYield) {
114//            segmentYield = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Yield", threadFunc);
115//        }
116
117        iBuilder->CreateBr(segmentWait);
118
119        segmentLoopBody = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Do", threadFunc);
120
121        iBuilder->SetInsertPoint(segmentWait);
122        const unsigned waitIdx = codegen::DebugOptionIsSet(codegen::SerializeThreads) ? (n - 1) : k;
123
124        iBuilder->setKernel(kernels[waitIdx]);
125        Value * const processedSegmentCount = iBuilder->acquireLogicalSegmentNo();
126        iBuilder->setKernel(kernel);
127
128        assert (processedSegmentCount->getType() == segNo->getType());
129        Value * const ready = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
130
131        if (kernel->hasNoTerminateAttribute()) {
132            iBuilder->CreateCondBr(ready, segmentLoopBody, segmentYield);
133        } else { // If the kernel was terminated in a previous segment then the pipeline is done.
134            BasicBlock * completionTest = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Completed", threadFunc, 0);
135            BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Exit", threadFunc, 0);
136            iBuilder->CreateCondBr(ready, completionTest, segmentYield);
137
138            iBuilder->SetInsertPoint(completionTest);
139            Value * terminationSignal = iBuilder->getTerminationSignal();
140            iBuilder->CreateCondBr(terminationSignal, exitBlock, segmentLoopBody);
141            iBuilder->SetInsertPoint(exitBlock);
142            // Ensure that the next thread will also exit.
143            iBuilder->releaseLogicalSegmentNo(nextSegNo);
144            iBuilder->CreateBr(exitThreadBlock);
145        }
146
147//        if (UseYield) {
148//            // Yield the thread after waiting
149//            iBuilder->SetInsertPoint(segmentYield);
150//            iBuilder->CreatePThreadYield();
151//            iBuilder->CreateBr(segmentWait);
152//        }
153
154        // Execute the kernel segment
155        iBuilder->SetInsertPoint(segmentLoopBody);
156        const auto & inputs = kernel->getStreamInputs();
157        std::vector<Value *> args = {kernel->getInstance(), terminated};
158        for (unsigned i = 0; i < inputs.size(); ++i) {
159            const auto f = producedPos.find(kernel->getStreamSetInputBuffer(i));
160            assert (f != producedPos.end());
161            args.push_back(f->second);
162        }
163
164        iBuilder->setKernel(kernel);
165        iBuilder->createDoSegmentCall(args);
166        if (!kernel->hasNoTerminateAttribute()) {
167            terminated = iBuilder->CreateOr(terminated, iBuilder->getTerminationSignal());
168        }
169
170        const auto & outputs = kernel->getStreamOutputs();
171        for (unsigned i = 0; i < outputs.size(); ++i) {           
172            Value * const produced = iBuilder->getProducedItemCount(outputs[i].name, terminated);
173            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(i);
174            assert (producedPos.count(buf) == 0);
175            producedPos.emplace(buf, produced);
176        }
177        for (unsigned i = 0; i < inputs.size(); ++i) {
178            Value * const processedItemCount = iBuilder->getProcessedItemCount(inputs[i].name);
179            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(i);           
180            auto f = consumedPos.find(buf);
181            if (f == consumedPos.end()) {
182                consumedPos.emplace(buf, processedItemCount);
183            } else {
184                Value * lesser = iBuilder->CreateICmpULT(processedItemCount, f->second);
185                f->second = iBuilder->CreateSelect(lesser, processedItemCount, f->second);
186            }
187        }
188        if (codegen::EnableCycleCounter) {
189            cycleCountEnd = iBuilder->CreateReadCycleCounter();
190            Value * counterPtr = iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR);
191            iBuilder->CreateStore(iBuilder->CreateAdd(iBuilder->CreateLoad(counterPtr), iBuilder->CreateSub(cycleCountEnd, cycleCountStart)), counterPtr);
192            cycleCountStart = cycleCountEnd;
193        }
194       
195        iBuilder->releaseLogicalSegmentNo(nextSegNo);
196    }
197
198    assert (segmentLoopBody);
199    exitThreadBlock->moveAfter(segmentLoopBody);
200
201    for (const auto consumed : consumedPos) {
202        const StreamSetBuffer * const buf = consumed.first;
203        Kernel * kernel = buf->getProducer();
204        const auto & outputs = kernel->getStreamSetOutputBuffers();
205        for (unsigned i = 0; i < outputs.size(); ++i) {
206            if (outputs[i] == buf) {
207                iBuilder->setKernel(kernel);
208                iBuilder->setConsumedItemCount(kernel->getStreamOutput(i).name, consumed.second);
209                break;
210            }
211        }
212    }
213
214    segNo->addIncoming(iBuilder->CreateAdd(segNo, iBuilder->getSize(codegen::ThreadNum)), segmentLoopBody);
215    iBuilder->CreateCondBr(terminated, exitThreadBlock, segmentLoop);
216
217    iBuilder->SetInsertPoint(exitThreadBlock);
218
219    // only call pthread_exit() within spawned threads; otherwise it'll be equivalent to calling exit() within the process
220    BasicBlock * const exitThread = BasicBlock::Create(iBuilder->getContext(), "ExitThread", threadFunc);
221    BasicBlock * const exitFunction = BasicBlock::Create(iBuilder->getContext(), "ExitProcessFunction", threadFunc);
222
223    Value * const exitCond = iBuilder->CreateICmpEQ(segOffset, ConstantInt::getNullValue(segOffset->getType()));
224    iBuilder->CreateCondBr(exitCond, exitFunction, exitThread);
225    iBuilder->SetInsertPoint(exitThread);
226    iBuilder->CreatePThreadExitCall(nullVoidPtrVal);
227    iBuilder->CreateBr(exitFunction);
228    iBuilder->SetInsertPoint(exitFunction);
229    iBuilder->CreateRetVoid();
230
231    // -------------------------------------------------------------------------------------------------------------------------
232    iBuilder->restoreIP(ip);
233
234    for (unsigned i = 0; i < n; ++i) {
235        kernels[i]->setInstance(instance[i]);
236    }
237
238    // -------------------------------------------------------------------------------------------------------------------------
239    // MAKE SEGMENT PARALLEL PIPELINE DRIVER
240    // -------------------------------------------------------------------------------------------------------------------------
241    const unsigned threads = codegen::ThreadNum - 1;
242    assert (codegen::ThreadNum > 1);
243    Type * const pthreadsTy = ArrayType::get(sizeTy, threads);
244    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
245    Value * threadIdPtr[threads];
246
247    for (unsigned i = 0; i < threads; ++i) {
248        threadIdPtr[i] = iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
249    }
250
251    for (unsigned i = 0; i < n; ++i) {
252        iBuilder->setKernel(kernels[i]);
253        iBuilder->releaseLogicalSegmentNo(iBuilder->getSize(0));
254    }
255
256    AllocaInst * const sharedStruct = iBuilder->CreateCacheAlignedAlloca(sharedStructType);
257    for (unsigned i = 0; i < n; ++i) {
258        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
259        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
260    }
261
262    // use the process thread to handle the initial segment function after spawning (n - 1) threads to handle the subsequent offsets
263    for (unsigned i = 0; i < threads; ++i) {
264        AllocaInst * const threadState = iBuilder->CreateAlloca(threadStructType);
265        iBuilder->CreateStore(sharedStruct, iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
266        iBuilder->CreateStore(iBuilder->getSize(i + 1), iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
267        iBuilder->CreatePThreadCreateCall(threadIdPtr[i], nullVoidPtrVal, threadFunc, threadState);
268    }
269
270    AllocaInst * const threadState = iBuilder->CreateAlloca(threadStructType);
271    iBuilder->CreateStore(sharedStruct, iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
272    iBuilder->CreateStore(iBuilder->getSize(0), iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
273    iBuilder->CreateCall(threadFunc, iBuilder->CreatePointerCast(threadState, voidPtrTy));
274
275    AllocaInst * const status = iBuilder->CreateAlloca(voidPtrTy);
276    for (unsigned i = 0; i < threads; ++i) {
277        Value * threadId = iBuilder->CreateLoad(threadIdPtr[i]);
278        iBuilder->CreatePThreadJoinCall(threadId, status);
279    }
280   
281    if (codegen::EnableCycleCounter) {
282        for (unsigned k = 0; k < kernels.size(); k++) {
283            auto & kernel = kernels[k];
284            iBuilder->setKernel(kernel);
285            const auto & inputs = kernel->getStreamInputs();
286            const auto & outputs = kernel->getStreamOutputs();
287            Value * items = nullptr;
288            if (inputs.empty()) {
289                items = iBuilder->getProducedItemCount(outputs[0].name);
290            } else {
291                items = iBuilder->getProcessedItemCount(inputs[0].name);
292            }
293            Value * fItems = iBuilder->CreateUIToFP(items, iBuilder->getDoubleTy());
294            Value * cycles = iBuilder->CreateLoad(iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR));
295            Value * fCycles = iBuilder->CreateUIToFP(cycles, iBuilder->getDoubleTy());
296            std::string formatString = kernel->getName() + ": %7.2e items processed; %7.2e CPU cycles,  %6.2f cycles per item.\n";
297            Value * stringPtr = iBuilder->CreatePointerCast(iBuilder->GetString(formatString), iBuilder->getInt8PtrTy());
298            iBuilder->CreateCall(iBuilder->GetDprintf(), {iBuilder->getInt32(2), stringPtr, fItems, fCycles, iBuilder->CreateFDiv(fCycles, fItems)});
299        }
300    }
301   
302}
303
304
305/** ------------------------------------------------------------------------------------------------------------- *
306 * @brief generateParallelPipeline
307 ** ------------------------------------------------------------------------------------------------------------- */
308void generateParallelPipeline(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> &kernels) {
309
310    Module * const m = iBuilder->getModule();
311    IntegerType * const sizeTy = iBuilder->getSizeTy();
312    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
313    ConstantInt * bufferSegments = ConstantInt::get(sizeTy, codegen::BufferSegments - 1);
314    ConstantInt * segmentItems = ConstantInt::get(sizeTy, codegen::SegmentSize * iBuilder->getBitBlockWidth());
315    Constant * const nullVoidPtrVal = ConstantPointerNull::getNullValue(voidPtrTy);
316
317    const unsigned n = kernels.size();
318
319    Type * const pthreadsTy = ArrayType::get(sizeTy, n);
320    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
321    Value * threadIdPtr[n];
322    for (unsigned i = 0; i < n; ++i) {
323        threadIdPtr[i] = iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
324    }
325
326    Value * instance[n];
327    Type * structTypes[n];
328    for (unsigned i = 0; i < n; ++i) {
329        instance[i] = kernels[i]->getInstance();
330        structTypes[i] = instance[i]->getType();
331    }
332
333    Type * const sharedStructType = StructType::get(m->getContext(), ArrayRef<Type *>{structTypes, n});
334
335
336    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
337    for (unsigned i = 0; i < n; ++i) {
338        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
339        iBuilder->CreateStore(instance[i], ptr);
340    }
341
342    for (auto & kernel : kernels) {
343        iBuilder->setKernel(kernel);
344        iBuilder->releaseLogicalSegmentNo(iBuilder->getSize(0));
345    }
346
347    // GENERATE THE PRODUCING AND CONSUMING KERNEL MAPS
348    StreamSetBufferMap<unsigned> producingKernel;
349    StreamSetBufferMap<std::vector<unsigned>> consumingKernels;
350    for (unsigned id = 0; id < n; ++id) {
351        const auto & kernel = kernels[id];
352        const auto & inputs = kernel->getStreamInputs();
353        const auto & outputs = kernel->getStreamOutputs();
354        // add any outputs from this kernel to the producing kernel map
355        for (unsigned j = 0; j < outputs.size(); ++j) {
356            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(j);
357            if (LLVM_UNLIKELY(producingKernel.count(buf) != 0)) {
358                report_fatal_error(kernel->getName() + " redefines stream set " + outputs[j].name);
359            }
360            producingKernel.emplace(buf, id);
361        }
362        // and any inputs to the consuming kernels list
363        for (unsigned j = 0; j < inputs.size(); ++j) {
364            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(j);
365            auto f = consumingKernels.find(buf);
366            if (f == consumingKernels.end()) {
367                if (LLVM_UNLIKELY(producingKernel.count(buf) == 0)) {
368                    report_fatal_error(kernel->getName() + " uses stream set " + inputs[j].name + " prior to its definition");
369                }
370                consumingKernels.emplace(buf, std::vector<unsigned>{ id });
371            } else {
372                f->second.push_back(id);
373            }
374        }
375    }
376
377    const auto ip = iBuilder->saveIP();
378
379    // GENERATE UNIQUE PIPELINE PARALLEL THREAD FUNCTION FOR EACH KERNEL
380    FlatSet<unsigned> kernelSet;
381    kernelSet.reserve(n);
382
383    Function * thread_functions[n];
384    Value * producerSegNo[n];
385    for (unsigned id = 0; id < n; id++) {
386        const auto & kernel = kernels[id];
387
388        iBuilder->setKernel(kernel);
389
390        const auto & inputs = kernel->getStreamInputs();
391
392        Function * const threadFunc = makeThreadFunction(iBuilder, "ppt:" + kernel->getName());
393
394         // Create the basic blocks for the thread function.
395        BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc);
396        BasicBlock * outputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "outputCheck", threadFunc);
397        BasicBlock * inputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "inputCheck", threadFunc);
398        BasicBlock * doSegmentBlock = BasicBlock::Create(iBuilder->getContext(), "doSegment", threadFunc);
399        BasicBlock * exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc);
400
401        iBuilder->SetInsertPoint(entryBlock);
402
403        Value * sharedStruct = iBuilder->CreateBitCast(&threadFunc->getArgumentList().front(), sharedStructType->getPointerTo());
404
405        for (unsigned k = 0; k < n; k++) {
406            Value * const ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(k)});
407            kernels[k]->setInstance(iBuilder->CreateLoad(ptr));
408        }
409
410        iBuilder->CreateBr(outputCheckBlock);
411
412        // Check whether the output buffers are ready for more data
413        iBuilder->SetInsertPoint(outputCheckBlock);
414        PHINode * segNo = iBuilder->CreatePHI(iBuilder->getSizeTy(), 3, "segNo");
415        segNo->addIncoming(iBuilder->getSize(0), entryBlock);
416        segNo->addIncoming(segNo, outputCheckBlock);
417
418        Value * outputWaitCond = iBuilder->getTrue();
419        for (const StreamSetBuffer * buf : kernel->getStreamSetOutputBuffers()) {
420            const auto & list = consumingKernels[buf];
421            assert(std::is_sorted(list.begin(), list.end()));
422            kernelSet.insert(list.begin(), list.end());
423        }
424        for (unsigned k : kernelSet) {
425            iBuilder->setKernel(kernels[k]);
426            Value * consumerSegNo = iBuilder->acquireLogicalSegmentNo();
427            assert (consumerSegNo->getType() == segNo->getType());
428            Value * consumedSegNo = iBuilder->CreateAdd(consumerSegNo, bufferSegments);
429            outputWaitCond = iBuilder->CreateAnd(outputWaitCond, iBuilder->CreateICmpULE(segNo, consumedSegNo));
430        }
431        kernelSet.clear();
432        iBuilder->setKernel(kernel);
433        iBuilder->CreateCondBr(outputWaitCond, inputCheckBlock, outputCheckBlock);
434
435        // Check whether the input buffers have enough data for this kernel to begin
436        iBuilder->SetInsertPoint(inputCheckBlock);
437        for (const StreamSetBuffer * buf : kernel->getStreamSetInputBuffers()) {
438            kernelSet.insert(producingKernel[buf]);
439        }
440
441        Value * inputWaitCond = iBuilder->getTrue();
442        for (unsigned k : kernelSet) {
443            iBuilder->setKernel(kernels[k]);
444            producerSegNo[k] = iBuilder->acquireLogicalSegmentNo();
445            assert (producerSegNo[k]->getType() == segNo->getType());
446            inputWaitCond = iBuilder->CreateAnd(inputWaitCond, iBuilder->CreateICmpULT(segNo, producerSegNo[k]));
447        }
448        iBuilder->setKernel(kernel);
449        iBuilder->CreateCondBr(inputWaitCond, doSegmentBlock, inputCheckBlock);
450
451        // Process the segment
452        iBuilder->SetInsertPoint(doSegmentBlock);
453
454        Value * const nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
455        Value * terminated = nullptr;
456        if (kernelSet.empty()) {
457            // if this kernel has no input streams, the kernel itself must decide when it terminates.
458            terminated = iBuilder->getTerminationSignal();
459        } else {
460            // ... otherwise the kernel terminates only when it exhausts all of its input streams
461            terminated = iBuilder->getTrue();
462            for (unsigned k : kernelSet) {
463                iBuilder->setKernel(kernels[k]);
464                terminated = iBuilder->CreateAnd(terminated, iBuilder->getTerminationSignal());
465                terminated = iBuilder->CreateAnd(terminated, iBuilder->CreateICmpEQ(nextSegNo, producerSegNo[k]));
466            }
467            kernelSet.clear();
468            iBuilder->setKernel(kernel);
469        }
470
471        std::vector<Value *> args = {kernel->getInstance(), terminated};
472        args.insert(args.end(), inputs.size(), iBuilder->CreateMul(segmentItems, segNo));
473
474        iBuilder->createDoSegmentCall(args);
475        segNo->addIncoming(nextSegNo, doSegmentBlock);
476        iBuilder->releaseLogicalSegmentNo(nextSegNo);
477
478        iBuilder->CreateCondBr(terminated, exitThreadBlock, outputCheckBlock);
479
480        iBuilder->SetInsertPoint(exitThreadBlock);
481
482        iBuilder->CreatePThreadExitCall(nullVoidPtrVal);
483
484        iBuilder->CreateRetVoid();
485
486        thread_functions[id] = threadFunc;
487    }
488
489    iBuilder->restoreIP(ip);
490
491    for (unsigned i = 0; i < n; ++i) {
492        kernels[i]->setInstance(instance[i]);
493    }
494
495    for (unsigned i = 0; i < n; ++i) {
496        iBuilder->CreatePThreadCreateCall(threadIdPtr[i], nullVoidPtrVal, thread_functions[i], sharedStruct);
497    }
498
499    AllocaInst * const status = iBuilder->CreateAlloca(voidPtrTy);
500    for (unsigned i = 0; i < n; ++i) {
501        Value * threadId = iBuilder->CreateLoad(threadIdPtr[i]);
502        iBuilder->CreatePThreadJoinCall(threadId, status);
503    }
504}
505
506/** ------------------------------------------------------------------------------------------------------------- *
507 * @brief generatePipelineLoop
508 ** ------------------------------------------------------------------------------------------------------------- */
509void generatePipelineLoop(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> & kernels) {
510
511    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
512    Function * main = entryBlock->getParent();
513
514    // Create the basic blocks for the loop.
515    BasicBlock * pipelineLoop = BasicBlock::Create(iBuilder->getContext(), "pipelineLoop", main);
516    BasicBlock * pipelineExit = BasicBlock::Create(iBuilder->getContext(), "pipelineExit", main);
517
518    StreamSetBufferMap<Value *> producedPos;
519    StreamSetBufferMap<Value *> consumedPos;
520
521    iBuilder->CreateBr(pipelineLoop);
522    iBuilder->SetInsertPoint(pipelineLoop);
523   
524    Value * cycleCountStart = nullptr;
525    Value * cycleCountEnd = nullptr;
526    if (codegen::EnableCycleCounter) {
527        cycleCountStart = iBuilder->CreateReadCycleCounter();
528    }
529    Value * terminated = iBuilder->getFalse();
530    for (unsigned k = 0; k < kernels.size(); k++) {
531
532        auto & kernel = kernels[k];
533
534        iBuilder->setKernel(kernel);
535        const auto & inputs = kernel->getStreamInputs();
536        const auto & outputs = kernel->getStreamOutputs();
537
538        std::vector<Value *> inputAvail;
539        std::vector<Value *> args = {kernel->getInstance(), terminated};
540       
541        for (unsigned i = 0; i < inputs.size(); ++i) {
542            const auto f = producedPos.find(kernel->getStreamSetInputBuffer(i));
543            if (LLVM_UNLIKELY(f == producedPos.end())) {
544                report_fatal_error(kernel->getName() + " uses stream set " + inputs[i].name + " prior to its definition");
545            }
546            inputAvail.push_back(f->second);
547            args.push_back(f->second);
548        }
549        applyOutputBufferExpansions(iBuilder, inputAvail, terminated);
550
551        iBuilder->createDoSegmentCall(args);
552        if (!kernel->hasNoTerminateAttribute()) {
553            Value * terminatedSignal = iBuilder->getTerminationSignal();
554            terminated = iBuilder->CreateOr(terminated, terminatedSignal);
555        }
556        for (unsigned i = 0; i < outputs.size(); ++i) {
557            Value * const produced = iBuilder->getProducedItemCount(outputs[i].name, terminated);
558            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(i);
559            assert (producedPos.count(buf) == 0);
560            producedPos.emplace(buf, produced);
561        }
562
563        for (unsigned i = 0; i < inputs.size(); ++i) {
564            Value * const processedItemCount = iBuilder->getProcessedItemCount(inputs[i].name);
565            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(i);
566            auto f = consumedPos.find(buf);
567            if (f == consumedPos.end()) {
568                consumedPos.emplace(buf, processedItemCount);
569            } else {
570                Value * lesser = iBuilder->CreateICmpULT(processedItemCount, f->second);
571                f->second = iBuilder->CreateSelect(lesser, processedItemCount, f->second);
572            }
573        }
574        if (codegen::EnableCycleCounter) {
575            cycleCountEnd = iBuilder->CreateReadCycleCounter();
576            //Value * counterPtr = iBuilder->CreateGEP(mCycleCounts, {iBuilder->getInt32(0), iBuilder->getInt32(k)});
577            Value * counterPtr = iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR);
578            iBuilder->CreateStore(iBuilder->CreateAdd(iBuilder->CreateLoad(counterPtr), iBuilder->CreateSub(cycleCountEnd, cycleCountStart)), counterPtr);
579            cycleCountStart = cycleCountEnd;
580        }
581
582        Value * const segNo = iBuilder->acquireLogicalSegmentNo();
583        Value * nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
584        iBuilder->releaseLogicalSegmentNo(nextSegNo);
585    }
586
587    for (const auto consumed : consumedPos) {
588        const StreamSetBuffer * const buf = consumed.first;
589        Kernel * k = buf->getProducer();
590        const auto & outputs = k->getStreamSetOutputBuffers();
591        for (unsigned i = 0; i < outputs.size(); ++i) {
592            if (outputs[i] == buf) {
593                iBuilder->setKernel(k);
594                iBuilder->setConsumedItemCount(k->getStreamOutput(i).name, consumed.second);
595                break;
596            }
597        }
598    }
599
600    iBuilder->CreateCondBr(terminated, pipelineExit, pipelineLoop);
601    iBuilder->SetInsertPoint(pipelineExit);
602    if (codegen::EnableCycleCounter) {
603        for (unsigned k = 0; k < kernels.size(); k++) {
604            auto & kernel = kernels[k];
605            iBuilder->setKernel(kernel);
606            const auto & inputs = kernel->getStreamInputs();
607            const auto & outputs = kernel->getStreamOutputs();
608            Value * items = nullptr;
609            if (inputs.empty()) {
610                items = iBuilder->getProducedItemCount(outputs[0].name);
611            } else {
612                items = iBuilder->getProcessedItemCount(inputs[0].name);
613            }
614            Value * fItems = iBuilder->CreateUIToFP(items, iBuilder->getDoubleTy());
615            Value * cycles = iBuilder->CreateLoad(iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR));
616            Value * fCycles = iBuilder->CreateUIToFP(cycles, iBuilder->getDoubleTy());
617            std::string formatString = kernel->getName() + ": %7.2e items processed; %7.2e CPU cycles,  %6.2f cycles per item.\n";
618            Value * stringPtr = iBuilder->CreatePointerCast(iBuilder->GetString(formatString), iBuilder->getInt8PtrTy());
619            iBuilder->CreateCall(iBuilder->GetDprintf(), {iBuilder->getInt32(2), stringPtr, fItems, fCycles, iBuilder->CreateFDiv(fCycles, fItems)});
620        }
621    }
622}
Note: See TracBrowser for help on using the repository browser.