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

Last change on this file since 5175 was 5175, checked in by cameron, 3 years ago

Some tidy ups and changes to prepare for LLVM 3.9

File size: 23.8 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 <llvm/IR/Module.h>
8#include <llvm/IR/Type.h>
9#include <llvm/IR/Value.h>
10#include <llvm/Support/raw_ostream.h>
11#include <llvm/IR/TypeBuilder.h>
12#include <llvm/Support/ErrorHandling.h>
13#include <toolchain.h>
14
15using namespace llvm;
16using namespace kernel;
17
18KernelBuilder::KernelBuilder(IDISA::IDISA_Builder * builder,
19                                 std::string kernelName,
20                                 std::vector<StreamSetBinding> stream_inputs,
21                                 std::vector<StreamSetBinding> stream_outputs,
22                                 std::vector<ScalarBinding> scalar_parameters,
23                                 std::vector<ScalarBinding> scalar_outputs,
24                                 std::vector<ScalarBinding> internal_scalars) :
25    KernelInterface(builder, kernelName, stream_inputs, stream_outputs, scalar_parameters, scalar_outputs, internal_scalars) {}
26
27void KernelBuilder::addScalar(Type * t, std::string scalarName) {
28    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
29        llvm::report_fatal_error("Illegal addition of kernel field after kernel state finalized: " + scalarName);
30    }
31    unsigned index = mKernelFields.size();
32    mKernelFields.push_back(t);
33    mInternalStateNameMap.emplace(scalarName, index);
34}
35
36void KernelBuilder::prepareKernel() {
37    unsigned blockSize = iBuilder->getBitBlockWidth();
38    if (mStreamSetInputs.size() != mStreamSetInputBuffers.size()) {
39        llvm::report_fatal_error("Kernel preparation: Incorrect number of input buffers");
40    }
41    if (mStreamSetOutputs.size() != mStreamSetOutputBuffers.size()) {
42        llvm::report_fatal_error("Kernel preparation: Incorrect number of output buffers");
43    }
44    addScalar(iBuilder->getSizeTy(), blockNoScalar);
45    addScalar(iBuilder->getSizeTy(), logicalSegmentNoScalar);
46    addScalar(iBuilder->getSizeTy(), processedItemCount);
47    addScalar(iBuilder->getSizeTy(), producedItemCount);
48    addScalar(iBuilder->getInt1Ty(), terminationSignal);
49    int streamSetNo = 0;
50    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
51        if (!(mStreamSetInputBuffers[i]->getBufferStreamSetType() == mStreamSetInputs[i].ssType)) {
52             llvm::report_fatal_error("Kernel preparation: Incorrect input buffer type");
53        }
54        if ((mStreamSetInputBuffers[i]->getBufferSize() > 0) && (mStreamSetInputBuffers[i]->getBufferSize() < codegen::SegmentSize + (blockSize + mLookAheadPositions - 1)/blockSize)) {
55             errs() << "buffer size = " << mStreamSetInputBuffers[i]->getBufferSize() << "\n";
56             llvm::report_fatal_error("Kernel preparation: Buffer size too small.");
57        }
58        mScalarInputs.push_back(ScalarBinding{mStreamSetInputBuffers[i]->getStreamSetStructPointerType(), mStreamSetInputs[i].ssName + basePtrSuffix});
59        mStreamSetNameMap.emplace(mStreamSetInputs[i].ssName, streamSetNo);
60        streamSetNo++;
61    }
62    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
63        if (!(mStreamSetOutputBuffers[i]->getBufferStreamSetType() == mStreamSetOutputs[i].ssType)) {
64             llvm::report_fatal_error("Kernel preparation: Incorrect output buffer type");
65        }
66        mScalarInputs.push_back(ScalarBinding{mStreamSetOutputBuffers[i]->getStreamSetStructPointerType(), mStreamSetOutputs[i].ssName + basePtrSuffix});
67        mStreamSetNameMap.emplace(mStreamSetOutputs[i].ssName, streamSetNo);
68        streamSetNo++;
69    }
70    for (auto binding : mScalarInputs) {
71        addScalar(binding.scalarType, binding.scalarName);
72    }
73    for (auto binding : mScalarOutputs) {
74        addScalar(binding.scalarType, binding.scalarName);
75    }
76    for (auto binding : mInternalScalars) {
77        addScalar(binding.scalarType, binding.scalarName);
78    }
79    mKernelStateType = StructType::create(iBuilder->getContext(), mKernelFields, mKernelName);
80}
81
82std::unique_ptr<Module> KernelBuilder::createKernelModule(std::vector<StreamSetBuffer *> input_buffers, std::vector<StreamSetBuffer *> output_buffers) {
83    Module * saveModule = iBuilder->getModule();
84    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
85    std::unique_ptr<Module> theModule = make_unique<Module>(mKernelName + "_" + iBuilder->getBitBlockTypeName(), iBuilder->getContext());
86    Module * m = theModule.get();
87    iBuilder->setModule(m);
88    generateKernel(input_buffers, output_buffers);
89    iBuilder->setModule(saveModule);
90    iBuilder->restoreIP(savePoint);
91    return theModule;
92}
93
94void KernelBuilder::generateKernel(std::vector<StreamSetBuffer *> input_buffers, std::vector<StreamSetBuffer*> output_buffers) {
95    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
96    Module * m = iBuilder->getModule();
97    mStreamSetInputBuffers = input_buffers;
98    mStreamSetOutputBuffers = output_buffers;
99    prepareKernel();  // possibly overriden by the KernelBuilder subtype
100    KernelInterface::addKernelDeclarations(m);
101    generateDoBlockMethod();     // must be implemented by the KernelBuilder subtype
102    generateFinalBlockMethod();  // possibly overriden by the KernelBuilder subtype
103    generateDoSegmentMethod();
104
105    // Implement the accumulator get functions
106    for (auto binding : mScalarOutputs) {
107        auto fnName = mKernelName + accumulator_infix + binding.scalarName;
108        Function * accumFn = m->getFunction(fnName);
109        iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "get_" + binding.scalarName, accumFn, 0));
110        Value * self = &*(accumFn->arg_begin());
111        Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(binding.scalarName)});
112        Value * retVal = iBuilder->CreateLoad(ptr);
113        iBuilder->CreateRet(retVal);
114    }
115    // Implement the initializer function
116    Function * initFunction = m->getFunction(mKernelName + init_suffix);
117    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "Init_entry", initFunction, 0));
118   
119    Function::arg_iterator args = initFunction->arg_begin();
120    Value * self = &*(args++);
121    iBuilder->CreateStore(Constant::getNullValue(mKernelStateType), self);
122    for (auto binding : mScalarInputs) {
123        Value * parm = &*(args++);
124        Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(binding.scalarName)});
125        iBuilder->CreateStore(parm, ptr);
126    }
127    iBuilder->CreateRetVoid();
128    iBuilder->restoreIP(savePoint);
129}
130
131//  The default finalBlock method simply dispatches to the doBlock routine.
132void KernelBuilder::generateFinalBlockMethod() {
133    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
134    Module * m = iBuilder->getModule();
135    Function * doBlockFunction = m->getFunction(mKernelName + doBlock_suffix);
136    Function * finalBlockFunction = m->getFunction(mKernelName + finalBlock_suffix);
137    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "fb_entry", finalBlockFunction, 0));
138    // Final Block arguments: self, remaining, then the standard DoBlock args.
139    Function::arg_iterator args = finalBlockFunction->arg_begin();
140    Value * self = &*(args++);
141    /* Skip "remaining" arg */ args++;
142    std::vector<Value *> doBlockArgs = {self};
143    while (args != finalBlockFunction->arg_end()){
144        doBlockArgs.push_back(&*args++);
145    }
146    iBuilder->CreateCall(doBlockFunction, doBlockArgs);
147    iBuilder->CreateRetVoid();
148    iBuilder->restoreIP(savePoint);
149}
150
151void KernelBuilder::generateDoBlockLogic(Value * self, Value * blockNo) {
152    Function * doBlockFunction = iBuilder->getModule()->getFunction(mKernelName + doBlock_suffix);
153    iBuilder->CreateCall(doBlockFunction, {self});
154}
155
156//  The default doSegment method dispatches to the doBlock routine for
157//  each block of the given number of blocksToDo, and then updates counts.
158void KernelBuilder::generateDoSegmentMethod() {
159    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
160    Module * m = iBuilder->getModule();
161    Function * doSegmentFunction = m->getFunction(mKernelName + doSegment_suffix);
162    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doSegmentFunction, 0));
163    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
164    BasicBlock * blockLoopCond = BasicBlock::Create(iBuilder->getContext(), "blockLoopCond", doSegmentFunction, 0);
165    BasicBlock * blockLoopBody = BasicBlock::Create(iBuilder->getContext(), "blockLoopBody", doSegmentFunction, 0);
166    BasicBlock * blocksDone = BasicBlock::Create(iBuilder->getContext(), "blocksDone", doSegmentFunction, 0);
167    Type * const size_ty = iBuilder->getSizeTy();
168    Value * stride = ConstantInt::get(size_ty, iBuilder->getStride());
169    Value * strideBlocks = ConstantInt::get(size_ty, iBuilder->getStride() / iBuilder->getBitBlockWidth());
170   
171    Function::arg_iterator args = doSegmentFunction->arg_begin();
172    Value * self = &*(args++);
173    Value * blocksToDo = &*(args);
174
175    Value * segmentNo = getLogicalSegmentNo(self);
176    iBuilder->CreateBr(blockLoopCond);
177
178    iBuilder->SetInsertPoint(blockLoopCond);
179    PHINode * blocksRemaining = iBuilder->CreatePHI(size_ty, 2, "blocksRemaining");
180    blocksRemaining->addIncoming(blocksToDo, entryBlock);
181    Value * notDone = iBuilder->CreateICmpUGT(blocksRemaining, ConstantInt::get(size_ty, 0));
182    iBuilder->CreateCondBr(notDone, blockLoopBody, blocksDone);
183
184    iBuilder->SetInsertPoint(blockLoopBody);
185    Value * blockNo = getScalarField(self, blockNoScalar);   
186    generateDoBlockLogic(self, blockNo);
187    setBlockNo(self, iBuilder->CreateAdd(blockNo, strideBlocks));
188    blocksRemaining->addIncoming(iBuilder->CreateSub(blocksRemaining, strideBlocks), blockLoopBody);
189    iBuilder->CreateBr(blockLoopCond);
190   
191    iBuilder->SetInsertPoint(blocksDone);
192    setProcessedItemCount(self, iBuilder->CreateAdd(getProcessedItemCount(self), iBuilder->CreateMul(blocksToDo, stride)));
193    // Must be the last action, for synchronization.
194    setLogicalSegmentNo(self, iBuilder->CreateAdd(segmentNo, ConstantInt::get(size_ty, 1)));
195
196    iBuilder->CreateRetVoid();
197    iBuilder->restoreIP(savePoint);
198}
199
200Value * KernelBuilder::getScalarIndex(std::string fieldName) {
201    const auto f = mInternalStateNameMap.find(fieldName);
202    if (LLVM_UNLIKELY(f == mInternalStateNameMap.end())) {
203        llvm::report_fatal_error("Kernel does not contain internal state: " + fieldName);
204    }
205    return iBuilder->getInt32(f->second);
206}
207
208
209
210Value * KernelBuilder::getScalarField(Value * self, std::string fieldName) {
211    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
212    return iBuilder->CreateLoad(ptr);
213}
214
215void KernelBuilder::setScalarField(Value * self, std::string fieldName, Value * newFieldVal) {
216    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
217    iBuilder->CreateStore(newFieldVal, ptr);
218}
219
220Value * KernelBuilder::getLogicalSegmentNo(Value * self) { 
221    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
222    LoadInst * segNo = iBuilder->CreateAlignedLoad(ptr, sizeof(size_t));
223    segNo->setOrdering(AtomicOrdering::Acquire);
224    return segNo;
225}
226
227Value * KernelBuilder::getProcessedItemCount(Value * self) { 
228    return getScalarField(self, processedItemCount);
229}
230
231Value * KernelBuilder::getProducedItemCount(Value * self) {
232    return getScalarField(self, producedItemCount);
233}
234
235//  By default, kernels do not terminate early. 
236Value * KernelBuilder::getTerminationSignal(Value * self) {
237    return ConstantInt::getNullValue(iBuilder->getInt1Ty());
238}
239
240
241void KernelBuilder::setLogicalSegmentNo(Value * self, Value * newCount) {
242    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
243    iBuilder->CreateAlignedStore(newCount, ptr, sizeof(size_t))->setOrdering(AtomicOrdering::Release);
244}
245
246void KernelBuilder::setProcessedItemCount(Value * self, Value * newCount) {
247    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(processedItemCount)});
248    iBuilder->CreateStore(newCount, ptr);
249}
250
251void KernelBuilder::setProducedItemCount(Value * self, Value * newCount) {
252    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(producedItemCount)});
253    iBuilder->CreateStore(newCount, ptr);
254}
255
256void KernelBuilder::setTerminationSignal(Value * self, Value * newFieldVal) {
257    llvm::report_fatal_error("This kernel type does not support setTerminationSignal.");
258}
259
260
261Value * KernelBuilder::getBlockNo(Value * self) {
262    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
263    LoadInst * blockNo = iBuilder->CreateLoad(ptr);
264    return blockNo;
265}
266
267void KernelBuilder::setBlockNo(Value * self, Value * newFieldVal) {
268    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
269    iBuilder->CreateStore(newFieldVal, ptr);
270}
271
272
273Value * KernelBuilder::getParameter(Function * f, std::string paramName) {
274    for (Function::arg_iterator argIter = f->arg_begin(), end = f->arg_end(); argIter != end; argIter++) {
275        Value * arg = &*argIter;
276        if (arg->getName() == paramName) return arg;
277    }
278    llvm::report_fatal_error("Method does not have parameter: " + paramName);
279}
280
281unsigned KernelBuilder::getStreamSetIndex(std::string ssName) {
282    const auto f = mStreamSetNameMap.find(ssName);
283    if (LLVM_UNLIKELY(f == mStreamSetNameMap.end())) {
284        llvm::report_fatal_error("Kernel does not contain stream set: " + ssName);
285    }
286    return f->second;
287}
288
289size_t KernelBuilder::getStreamSetBufferSize(Value * self, std::string ssName) {
290    unsigned ssIndex = getStreamSetIndex(ssName);
291    if (ssIndex < mStreamSetInputs.size()) {
292        return mStreamSetInputBuffers[ssIndex]->getBufferSize();
293    }
294    else {
295        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getBufferSize();
296    }
297}
298
299Value * KernelBuilder::getStreamSetBasePtr(Value * self, std::string ssName) {
300    return getScalarField(self, ssName + basePtrSuffix);
301}
302
303Value * KernelBuilder::getStreamSetBlockPtr(Value * self, std::string ssName, Value * blockNo) {
304    Value * basePtr = getStreamSetBasePtr(self, ssName);
305    unsigned ssIndex = getStreamSetIndex(ssName);
306    if (ssIndex < mStreamSetInputs.size()) {
307        return mStreamSetInputBuffers[ssIndex]->getStreamSetBlockPointer(basePtr, blockNo);
308    }
309    else {
310        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getStreamSetBlockPointer(basePtr, blockNo);
311    }
312}
313
314Value * KernelBuilder::createInstance(std::vector<Value *> args) {
315    Value * kernelInstance = iBuilder->CreateAlloca(mKernelStateType);
316    Module * m = iBuilder->getModule();
317    std::vector<Value *> init_args = {kernelInstance};
318    for (auto a : args) {
319        init_args.push_back(a);
320    }
321    for (auto b : mStreamSetInputBuffers) { 
322        init_args.push_back(b->getStreamSetStructPtr());
323    }
324    for (auto b : mStreamSetOutputBuffers) { 
325        init_args.push_back(b->getStreamSetStructPtr());
326    }
327    std::string initFnName = mKernelName + init_suffix;
328    Function * initMethod = m->getFunction(initFnName);
329    if (!initMethod) {
330        llvm::report_fatal_error("Cannot find " + initFnName);
331    }
332    iBuilder->CreateCall(initMethod, init_args);
333    return kernelInstance;
334}
335
336Function * KernelBuilder::generateThreadFunction(std::string name){
337    Module * m = iBuilder->getModule();
338    Type * const voidTy = Type::getVoidTy(m->getContext());
339    Type * const voidPtrTy = TypeBuilder<void *, false>::get(m->getContext());
340    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
341    Type * const int1ty = iBuilder->getInt1Ty();
342
343    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
344    threadFunc->setCallingConv(CallingConv::C);
345    Function::arg_iterator args = threadFunc->arg_begin();
346
347    Value * const arg = &*(args++);
348    arg->setName("args");
349
350    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc,0));
351
352    Value * self = iBuilder->CreateBitCast(arg, PointerType::get(mKernelStateType, 0));
353
354    std::vector<Value *> inbufProducerPtrs;
355    std::vector<Value *> inbufConsumerPtrs;
356    std::vector<Value *> outbufProducerPtrs;
357    std::vector<Value *> outbufConsumerPtrs;   
358    std::vector<Value *> endSignalPtrs;
359
360    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
361        Value * basePtr = getStreamSetBasePtr(self, mStreamSetInputs[i].ssName);
362        inbufProducerPtrs.push_back(mStreamSetInputBuffers[i]->getProducerPosPtr(basePtr));
363        inbufConsumerPtrs.push_back(mStreamSetInputBuffers[i]->getConsumerPosPtr(basePtr));
364        endSignalPtrs.push_back(mStreamSetInputBuffers[i]->hasEndOfInputPtr(basePtr));
365    }
366    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
367        Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
368        outbufProducerPtrs.push_back(mStreamSetOutputBuffers[i]->getProducerPosPtr(basePtr));
369        outbufConsumerPtrs.push_back(mStreamSetOutputBuffers[i]->getConsumerPosPtr(basePtr));
370    }
371
372    const unsigned segmentBlocks = codegen::SegmentSize;
373    const unsigned bufferSegments = codegen::BufferSegments;
374    const unsigned segmentSize = segmentBlocks * iBuilder->getBitBlockWidth();
375    Type * const size_ty = iBuilder->getSizeTy();
376
377    Value * segSize = ConstantInt::get(size_ty, segmentSize);
378    Value * bufferSize = ConstantInt::get(size_ty, segmentSize * (bufferSegments - 1));
379    Value * segBlocks = ConstantInt::get(size_ty, segmentBlocks);
380   
381    BasicBlock * outputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "outputCheck", threadFunc, 0);
382    BasicBlock * inputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "inputCheck", threadFunc, 0);
383   
384    BasicBlock * endSignalCheckBlock = BasicBlock::Create(iBuilder->getContext(), "endSignalCheck", threadFunc, 0);
385    BasicBlock * doSegmentBlock = BasicBlock::Create(iBuilder->getContext(), "doSegment", threadFunc, 0);
386    BasicBlock * endBlock = BasicBlock::Create(iBuilder->getContext(), "end", threadFunc, 0);
387    BasicBlock * doFinalSegBlock = BasicBlock::Create(iBuilder->getContext(), "doFinalSeg", threadFunc, 0);
388    BasicBlock * doFinalBlock = BasicBlock::Create(iBuilder->getContext(), "doFinal", threadFunc, 0);
389
390    iBuilder->CreateBr(outputCheckBlock);
391
392    iBuilder->SetInsertPoint(outputCheckBlock);
393
394    Value * waitCondTest = ConstantInt::get(int1ty, 1);   
395    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
396        LoadInst * producerPos = iBuilder->CreateAlignedLoad(outbufProducerPtrs[i], sizeof(size_t));
397        producerPos->setOrdering(AtomicOrdering::Acquire);
398        // iBuilder->CallPrintInt(name + ":output producerPos", producerPos);
399        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(outbufConsumerPtrs[i], sizeof(size_t));
400        consumerPos->setOrdering(AtomicOrdering::Acquire);
401        // iBuilder->CallPrintInt(name + ":output consumerPos", consumerPos);
402        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(producerPos, iBuilder->CreateAdd(consumerPos, bufferSize)));
403    }
404   
405    iBuilder->CreateCondBr(waitCondTest, inputCheckBlock, outputCheckBlock); 
406
407    iBuilder->SetInsertPoint(inputCheckBlock); 
408
409    Value * requiredSize = segSize;
410    if (mLookAheadPositions > 0) {
411        requiredSize = iBuilder->CreateAdd(segSize, ConstantInt::get(size_ty, mLookAheadPositions));
412    }
413    waitCondTest = ConstantInt::get(int1ty, 1); 
414    for (unsigned i = 0; i < inbufProducerPtrs.size(); i++) {
415        LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[i], sizeof(size_t));
416        producerPos->setOrdering(AtomicOrdering::Acquire);
417        // iBuilder->CallPrintInt(name + ":input producerPos", producerPos);
418        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(inbufConsumerPtrs[i], sizeof(size_t));
419        consumerPos->setOrdering(AtomicOrdering::Acquire);
420        // iBuilder->CallPrintInt(name + ":input consumerPos", consumerPos);
421        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(iBuilder->CreateAdd(consumerPos, requiredSize), producerPos));
422    }
423
424    iBuilder->CreateCondBr(waitCondTest, doSegmentBlock, endSignalCheckBlock);
425   
426    iBuilder->SetInsertPoint(endSignalCheckBlock);
427   
428    LoadInst * endSignal = iBuilder->CreateAlignedLoad(endSignalPtrs[0], sizeof(size_t));
429    // iBuilder->CallPrintInt(name + ":endSignal", endSignal);
430    endSignal->setOrdering(AtomicOrdering::Acquire);
431    for (unsigned i = 1; i < endSignalPtrs.size(); i++){
432        LoadInst * endSignal_next = iBuilder->CreateAlignedLoad(endSignalPtrs[i], sizeof(size_t));
433        endSignal_next->setOrdering(AtomicOrdering::Acquire);
434        iBuilder->CreateAnd(endSignal, endSignal_next);
435    }
436       
437    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(endSignal, ConstantInt::get(iBuilder->getInt8Ty(), 1)), endBlock, inputCheckBlock);
438   
439    iBuilder->SetInsertPoint(doSegmentBlock);
440 
441    createDoSegmentCall(self, segBlocks);
442
443    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
444        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), segSize);
445        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
446    }
447   
448    Value * produced = getProducedItemCount(self);
449    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
450        iBuilder->CreateAlignedStore(produced, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
451    }
452   
453    Value * earlyEndSignal = getTerminationSignal(self);
454    if (earlyEndSignal != ConstantInt::getNullValue(iBuilder->getInt1Ty())) {
455        BasicBlock * earlyEndBlock = BasicBlock::Create(iBuilder->getContext(), "earlyEndSignal", threadFunc, 0);
456        iBuilder->CreateCondBr(earlyEndSignal, earlyEndBlock, outputCheckBlock);
457
458        iBuilder->SetInsertPoint(earlyEndBlock);
459        for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
460            Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
461            mStreamSetOutputBuffers[i]->setEndOfInput(basePtr);
462        }       
463    }
464    iBuilder->CreateBr(outputCheckBlock);
465     
466    iBuilder->SetInsertPoint(endBlock);
467    LoadInst * producerPos = iBuilder->CreateLoad(inbufProducerPtrs[0]);
468    LoadInst * consumerPos = iBuilder->CreateLoad(inbufConsumerPtrs[0]);
469    Value * remainingBytes = iBuilder->CreateSub(producerPos, consumerPos);
470    Value * blockSize = ConstantInt::get(size_ty, iBuilder->getBitBlockWidth());
471    Value * blocks = iBuilder->CreateUDiv(remainingBytes, blockSize);
472    Value * finalBlockRemainingBytes = iBuilder->CreateURem(remainingBytes, blockSize);
473
474    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(blocks, ConstantInt::get(size_ty, 0)), doFinalBlock, doFinalSegBlock);
475
476    iBuilder->SetInsertPoint(doFinalSegBlock);
477
478    createDoSegmentCall(self, blocks);
479
480    iBuilder->CreateBr(doFinalBlock);
481
482    iBuilder->SetInsertPoint(doFinalBlock);
483
484    createFinalBlockCall(self, finalBlockRemainingBytes);
485
486    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
487        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), remainingBytes);
488        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
489    }
490    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
491        iBuilder->CreateAlignedStore(producerPos, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
492    }
493
494    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
495        Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
496        mStreamSetOutputBuffers[i]->setEndOfInput(basePtr);
497    }
498
499    Value * nullVal = Constant::getNullValue(voidPtrTy);
500    Function * pthreadExitFunc = m->getFunction("pthread_exit");
501    CallInst * exitThread = iBuilder->CreateCall(pthreadExitFunc, {nullVal}); 
502    exitThread->setDoesNotReturn();
503    iBuilder->CreateRetVoid();
504
505    return threadFunc;
506
507}
Note: See TracBrowser for help on using the repository browser.