source: icGREP/icgrep-devel/icgrep/kernels/kernel.cpp @ 5448

Last change on this file since 5448 was 5448, checked in by cameron, 23 months ago

Hack for source/external buffers with mBufferBlocks=1; u8u16 test with segment-pipeline-parallel; simplified copying

File size: 50.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 "kernel.h"
7#include <toolchain/toolchain.h>
8#include <kernels/streamset.h>
9#include <llvm/IR/Constants.h>
10#include <llvm/IR/Function.h>
11#include <llvm/IR/Instructions.h>
12#include <llvm/IR/MDBuilder.h>
13#include <llvm/IR/Module.h>
14#include <llvm/Support/raw_ostream.h>
15#include <llvm/Bitcode/ReaderWriter.h>
16#include <llvm/Transforms/Utils/Local.h>
17#include <kernels/streamset.h>
18#include <sstream>
19#include <kernels/kernel_builder.h>
20
21using namespace llvm;
22using namespace parabix;
23
24namespace kernel {
25
26const std::string Kernel::DO_BLOCK_SUFFIX = "_DoBlock";
27const std::string Kernel::FINAL_BLOCK_SUFFIX = "_FinalBlock";
28const std::string Kernel::MULTI_BLOCK_SUFFIX = "_MultiBlock";
29const std::string Kernel::LOGICAL_SEGMENT_NO_SCALAR = "logicalSegNo";
30const std::string Kernel::PROCESSED_ITEM_COUNT_SUFFIX = "_processedItemCount";
31const std::string Kernel::CONSUMED_ITEM_COUNT_SUFFIX = "_consumedItemCount";
32const std::string Kernel::PRODUCED_ITEM_COUNT_SUFFIX = "_producedItemCount";
33const std::string Kernel::TERMINATION_SIGNAL = "terminationSignal";
34const std::string Kernel::BUFFER_PTR_SUFFIX = "_bufferPtr";
35const std::string Kernel::CONSUMER_SUFFIX = "_consumerLocks";
36
37unsigned Kernel::addScalar(Type * const type, const std::string & name) {
38    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
39        report_fatal_error("Cannot add field " + name + " to " + getName() + " after kernel state finalized");
40    }
41    if (LLVM_UNLIKELY(mKernelMap.count(name))) {
42        report_fatal_error(getName() + " already contains scalar field " + name);
43    }
44    const auto index = mKernelFields.size();
45    mKernelMap.emplace(name, index);
46    mKernelFields.push_back(type);
47    return index;
48}
49
50unsigned Kernel::addUnnamedScalar(Type * const type) {
51    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
52        report_fatal_error("Cannot add unnamed field  to " + getName() + " after kernel state finalized");
53    }
54    const auto index = mKernelFields.size();
55    mKernelFields.push_back(type);
56    return index;
57}
58
59void Kernel::prepareStreamSetNameMap() {
60    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
61        mStreamMap.emplace(mStreamSetInputs[i].name, std::make_pair(Port::Input, i));
62    }
63    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
64        mStreamMap.emplace(mStreamSetOutputs[i].name, std::make_pair(Port::Output, i));
65    }
66}
67
68void Kernel::bindPorts(const StreamSetBuffers & inputs, const StreamSetBuffers & outputs) {
69    assert (mModule == nullptr);
70    assert (mStreamSetInputBuffers.empty());
71    assert (mStreamSetOutputBuffers.empty());
72
73    if (LLVM_UNLIKELY(mStreamSetInputs.size() != inputs.size())) {
74        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetInputs.size()) +
75                           " input stream sets but was given "
76                           + std::to_string(inputs.size()));
77    }
78
79    for (unsigned i = 0; i < inputs.size(); ++i) {
80        StreamSetBuffer * const buf = inputs[i];
81        if (LLVM_UNLIKELY(buf == nullptr)) {
82            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
83                               + " cannot be null");
84        }
85        buf->addConsumer(this);
86    }
87
88    if (LLVM_UNLIKELY(mStreamSetOutputs.size() != outputs.size())) {
89        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetOutputs.size())
90                           + " output stream sets but was given "
91                           + std::to_string(outputs.size()));
92    }
93
94    for (unsigned i = 0; i < outputs.size(); ++i) {
95        StreamSetBuffer * const buf = outputs[i];
96        if (LLVM_UNLIKELY(buf == nullptr)) {
97            report_fatal_error(getName() + ": output stream set " + std::to_string(i) + " cannot be null");
98        }
99        if (LLVM_LIKELY(buf->getProducer() == nullptr)) {
100            buf->setProducer(this);
101        } else {
102            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
103                               + " is already produced by kernel " + buf->getProducer()->getName());
104        }
105    }
106
107    mStreamSetInputBuffers.assign(inputs.begin(), inputs.end());
108    mStreamSetOutputBuffers.assign(outputs.begin(), outputs.end());
109}
110
111Module * Kernel::makeModule(const std::unique_ptr<KernelBuilder> & idb) {
112    assert (mModule == nullptr);
113    std::stringstream cacheName;   
114    cacheName << getName() << '_' << idb->getBuilderUniqueName();
115    for (const StreamSetBuffer * b: mStreamSetInputBuffers) {
116        cacheName <<  ':' <<  b->getUniqueID();
117    }
118    for (const StreamSetBuffer * b: mStreamSetOutputBuffers) {
119        cacheName <<  ':' <<  b->getUniqueID();
120    }
121    mModule = new Module(cacheName.str(), idb->getContext());
122    prepareKernel(idb);
123    return mModule;
124}
125
126Module * Kernel::setModule(const std::unique_ptr<KernelBuilder> & idb, llvm::Module * const module) {
127    assert (mModule == nullptr);
128    mModule = module;
129    prepareKernel(idb);
130    return mModule;
131}
132
133void Kernel::prepareKernel(const std::unique_ptr<KernelBuilder> & idb) {
134    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
135    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
136        report_fatal_error("Cannot prepare kernel after kernel state finalized");
137    }
138    const auto blockSize = idb->getBitBlockWidth();
139    const auto requiredBlocks = codegen::SegmentSize + ((blockSize + mLookAheadPositions - 1) / blockSize);
140
141    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
142        if ((mStreamSetInputBuffers[i]->getBufferBlocks() > 1) && (mStreamSetInputBuffers[i]->getBufferBlocks() < requiredBlocks)) {
143            report_fatal_error(getName() + ": " + mStreamSetInputs[i].name + " requires buffer size " + std::to_string(requiredBlocks));
144        }
145        mScalarInputs.emplace_back(mStreamSetInputBuffers[i]->getPointerType(), mStreamSetInputs[i].name + BUFFER_PTR_SUFFIX);
146        if ((i == 0) || !mStreamSetInputs[i].rate.isExact()) {
147            addScalar(idb->getSizeTy(), mStreamSetInputs[i].name + PROCESSED_ITEM_COUNT_SUFFIX);
148        }
149    }
150
151    IntegerType * const sizeTy = idb->getSizeTy();
152    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
153        mScalarInputs.emplace_back(mStreamSetOutputBuffers[i]->getPointerType(), mStreamSetOutputs[i].name + BUFFER_PTR_SUFFIX);
154        if ((mStreamSetInputs.empty() && (i == 0)) || !mStreamSetOutputs[i].rate.isExact()) {
155            addScalar(sizeTy, mStreamSetOutputs[i].name + PRODUCED_ITEM_COUNT_SUFFIX);
156        }
157    }
158    for (const auto & binding : mScalarInputs) {
159        addScalar(binding.type, binding.name);
160    }
161    for (const auto & binding : mScalarOutputs) {
162        addScalar(binding.type, binding.name);
163    }
164    if (mStreamMap.empty()) {
165        prepareStreamSetNameMap();
166    }
167    for (const auto & binding : mInternalScalars) {
168        addScalar(binding.type, binding.name);
169    }
170
171    Type * const consumerSetTy = StructType::get(sizeTy, sizeTy->getPointerTo()->getPointerTo(), nullptr)->getPointerTo();
172    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
173        addScalar(consumerSetTy, mStreamSetOutputs[i].name + CONSUMER_SUFFIX);
174    }
175
176    addScalar(sizeTy, LOGICAL_SEGMENT_NO_SCALAR);
177    addScalar(idb->getInt1Ty(), TERMINATION_SIGNAL);
178
179    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
180        addScalar(sizeTy, mStreamSetOutputs[i].name + CONSUMED_ITEM_COUNT_SUFFIX);
181    }
182
183    mKernelStateType = StructType::create(idb->getContext(), mKernelFields, getName());
184}
185
186// Default kernel signature: generate the IR and emit as byte code.
187std::string Kernel::makeSignature(const std::unique_ptr<kernel::KernelBuilder> & idb) {
188    assert ("KernelBuilder does not have a valid IDISA Builder" && idb.get());
189    if (LLVM_LIKELY(moduleIDisSignature())) {
190        return getModule()->getModuleIdentifier();
191    } else {
192        generateKernel(idb);
193        std::string signature;
194        raw_string_ostream OS(signature);
195        WriteBitcodeToFile(getModule(), OS);
196        return signature;
197    }
198}
199
200void Kernel::generateKernel(const std::unique_ptr<kernel::KernelBuilder> & idb) {
201    assert ("KernelBuilder does not have a valid IDISA Builder" && idb.get());
202    // If the module id cannot uniquely identify this kernel, "generateKernelSignature()" will have already
203    // generated the unoptimized IR.
204    if (!mIsGenerated) {
205        const auto m = idb->getModule();
206        const auto ip = idb->saveIP();
207        const auto saveInstance = getInstance();
208        idb->setModule(mModule);
209        addKernelDeclarations(idb);
210        callGenerateInitializeMethod(idb);
211        callGenerateDoSegmentMethod(idb);
212        callGenerateFinalizeMethod(idb);
213        setInstance(saveInstance);
214        idb->setModule(m);
215        idb->restoreIP(ip);
216        mIsGenerated = true;
217    }
218}
219
220inline void Kernel::callGenerateInitializeMethod(const std::unique_ptr<kernel::KernelBuilder> & idb) {
221    mCurrentMethod = getInitFunction(idb->getModule());
222    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
223    Function::arg_iterator args = mCurrentMethod->arg_begin();
224    setInstance(&*(args++));
225    idb->CreateStore(ConstantAggregateZero::get(mKernelStateType), getInstance());
226    for (const auto & binding : mScalarInputs) {
227        idb->setScalarField(binding.name, &*(args++));
228    }
229    for (const auto & binding : mStreamSetOutputs) {
230        idb->setConsumerLock(binding.name, &*(args++));
231    }
232    generateInitializeMethod(idb);
233    idb->CreateRetVoid();
234}
235
236inline void Kernel::callGenerateDoSegmentMethod(const std::unique_ptr<kernel::KernelBuilder> & idb) {
237    mCurrentMethod = getDoSegmentFunction(idb->getModule());
238    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
239    auto args = mCurrentMethod->arg_begin();
240    setInstance(&*(args++));
241    mIsFinal = &*(args++);
242    const auto n = mStreamSetInputs.size();
243    mAvailableItemCount.resize(n, nullptr);
244    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
245        mAvailableItemCount[i] = &*(args++);
246    }
247    generateDoSegmentMethod(idb); // must be overridden by the KernelBuilder subtype
248    mIsFinal = nullptr;
249    mAvailableItemCount.clear();
250    idb->CreateRetVoid();
251}
252
253inline void Kernel::callGenerateFinalizeMethod(const std::unique_ptr<KernelBuilder> & idb) {
254    mCurrentMethod = getTerminateFunction(idb->getModule());
255    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
256    auto args = mCurrentMethod->arg_begin();
257    setInstance(&*(args++));
258    generateFinalizeMethod(idb); // may be overridden by the KernelBuilder subtype
259    const auto n = mScalarOutputs.size();
260    if (n == 0) {
261        idb->CreateRetVoid();
262    } else {
263        Value * outputs[n];
264        for (unsigned i = 0; i < n; ++i) {
265            outputs[i] = idb->getScalarField(mScalarOutputs[i].name);
266        }
267        if (n == 1) {
268            idb->CreateRet(outputs[0]);
269        } else {
270            idb->CreateAggregateRet(outputs, n);
271        }
272    }
273}
274
275unsigned Kernel::getScalarIndex(const std::string & name) const {
276    const auto f = mKernelMap.find(name);
277    if (LLVM_UNLIKELY(f == mKernelMap.end())) {
278        report_fatal_error(getName() + " does not contain scalar: " + name);
279    }
280    return f->second;
281}
282
283Value * Kernel::createInstance(const std::unique_ptr<KernelBuilder> & idb) {
284    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
285    if (LLVM_UNLIKELY(mKernelStateType == nullptr)) {
286        report_fatal_error("Cannot instantiate " + getName() + " before calling prepareKernel()");
287    }
288    setInstance(idb->CreateCacheAlignedAlloca(mKernelStateType));
289    return getInstance();
290}
291
292void Kernel::initializeInstance(const std::unique_ptr<KernelBuilder> & idb) {
293    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
294    if (LLVM_UNLIKELY(getInstance() == nullptr)) {
295        report_fatal_error("Cannot initialize " + getName() + " before calling createInstance()");
296    }
297    std::vector<Value *> args;
298    args.reserve(1 + mInitialArguments.size() + mStreamSetInputBuffers.size() + (mStreamSetOutputBuffers.size() * 2));
299    args.push_back(getInstance());
300    for (unsigned i = 0; i < mInitialArguments.size(); ++i) {
301        Value * arg = mInitialArguments[i];
302        if (LLVM_UNLIKELY(arg == nullptr)) {
303            report_fatal_error(getName() + ": initial argument " + std::to_string(i)
304                               + " cannot be null when calling createInstance()");
305        }
306        args.push_back(arg);
307    }
308    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); ++i) {
309        assert (mStreamSetInputBuffers[i]);
310        Value * arg = mStreamSetInputBuffers[i]->getStreamSetBasePtr();
311        if (LLVM_UNLIKELY(arg == nullptr)) {
312            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
313                               + " was not allocated prior to calling createInstance()");
314        }
315        args.push_back(arg);
316    }
317    assert (mStreamSetInputs.size() == mStreamSetInputBuffers.size());
318    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
319        assert (mStreamSetOutputBuffers[i]);
320        Value * arg = mStreamSetOutputBuffers[i]->getStreamSetBasePtr();
321        if (LLVM_UNLIKELY(arg == nullptr)) {
322            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
323                               + " was not allocated prior to calling createInstance()");
324        }
325        args.push_back(arg);
326    }
327    assert (mStreamSetOutputs.size() == mStreamSetOutputBuffers.size());
328    IntegerType * const sizeTy = idb->getSizeTy();
329    PointerType * const sizePtrTy = sizeTy->getPointerTo();
330    PointerType * const sizePtrPtrTy = sizePtrTy->getPointerTo();
331    StructType * const consumerTy = StructType::get(sizeTy, sizePtrPtrTy, nullptr);
332    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
333        const auto output = mStreamSetOutputBuffers[i];
334        const auto & consumers = output->getConsumers();
335        const auto n = consumers.size();
336        AllocaInst * const outputConsumers = idb->CreateAlloca(consumerTy);
337        Value * const consumerSegNoArray = idb->CreateAlloca(ArrayType::get(sizePtrTy, n));
338        for (unsigned i = 0; i < n; ++i) {
339            Kernel * const consumer = consumers[i];
340            assert ("all instances must be created prior to initialization of any instance" && consumer->getInstance());
341            idb->setKernel(consumer);
342            Value * const segmentNoPtr = idb->getScalarFieldPtr(LOGICAL_SEGMENT_NO_SCALAR);
343            idb->CreateStore(segmentNoPtr, idb->CreateGEP(consumerSegNoArray, { idb->getInt32(0), idb->getInt32(i) }));
344        }
345        idb->setKernel(this);
346        Value * const consumerCountPtr = idb->CreateGEP(outputConsumers, {idb->getInt32(0), idb->getInt32(0)});
347        idb->CreateStore(idb->getSize(n), consumerCountPtr);
348        Value * const consumerSegNoArrayPtr = idb->CreateGEP(outputConsumers, {idb->getInt32(0), idb->getInt32(1)});
349        idb->CreateStore(idb->CreatePointerCast(consumerSegNoArray, sizePtrPtrTy), consumerSegNoArrayPtr);
350        args.push_back(outputConsumers);
351    }
352    idb->CreateCall(getInitFunction(idb->getModule()), args);
353}
354
355//  The default doSegment method dispatches to the doBlock routine for
356//  each block of the given number of blocksToDo, and then updates counts.
357
358void BlockOrientedKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & idb) {
359    BasicBlock * const entryBlock = idb->GetInsertBlock();
360    BasicBlock * const strideLoopCond = idb->CreateBasicBlock(getName() + "_strideLoopCond");
361    mStrideLoopBody = idb->CreateBasicBlock(getName() + "_strideLoopBody");
362    BasicBlock * const stridesDone = idb->CreateBasicBlock(getName() + "_stridesDone");
363    BasicBlock * const doFinalBlock = idb->CreateBasicBlock(getName() + "_doFinalBlock");
364    BasicBlock * const segmentDone = idb->CreateBasicBlock(getName() + "_segmentDone");
365
366    Value * baseTarget = nullptr;
367    if (idb->supportsIndirectBr()) {
368        baseTarget = idb->CreateSelect(mIsFinal, BlockAddress::get(doFinalBlock), BlockAddress::get(segmentDone));
369    }
370
371    ConstantInt * stride = idb->getSize(idb->getStride());
372    Value * availablePos = mAvailableItemCount[0];
373    Value * processed = idb->getProcessedItemCount(mStreamSetInputs[0].name);
374    Value * itemsAvail = idb->CreateSub(availablePos, processed);
375    Value * stridesToDo = idb->CreateUDiv(itemsAvail, stride);
376
377    idb->CreateBr(strideLoopCond);
378
379    idb->SetInsertPoint(strideLoopCond);
380
381    PHINode * branchTarget = nullptr;
382    if (idb->supportsIndirectBr()) {
383        branchTarget = idb->CreatePHI(baseTarget->getType(), 2, "branchTarget");
384        branchTarget->addIncoming(baseTarget, entryBlock);
385    }
386
387    PHINode * const stridesRemaining = idb->CreatePHI(idb->getSizeTy(), 2, "stridesRemaining");
388    stridesRemaining->addIncoming(stridesToDo, entryBlock);
389    // NOTE: stridesRemaining may go to a negative number in the final block if the generateFinalBlockMethod(...)
390    // calls CreateDoBlockMethodCall(). Do *not* replace the comparator with an unsigned one!
391    Value * notDone = idb->CreateICmpSGT(stridesRemaining, idb->getSize(0));
392    idb->CreateLikelyCondBr(notDone, mStrideLoopBody, stridesDone);
393
394    idb->SetInsertPoint(mStrideLoopBody);
395
396    if (idb->supportsIndirectBr()) {
397        mStrideLoopTarget = idb->CreatePHI(baseTarget->getType(), 2, "strideTarget");
398        mStrideLoopTarget->addIncoming(branchTarget, strideLoopCond);
399    }
400
401    /// GENERATE DO BLOCK METHOD
402
403    writeDoBlockMethod(idb);
404
405    /// UPDATE PROCESSED COUNTS
406
407    processed = idb->getProcessedItemCount(mStreamSetInputs[0].name);
408    Value * itemsDone = idb->CreateAdd(processed, stride);
409    idb->setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);
410
411    stridesRemaining->addIncoming(idb->CreateSub(stridesRemaining, idb->getSize(1)), idb->GetInsertBlock());
412
413    BasicBlock * bodyEnd = idb->GetInsertBlock();
414    if (idb->supportsIndirectBr()) {
415        branchTarget->addIncoming(mStrideLoopTarget, bodyEnd);
416    }
417    idb->CreateBr(strideLoopCond);
418
419    stridesDone->moveAfter(bodyEnd);
420
421    idb->SetInsertPoint(stridesDone);
422
423    // Now conditionally perform the final block processing depending on the doFinal parameter.
424    if (idb->supportsIndirectBr()) {
425        mStrideLoopBranch = idb->CreateIndirectBr(branchTarget, 3);
426        mStrideLoopBranch->addDestination(doFinalBlock);
427        mStrideLoopBranch->addDestination(segmentDone);
428    } else {
429        idb->CreateUnlikelyCondBr(mIsFinal, doFinalBlock, segmentDone);
430    }
431
432    doFinalBlock->moveAfter(stridesDone);
433
434    idb->SetInsertPoint(doFinalBlock);
435
436    Value * remainingItems = idb->CreateSub(mAvailableItemCount[0], idb->getProcessedItemCount(mStreamSetInputs[0].name));
437
438    writeFinalBlockMethod(idb, remainingItems);
439
440    itemsDone = mAvailableItemCount[0];
441    idb->setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);
442    idb->setTerminationSignal();
443    idb->CreateBr(segmentDone);
444
445    segmentDone->moveAfter(idb->GetInsertBlock());
446
447    idb->SetInsertPoint(segmentDone);
448
449    // Update the branch prediction metadata to indicate that the likely target will be segmentDone
450    if (idb->supportsIndirectBr()) {
451        MDBuilder mdb(idb->getContext());
452        const auto destinations = mStrideLoopBranch->getNumDestinations();
453        uint32_t weights[destinations];
454        for (unsigned i = 0; i < destinations; ++i) {
455            weights[i] = (mStrideLoopBranch->getDestination(i) == segmentDone) ? 100 : 1;
456        }
457        ArrayRef<uint32_t> bw(weights, destinations);
458        mStrideLoopBranch->setMetadata(LLVMContext::MD_prof, mdb.createBranchWeights(bw));
459    }
460
461}
462
463inline void BlockOrientedKernel::writeDoBlockMethod(const std::unique_ptr<KernelBuilder> & idb) {
464
465    Value * const self = getInstance();
466    Function * const cp = mCurrentMethod;
467    auto ip = idb->saveIP();
468
469    /// Check if the do block method is called and create the function if necessary   
470    if (!idb->supportsIndirectBr()) {
471        FunctionType * const type = FunctionType::get(idb->getVoidTy(), {self->getType()}, false);
472        mCurrentMethod = Function::Create(type, GlobalValue::InternalLinkage, getName() + DO_BLOCK_SUFFIX, idb->getModule());
473        mCurrentMethod->setCallingConv(CallingConv::C);
474        mCurrentMethod->setDoesNotThrow();
475        mCurrentMethod->setDoesNotCapture(1);
476        auto args = mCurrentMethod->arg_begin();
477        args->setName("self");
478        setInstance(&*args);
479        idb->SetInsertPoint(idb->CreateBasicBlock("entry"));
480    }
481
482    std::vector<Value *> priorProduced;
483    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
484        if (isa<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]) || isa<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
485            priorProduced.push_back(idb->getProducedItemCount(mStreamSetOutputs[i].name));
486        }
487    }
488
489    generateDoBlockMethod(idb); // must be implemented by the BlockOrientedKernelBuilder subtype
490
491    unsigned priorIdx = 0;
492    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
493        Value * log2BlockSize = idb->getSize(std::log2(idb->getBitBlockWidth()));
494        if (SwizzledCopybackBuffer * const cb = dyn_cast<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
495            BasicBlock * copyBack = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
496            BasicBlock * done = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
497            Value * newlyProduced = idb->CreateSub(idb->getProducedItemCount(mStreamSetOutputs[i].name), priorProduced[priorIdx]);
498            Value * priorBlock = idb->CreateLShr(priorProduced[priorIdx], log2BlockSize);
499            Value * priorOffset = idb->CreateAnd(priorProduced[priorIdx], idb->getSize(idb->getBitBlockWidth() - 1));
500            Value * instance = idb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
501            Value * accessibleBlocks = cb->getLinearlyAccessibleBlocks(idb.get(), priorBlock);
502            Value * accessible = idb->CreateSub(idb->CreateShl(accessibleBlocks, log2BlockSize), priorOffset);
503            Value * wraparound = idb->CreateICmpULT(accessible, newlyProduced);
504            idb->CreateCondBr(wraparound, copyBack, done);
505            idb->SetInsertPoint(copyBack);
506            Value * copyItems = idb->CreateSub(newlyProduced, accessible);
507            cb->createCopyBack(idb.get(), instance, copyItems);
508            idb->CreateBr(done);
509            idb->SetInsertPoint(done);
510            priorIdx++;
511        }
512        if (CircularCopybackBuffer * const cb = dyn_cast<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
513            BasicBlock * copyBack = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
514            BasicBlock * done = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
515            Value * instance = idb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
516            Value * newlyProduced = idb->CreateSub(idb->getProducedItemCount(mStreamSetOutputs[i].name), priorProduced[priorIdx]);
517            Value * accessible = cb->getLinearlyAccessibleItems(idb.get(), priorProduced[priorIdx]);
518            Value * wraparound = idb->CreateICmpULT(accessible, newlyProduced);
519            idb->CreateCondBr(wraparound, copyBack, done);
520            idb->SetInsertPoint(copyBack);
521            Value * copyItems = idb->CreateSub(newlyProduced, accessible);
522            cb->createCopyBack(idb.get(), instance, copyItems);
523            idb->CreateBr(done);
524            idb->SetInsertPoint(done);
525            priorIdx++;
526        }
527    }
528
529
530    /// Call the do block method if necessary then restore the current function state to the do segement method
531    if (!idb->supportsIndirectBr()) {
532        idb->CreateRetVoid();
533        mDoBlockMethod = mCurrentMethod;
534        idb->restoreIP(ip);
535        idb->CreateCall(mCurrentMethod, self);
536        setInstance(self);
537        mCurrentMethod = cp;
538    }
539
540}
541
542inline void BlockOrientedKernel::writeFinalBlockMethod(const std::unique_ptr<KernelBuilder> & idb, Value * remainingItems) {
543
544    Value * const self = getInstance();
545    Function * const cp = mCurrentMethod;
546    Value * const remainingItemCount = remainingItems;
547    auto ip = idb->saveIP();
548
549    if (!idb->supportsIndirectBr()) {
550        FunctionType * const type = FunctionType::get(idb->getVoidTy(), {self->getType(), idb->getSizeTy()}, false);
551        mCurrentMethod = Function::Create(type, GlobalValue::InternalLinkage, getName() + FINAL_BLOCK_SUFFIX, idb->getModule());
552        mCurrentMethod->setCallingConv(CallingConv::C);
553        mCurrentMethod->setDoesNotThrow();
554        mCurrentMethod->setDoesNotCapture(1);
555        auto args = mCurrentMethod->arg_begin();
556        args->setName("self");
557        setInstance(&*args);
558        remainingItems = &*(++args);
559        remainingItems->setName("remainingItems");
560        idb->SetInsertPoint(idb->CreateBasicBlock("entry"));
561    }
562
563    generateFinalBlockMethod(idb, remainingItems); // may be implemented by the BlockOrientedKernel subtype
564
565    RecursivelyDeleteTriviallyDeadInstructions(remainingItems); // if remainingItems was not used, this will eliminate it.
566
567    if (!idb->supportsIndirectBr()) {
568        idb->CreateRetVoid();
569        idb->restoreIP(ip);
570        idb->CreateCall(mCurrentMethod, {self, remainingItemCount});
571        mCurrentMethod = cp;
572        setInstance(self);
573    }
574
575}
576
577//  The default finalBlock method simply dispatches to the doBlock routine.
578void BlockOrientedKernel::generateFinalBlockMethod(const std::unique_ptr<KernelBuilder> & idb, Value * /* remainingItems */) {
579    CreateDoBlockMethodCall(idb);
580}
581
582void BlockOrientedKernel::CreateDoBlockMethodCall(const std::unique_ptr<KernelBuilder> & idb) {
583    if (idb->supportsIndirectBr()) {
584        BasicBlock * bb = idb->CreateBasicBlock("resume");
585        mStrideLoopBranch->addDestination(bb);
586        mStrideLoopTarget->addIncoming(BlockAddress::get(bb), idb->GetInsertBlock());
587        idb->CreateBr(mStrideLoopBody);
588        bb->moveAfter(idb->GetInsertBlock());
589        idb->SetInsertPoint(bb);
590    } else {
591        idb->CreateCall(mDoBlockMethod, getInstance());
592    }
593}
594
595void MultiBlockKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & kb) {
596
597    auto ip = kb->saveIP();
598    Function * const cp = mCurrentMethod;
599    const auto saveInstance = getInstance();
600
601    // First prepare the multi-block method that will be used.
602
603    DataLayout DL(kb->getModule());
604    IntegerType * const intAddressTy = DL.getIntPtrType(kb->getContext());
605
606    std::vector<Type *> multiBlockParmTypes;
607    multiBlockParmTypes.push_back(mKernelStateType->getPointerTo());
608    multiBlockParmTypes.push_back(kb->getSizeTy());
609    for (auto buffer : mStreamSetInputBuffers) {
610        multiBlockParmTypes.push_back(buffer->getPointerType());
611    }
612    for (auto buffer : mStreamSetOutputBuffers) {
613        multiBlockParmTypes.push_back(buffer->getPointerType());
614    }
615
616    FunctionType * const type = FunctionType::get(kb->getVoidTy(), multiBlockParmTypes, false);
617    Function * multiBlockFunction = Function::Create(type, GlobalValue::InternalLinkage, getName() + MULTI_BLOCK_SUFFIX, kb->getModule());
618    multiBlockFunction->setCallingConv(CallingConv::C);
619    multiBlockFunction->setDoesNotThrow();
620    auto args = multiBlockFunction->arg_begin();
621    args->setName("self");
622    setInstance(&*args);
623    (++args)->setName("itemsToDo");
624    for (auto binding : mStreamSetInputs) {
625        (++args)->setName(binding.name + "BufPtr");
626    }
627    for (auto binding : mStreamSetOutputs) {
628        (++args)->setName(binding.name + "BufPtr");
629    }
630
631    // Now use the generateMultiBlockLogic method of the MultiBlockKernelBuilder subtype to
632    // provide the required multi-block kernel logic.
633    mCurrentMethod = multiBlockFunction;
634    kb->SetInsertPoint(BasicBlock::Create(kb->getContext(), "multiBlockEntry", multiBlockFunction, 0));
635    generateMultiBlockLogic(kb);
636
637    kb->CreateRetVoid();
638
639    kb->restoreIP(ip);
640    mCurrentMethod = cp;
641    setInstance(saveInstance);
642
643    // Now proceed with creation of the doSegment method.
644
645    BasicBlock * const entry = kb->GetInsertBlock();
646    BasicBlock * const doSegmentOuterLoop = kb->CreateBasicBlock(getName() + "_doSegmentOuterLoop");
647    BasicBlock * const doMultiBlockCall = kb->CreateBasicBlock(getName() + "_doMultiBlockCall");
648    BasicBlock * const tempBlockCheck = kb->CreateBasicBlock(getName() + "_tempBlockCheck");
649    BasicBlock * const doTempBufferBlock = kb->CreateBasicBlock(getName() + "_doTempBufferBlock");
650    BasicBlock * const segmentDone = kb->CreateBasicBlock(getName() + "_segmentDone");
651
652    Value * blockBaseMask = kb->CreateNot(kb->getSize(kb->getBitBlockWidth() - 1));
653
654    //
655    //  A. Temporary Buffer Area Determination
656    //
657    // For final block processing and for processing near the end of physical buffer
658    // boundaries, we need to allocate temporary space for processing a full block of input.
659    // Compute the size requirements to store stream set data at the declared processing
660    // rates in reference to one block of the principal input stream.
661    //
662
663    unsigned bitBlockWidth = kb->getBitBlockWidth();
664    std::vector<Type *> tempBuffers;
665    std::vector<unsigned> itemsPerPrincipalBlock;
666    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
667        auto & rate = mStreamSetInputs[i].rate;
668        std::string refSet = mStreamSetInputs[i].rate.referenceStreamSet();
669        if (refSet.empty()) {
670            itemsPerPrincipalBlock.push_back(rate.calculateRatio(bitBlockWidth));
671        }
672        else {
673            Port port; unsigned ssIdx;
674            std::tie(port, ssIdx) = getStreamPort(mStreamSetInputs[i].name);
675            assert (port == Port::Input && ssIdx < i);
676            itemsPerPrincipalBlock.push_back(rate.calculateRatio(itemsPerPrincipalBlock[ssIdx]));
677        }
678        unsigned blocks = (itemsPerPrincipalBlock.back() + bitBlockWidth - 1)/bitBlockWidth +2;
679        if (blocks > 1) {
680            tempBuffers.push_back(ArrayType::get(mStreamSetInputBuffers[i]->getType(), blocks));
681        }
682        else {
683            tempBuffers.push_back(mStreamSetInputBuffers[i]->getType());
684        }
685    }
686
687    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
688        auto & rate = mStreamSetOutputs[i].rate;
689        std::string refSet = mStreamSetOutputs[i].rate.referenceStreamSet();
690        if (refSet.empty()) {
691            itemsPerPrincipalBlock.push_back(rate.calculateRatio(bitBlockWidth));
692        }
693        else {
694            Port port; unsigned ssIdx;
695            std::tie(port, ssIdx) = getStreamPort(mStreamSetOutputs[i].name);
696            if (port == Port::Output) ssIdx += mStreamSetInputs.size();
697            itemsPerPrincipalBlock.push_back(rate.calculateRatio(itemsPerPrincipalBlock[ssIdx]));
698        }
699        unsigned blocks = (itemsPerPrincipalBlock.back() + bitBlockWidth - 1)/bitBlockWidth +2;
700        if (blocks > 1) {
701            tempBuffers.push_back(ArrayType::get(mStreamSetOutputBuffers[i]->getType(), blocks));
702        }
703        else {
704            tempBuffers.push_back(mStreamSetOutputBuffers[i]->getType());
705        }
706    }
707
708    Type * tempParameterStructType = StructType::create(kb->getContext(), tempBuffers);
709    Value * tempParameterArea = kb->CreateCacheAlignedAlloca(tempParameterStructType);
710
711    ConstantInt * blockSize = kb->getSize(kb->getBitBlockWidth());
712
713    Value * availablePos = mAvailableItemCount[0];
714    Value * itemsAvail = availablePos;
715
716    //  Make sure that corresponding data is available depending on processing rate
717    //  for all input stream sets.
718
719    for (unsigned i = 1; i < mStreamSetInputs.size(); i++) {
720        Value * a = mAvailableItemCount[i];
721        auto & rate = mStreamSetInputs[i].rate;
722        assert (((rate.referenceStreamSet().empty()) || (rate.referenceStreamSet() == mStreamSetInputs[0].name)) && "Multiblock kernel input rate not with respect to principal stream.");
723        Value * maxItems = rate.CreateMaxReferenceItemsCalculation(kb.get(), a);
724        itemsAvail = kb->CreateSelect(kb->CreateICmpULT(itemsAvail, maxItems), itemsAvail, maxItems);
725    }
726
727    Value * processed = kb->getProcessedItemCount(mStreamSetInputs[0].name);
728    Value * itemsToDo = kb->CreateSub(itemsAvail, processed);
729    Value * fullBlocksToDo = kb->CreateUDiv(itemsToDo, blockSize);
730    Value * excessItems = kb->CreateURem(itemsToDo, blockSize);
731
732    //  Now we iteratively process these blocks using the doMultiBlock method.
733    //  In each iteration, we process the maximum number of linearly accessible
734    //  blocks on the principal input, reduced to ensure that the corresponding
735    //  data is linearly available at the specified processing rates for the other inputs,
736    //  and that each of the output buffers has sufficient linearly available space
737    //  (using overflow areas, if necessary) for the maximum output that can be
738    //  produced.
739
740    kb->CreateBr(doSegmentOuterLoop);
741    kb->SetInsertPoint(doSegmentOuterLoop);
742    PHINode * const blocksRemaining = kb->CreatePHI(kb->getSizeTy(), 2, "blocksRemaining");
743    blocksRemaining->addIncoming(fullBlocksToDo, entry);
744
745    // For each input buffer, determine the processedItemCount, the block pointer for the
746    // buffer block containing the next item, and the number of linearly available items.
747
748    std::vector<Value *> processedItemCount;
749    std::vector<Value *> inputBlockPtr;
750    std::vector<Value *> producedItemCount;
751    std::vector<Value *> outputBlockPtr;
752
753    //  Now determine the linearly available blocks, based on blocks remaining reduced
754    //  by limitations of linearly available input buffer space.
755
756    Value * linearlyAvailBlocks = blocksRemaining;
757    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
758        Value * p = kb->getProcessedItemCount(mStreamSetInputs[i].name);
759        Value * blkNo = kb->CreateUDiv(p, blockSize);
760        Value * b = kb->getInputStreamBlockPtr(mStreamSetInputs[i].name, kb->getInt32(0));
761        processedItemCount.push_back(p);
762        inputBlockPtr.push_back(b);
763        auto & rate = mStreamSetInputs[i].rate;
764        Value * blocks = nullptr;
765        if ((rate.isFixedRatio()) && (rate.getRatioNumerator() == rate.getRatioDenominator()) && (rate.referenceStreamSet() == "")) {
766            blocks = mStreamSetInputBuffers[i]->getLinearlyAccessibleBlocks(kb.get(), blkNo);
767        } else {
768            Value * linearlyAvailItems = mStreamSetInputBuffers[i]->getLinearlyAccessibleItems(kb.get(), p);
769            Value * items = rate.CreateMaxReferenceItemsCalculation(kb.get(), linearlyAvailItems);
770            blocks = kb->CreateUDiv(items, blockSize);
771        }
772        linearlyAvailBlocks = kb->CreateSelect(kb->CreateICmpULT(blocks, linearlyAvailBlocks), blocks, linearlyAvailBlocks);
773    }
774    //  Now determine the linearly writeable blocks, based on available blocks reduced
775    //  by limitations of output buffer space.
776    Value * linearlyWritableBlocks = linearlyAvailBlocks;
777
778    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
779        Value * p = kb->getProducedItemCount(mStreamSetOutputs[i].name);
780        Value * blkNo = kb->CreateUDiv(p, blockSize);
781        Value * b = kb->getOutputStreamBlockPtr(mStreamSetOutputs[i].name, kb->getInt32(0));
782        producedItemCount.push_back(p);
783        outputBlockPtr.push_back(b);
784        auto & rate = mStreamSetOutputs[i].rate;
785        Value * blocks = nullptr;
786        if ((rate.isFixedRatio()) && (rate.getRatioNumerator() == rate.getRatioDenominator())) {
787            blocks = mStreamSetOutputBuffers[0]->getLinearlyWritableBlocks(kb.get(), blkNo);
788        } else {
789            Value * writableItems = mStreamSetOutputBuffers[0]->getLinearlyWritableItems(kb.get(), p);
790            blocks = kb->CreateUDiv(writableItems, blockSize);
791        }
792        linearlyWritableBlocks = kb->CreateSelect(kb->CreateICmpULT(blocks, linearlyWritableBlocks), blocks, linearlyWritableBlocks);
793    }
794    Value * haveBlocks = kb->CreateICmpUGT(linearlyWritableBlocks, kb->getSize(0));
795    kb->CreateCondBr(haveBlocks, doMultiBlockCall, tempBlockCheck);
796
797    //  At this point we have verified the availability of one or more blocks of input data and output buffer space for all stream sets.
798    //  Now prepare the doMultiBlock call.
799    kb->SetInsertPoint(doMultiBlockCall);
800
801    Value * linearlyAvailItems = kb->CreateMul(linearlyWritableBlocks, blockSize);
802
803    std::vector<Value *> doMultiBlockArgs;
804    doMultiBlockArgs.push_back(getInstance());
805    doMultiBlockArgs.push_back(linearlyAvailItems);
806    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
807        Value * bufPtr = kb->getRawInputPointer(mStreamSetInputs[i].name, kb->getInt32(0), processedItemCount[i]);
808        bufPtr = kb->CreatePointerCast(bufPtr, mStreamSetInputBuffers[i]->getPointerType());
809        doMultiBlockArgs.push_back(bufPtr);
810    }
811    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
812        Value * bufPtr = kb->getRawOutputPointer(mStreamSetOutputs[i].name, kb->getInt32(0), producedItemCount[i]);
813        bufPtr = kb->CreatePointerCast(bufPtr, mStreamSetOutputBuffers[i]->getPointerType());
814        doMultiBlockArgs.push_back(bufPtr);
815    }
816
817    kb->CreateCall(multiBlockFunction, doMultiBlockArgs);
818    // Do copybacks if necessary.
819    unsigned priorIdx = 0;
820    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
821        Value * log2BlockSize = kb->getSize(std::log2(kb->getBitBlockWidth()));
822        if (auto cb = dyn_cast<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
823            BasicBlock * copyBack = kb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
824            BasicBlock * done = kb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
825            Value * newlyProduced = kb->CreateSub(kb->getProducedItemCount(mStreamSetOutputs[i].name), producedItemCount[i]);
826            Value * priorBlock = kb->CreateLShr(producedItemCount[i], log2BlockSize);
827            Value * priorOffset = kb->CreateAnd(producedItemCount[i], kb->getSize(kb->getBitBlockWidth() - 1));
828            Value * instance = kb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
829            Value * accessibleBlocks = cb->getLinearlyAccessibleBlocks(kb.get(), priorBlock);
830            Value * accessible = kb->CreateSub(kb->CreateShl(accessibleBlocks, log2BlockSize), priorOffset);
831            Value * wraparound = kb->CreateICmpULT(accessible, newlyProduced);
832            kb->CreateCondBr(wraparound, copyBack, done);
833            kb->SetInsertPoint(copyBack);
834            Value * copyItems = kb->CreateSub(newlyProduced, accessible);
835            cb->createCopyBack(kb.get(), instance, copyItems);
836            kb->CreateBr(done);
837            kb->SetInsertPoint(done);
838            priorIdx++;
839        }
840        if (auto cb = dyn_cast<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
841            BasicBlock * copyBack = kb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
842            BasicBlock * done = kb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
843            Value * instance = kb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
844            Value * newlyProduced = kb->CreateSub(kb->getProducedItemCount(mStreamSetOutputs[i].name), producedItemCount[i]);
845            Value * accessible = cb->getLinearlyAccessibleItems(kb.get(), producedItemCount[i]);
846            Value * wraparound = kb->CreateICmpULT(accessible, newlyProduced);
847            kb->CreateCondBr(wraparound, copyBack, done);
848            kb->SetInsertPoint(copyBack);
849            Value * copyItems = kb->CreateSub(newlyProduced, accessible);
850            cb->createCopyBack(kb.get(), instance, copyItems);
851            kb->CreateBr(done);
852            kb->SetInsertPoint(done);
853            priorIdx++;
854        }
855    }
856    kb->setProcessedItemCount(mStreamSetInputs[0].name, kb->CreateAdd(processed, linearlyAvailItems));
857    Value * reducedBlocksToDo = kb->CreateSub(blocksRemaining, linearlyWritableBlocks);
858    Value * fullBlocksRemain = kb->CreateICmpUGT(reducedBlocksToDo, kb->getSize(0));
859    BasicBlock * multiBlockFinal = kb->GetInsertBlock();
860    blocksRemaining->addIncoming(reducedBlocksToDo, multiBlockFinal);
861    kb->CreateCondBr(fullBlocksRemain, doSegmentOuterLoop, tempBlockCheck);
862    //iBuilder->CreateBr(doSegmentOuterLoop);
863    //
864    // We use temporary buffers in 3 different cases that preclude full block processing.
865    // (a) One or more input buffers does not have a sufficient number of input items linearly available.
866    // (b) One or more output buffers does not have sufficient linearly available buffer space.
867    // (c) We have processed all the full blocks of input and only the excessItems remain.
868    // In each case we set up temporary buffers for input and output and then
869    // call the Multiblock routine.
870    //
871
872    kb->SetInsertPoint(tempBlockCheck);
873    PHINode * const tempBlocksRemain = kb->CreatePHI(kb->getSizeTy(), 2, "tempBlocksRemain");
874    tempBlocksRemain->addIncoming(blocksRemaining, doSegmentOuterLoop);
875    tempBlocksRemain->addIncoming(reducedBlocksToDo, multiBlockFinal);
876
877    haveBlocks = kb->CreateICmpUGT(tempBlocksRemain, kb->getSize(0));
878    kb->CreateCondBr(kb->CreateOr(mIsFinal, haveBlocks), doTempBufferBlock, segmentDone);
879
880    //
881    // We use temporary buffers in 3 different cases that preclude full block processing.
882    // (a) One or more input buffers does not have a sufficient number of input items linearly available.
883    // (b) One or more output buffers does not have sufficient linearly available buffer space.
884    // (c) We have processed all the full blocks of input and only the excessItems remain.
885    // In each case we set up temporary buffers for input and output and then
886    // call the Multiblock routine.
887    //
888    kb->SetInsertPoint(doTempBufferBlock);
889    Value * tempBlockItems = kb->CreateSelect(haveBlocks, blockSize, excessItems);
890
891    // Begin constructing the doMultiBlock args.
892    std::vector<Value *> tempArgs;
893    tempArgs.push_back(getInstance());
894    tempArgs.push_back(tempBlockItems);
895
896    // Prepare the temporary buffer area.
897    //
898    // First zero it out.
899    Constant * const tempAreaSize = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(tempParameterStructType), kb->getSizeTy(), false);
900    kb->CreateMemZero(tempParameterArea, tempAreaSize);
901
902    // For each input and output buffer, copy over necessary data starting from the last
903    // block boundary.
904    std::vector<Value *> finalItemPos;
905    finalItemPos.push_back(kb->CreateAdd(processedItemCount[0], tempBlockItems));
906
907    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); i++) {
908        Value * tempBufPtr = kb->CreateGEP(tempParameterArea, kb->getInt32(i));
909        tempBufPtr = kb->CreatePointerCast(tempBufPtr, mStreamSetInputBuffers[i]->getPointerType());
910
911        Value * blockItemPos = kb->CreateAnd(processedItemCount[i], blockBaseMask);
912
913        // The number of items to copy is determined by the processing rate requirements.
914        if (i > 1) {
915            auto & rate = mStreamSetInputs[i].rate;
916            std::string refSet = mStreamSetInputs[i].rate.referenceStreamSet();
917            if (refSet.empty()) {
918                finalItemPos.push_back(rate.CreateRatioCalculation(kb.get(), finalItemPos[0], kb->CreateNot(haveBlocks)));
919            }
920            else {
921                Port port; unsigned ssIdx;
922                std::tie(port, ssIdx) = getStreamPort(mStreamSetInputs[i].name);
923                assert (port == Port::Input && ssIdx < i);
924                finalItemPos.push_back(rate.CreateRatioCalculation(kb.get(), finalItemPos[ssIdx], kb->CreateNot(haveBlocks)));
925            }
926        }
927        Value * neededItems = kb->CreateSub(finalItemPos[i], blockItemPos);
928        Value * availFromBase = mStreamSetInputBuffers[i]->getLinearlyAccessibleItems(kb.get(), blockItemPos);
929        Value * copyItems1 = kb->CreateSelect(kb->CreateICmpULT(neededItems, availFromBase), neededItems, availFromBase);
930        Value * copyItems2 = kb->CreateSub(neededItems, copyItems1);
931        Value * inputPtr = kb->getInputStreamBlockPtr(mStreamSetInputs[i].name, kb->getInt32(0));
932        mStreamSetInputBuffers[i]->createBlockAlignedCopy(kb.get(), tempBufPtr, inputPtr, copyItems1);
933        Value * nextBufPtr = kb->CreateGEP(tempBufPtr, kb->CreateUDiv(availFromBase, blockSize));
934        mStreamSetInputBuffers[i]->createBlockAlignedCopy(kb.get(), nextBufPtr, kb->getStreamSetBufferPtr(mStreamSetInputs[i].name), copyItems2);
935
936        Value * itemAddress = kb->getRawInputPointer(mStreamSetInputs[i].name, kb->getInt32(0), processedItemCount[i]);
937        itemAddress = kb->CreatePtrToInt(itemAddress, intAddressTy);
938
939        Value * baseAddress = inputBlockPtr[i];
940        baseAddress = kb->CreatePtrToInt(baseAddress, intAddressTy);
941
942
943        Value * tempAddress = kb->CreateAdd(kb->CreatePtrToInt(tempBufPtr, intAddressTy), kb->CreateSub(itemAddress, baseAddress));
944        tempArgs.push_back(kb->CreateIntToPtr(tempAddress, mStreamSetInputBuffers[i]->getPointerType()));
945    }
946
947    std::vector<Value *> blockItemPos;
948    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); i++) {
949        Value * tempBufPtr = kb->CreateGEP(tempParameterArea, kb->getInt32(mStreamSetInputs.size() + i));
950        tempBufPtr = kb->CreatePointerCast(tempBufPtr, mStreamSetOutputBuffers[i]->getPointerType());
951        blockItemPos.push_back(kb->CreateAnd(producedItemCount[i], blockBaseMask));
952        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(kb.get(), tempBufPtr, outputBlockPtr[i], kb->CreateSub(producedItemCount[i], blockItemPos[i]));
953        Value * itemAddress = kb->CreatePtrToInt(kb->getRawOutputPointer(mStreamSetInputs[i].name, kb->getInt32(0), producedItemCount[i]), intAddressTy);
954        Value * outputPtr = kb->getOutputStreamBlockPtr(mStreamSetOutputs[i].name, kb->getInt32(0));
955        Value * baseAddress = kb->CreatePtrToInt(outputPtr, intAddressTy);
956        Value * tempAddress = kb->CreateAdd(kb->CreatePtrToInt(tempBufPtr, intAddressTy), kb->CreateSub(itemAddress, baseAddress));
957        tempArgs.push_back(kb->CreateIntToPtr(tempAddress, mStreamSetOutputBuffers[i]->getPointerType()));
958    }
959
960
961    kb->CreateCall(multiBlockFunction, tempArgs);
962
963    // Copy back data to the actual output buffers.
964
965    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); i++) {
966        Value * tempBufPtr = kb->CreateGEP(tempParameterArea, kb->getInt32(mStreamSetInputs.size() + i));
967        tempBufPtr = kb->CreatePointerCast(tempBufPtr, mStreamSetOutputBuffers[i]->getPointerType());
968        Value * final_items = kb->getProducedItemCount(mStreamSetOutputs[i].name);
969        Value * copyItems = kb->CreateSub(final_items, blockItemPos[i]);
970        Value * copyItems1 = mStreamSetOutputBuffers[i]->getLinearlyWritableItems(kb.get(), blockItemPos[i]); // must be a whole number of blocks.
971        Value * outputPtr = kb->getOutputStreamBlockPtr(mStreamSetOutputs[i].name, kb->getInt32(0));
972        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(kb.get(), outputPtr, tempBufPtr, copyItems1);
973        Value * copyItems2 = kb->CreateSelect(kb->CreateICmpULT(copyItems, copyItems), kb->getSize(0), kb->CreateSub(copyItems, copyItems1));
974        tempBufPtr = kb->CreateGEP(tempBufPtr, kb->CreateUDiv(copyItems1, blockSize));
975        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(kb.get(), kb->getStreamSetBufferPtr(mStreamSetOutputs[i].name), tempBufPtr, copyItems2);
976    }
977
978    kb->setProcessedItemCount(mStreamSetInputs[0].name, finalItemPos[0]);
979
980    //  We've dealt with the partial block processing and copied information back into the
981    //  actual buffers.  If this isn't the final block, loop back for more multiblock processing.
982    //
983    blocksRemaining->addIncoming(kb->CreateSub(tempBlocksRemain, kb->CreateZExt(haveBlocks, kb->getSizeTy())), kb->GetInsertBlock());
984    kb->CreateCondBr(haveBlocks, doSegmentOuterLoop, segmentDone);
985    kb->SetInsertPoint(segmentDone);
986}
987
988void Kernel::finalizeInstance(const std::unique_ptr<KernelBuilder> & idb) {
989    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
990    mOutputScalarResult = idb->CreateCall(getTerminateFunction(idb->getModule()), { getInstance() });
991}
992
993Kernel::StreamPort Kernel::getStreamPort(const std::string & name) const {
994    const auto f = mStreamMap.find(name);
995    if (LLVM_UNLIKELY(f == mStreamMap.end())) {
996        report_fatal_error(getName() + " does not contain stream set " + name);
997    }
998    return f->second;
999}
1000
1001// CONSTRUCTOR
1002Kernel::Kernel(std::string && kernelName,
1003                             std::vector<Binding> && stream_inputs,
1004                             std::vector<Binding> && stream_outputs,
1005                             std::vector<Binding> && scalar_parameters,
1006                             std::vector<Binding> && scalar_outputs,
1007                             std::vector<Binding> && internal_scalars)
1008: KernelInterface(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars))
1009, mCurrentMethod(nullptr)
1010, mNoTerminateAttribute(false)
1011, mIsGenerated(false)
1012, mIsFinal(nullptr)
1013, mOutputScalarResult(nullptr) {
1014
1015}
1016
1017Kernel::~Kernel() {
1018
1019}
1020
1021// CONSTRUCTOR
1022BlockOrientedKernel::BlockOrientedKernel(std::string && kernelName,
1023                                         std::vector<Binding> && stream_inputs,
1024                                         std::vector<Binding> && stream_outputs,
1025                                         std::vector<Binding> && scalar_parameters,
1026                                         std::vector<Binding> && scalar_outputs,
1027                                         std::vector<Binding> && internal_scalars)
1028: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars))
1029, mDoBlockMethod(nullptr)
1030, mStrideLoopBody(nullptr)
1031, mStrideLoopBranch(nullptr)
1032, mStrideLoopTarget(nullptr) {
1033
1034}
1035
1036// CONSTRUCTOR
1037MultiBlockKernel::MultiBlockKernel(std::string && kernelName,
1038                                     std::vector<Binding> && stream_inputs,
1039                                     std::vector<Binding> && stream_outputs,
1040                                     std::vector<Binding> && scalar_parameters,
1041                                     std::vector<Binding> && scalar_outputs,
1042                                             std::vector<Binding> && internal_scalars)
1043: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
1044   
1045}
1046
1047// CONSTRUCTOR
1048SegmentOrientedKernel::SegmentOrientedKernel(std::string && kernelName,
1049                                             std::vector<Binding> && stream_inputs,
1050                                             std::vector<Binding> && stream_outputs,
1051                                             std::vector<Binding> && scalar_parameters,
1052                                             std::vector<Binding> && scalar_outputs,
1053                                             std::vector<Binding> && internal_scalars)
1054: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
1055   
1056}
1057   
1058}
Note: See TracBrowser for help on using the repository browser.