source: icGREP/icgrep-devel/icgrep/kernels/streamset.cpp @ 5805

Last change on this file since 5805 was 5793, checked in by nmedfort, 19 months ago

Bug fix for pipeline: it was terminating too early when there was insufficient output space to process all of the input for a kernel.

File size: 46.6 KB
RevLine 
[5044]1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
[5260]6#include "streamset.h"
[5436]7#include <llvm/IR/Module.h>
[5307]8#include <llvm/Support/raw_ostream.h>
[5408]9#include <kernels/kernel.h>
[5436]10#include <kernels/kernel_builder.h>
[5425]11#include <toolchain/toolchain.h>
[5542]12#include <llvm/Support/Debug.h>
13#include <llvm/Support/Format.h>
[5307]14
[5260]15namespace llvm { class Constant; }
16namespace llvm { class Function; }
[5191]17
[5100]18using namespace parabix;
[5260]19using namespace llvm;
20using namespace IDISA;
[5044]21
[5755]22inline static bool is_power_2(const uint64_t n) {
23    return ((n & (n - 1)) == 0) && n;
24}
[5506]25
26Type * StreamSetBuffer::getStreamSetBlockType() const { return mType;}
27
[5436]28ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
[5320]29
[5436]30StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
[5320]31
[5755]32void StreamSetBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5706]33    assert (mBufferBlocks > 0);
[5429]34    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
35        Type * const ty = getType();
[5597]36        if (mAddressSpace == 0) {
37            Constant * size = ConstantExpr::getSizeOf(ty);
38            size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks));
[5755]39            mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
[5597]40        } else {
[5755]41            mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(ty, b->getSize(mBufferBlocks));
[5597]42        }
[5755]43        b->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, b->getCacheAlignment());
[5429]44    } else {
45        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
46    }
[5044]47}
48
[5755]49void StreamSetBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
[5597]50    if (mAddressSpace == 0) {
[5755]51        b->CreateFree(mStreamSetBufferPtr);
[5597]52    }
53}
54
[5755]55inline bool StreamSetBuffer::isCapacityGuaranteed(const Value * const index, const size_t capacity) const {
56    return isa<ConstantInt>(index) ? cast<ConstantInt>(index)->getLimitedValue() < capacity : false;
57}
58
59Value * StreamSetBuffer::modBufferSize(IDISA::IDISA_Builder * const b, Value * const offset) const {
60    assert (offset->getType()->isIntegerTy());
61    if (mBufferBlocks == 0 || isCapacityGuaranteed(offset, mBufferBlocks)) {
62        return offset;
63    } else if (mBufferBlocks == 1) {
64        return ConstantInt::getNullValue(offset->getType());
65    } else if (is_power_2(mBufferBlocks)) {
66        return b->CreateAnd(offset, ConstantInt::get(offset->getType(), mBufferBlocks - 1));
67    } else {
68        return b->CreateURem(offset, ConstantInt::get(offset->getType(), mBufferBlocks));
69    }
70}
71
72Value * StreamSetBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, const bool /* readOnly */) const {
[5721]73    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
[5755]74        Value * const count = getStreamSetCount(b, handle);
75        Value * const index = b->CreateZExtOrTrunc(streamIndex, count->getType());
76        Value * const cond = b->CreateICmpULT(index, count);
77        b->CreateAssert(cond, "out-of-bounds stream access");
[5486]78    }
[5755]79    return b->CreateGEP(addr, {modBufferSize(b, blockIndex), streamIndex});
[5260]80}
81
[5755]82Value * StreamSetBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool /* readOnly */) const {
[5721]83    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
[5755]84        Value * const count = getStreamSetCount(b, handle);
85        Value * const index = b->CreateZExtOrTrunc(streamIndex, count->getType());
86        Value * const cond = b->CreateICmpULT(index, count);
87        b->CreateAssert(cond, "out-of-bounds stream access");
[5486]88    }
[5755]89    return b->CreateGEP(addr, {modBufferSize(b, blockIndex), streamIndex, packIndex});
[5260]90}
91
[5755]92void StreamSetBuffer::setBaseAddress(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* addr */) const {
[5398]93    report_fatal_error("setBaseAddress is not supported by this buffer type");
94}
95
[5755]96Value * StreamSetBuffer::getBufferedSize(IDISA::IDISA_Builder * const b, Value * /* handle */) const {
97    return b->getSize(mBufferBlocks * b->getBitBlockWidth());
[5398]98}
99
[5755]100void StreamSetBuffer::setBufferedSize(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* size */) const {
[5398]101    report_fatal_error("setBufferedSize is not supported by this buffer type");
102}
103
[5757]104Value * StreamSetBuffer::getCapacity(IDISA::IDISA_Builder * const b, Value * const /* handle */) const {
105    return b->getSize(mBufferBlocks * b->getBitBlockWidth());
[5501]106}
107
[5755]108void StreamSetBuffer::setCapacity(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* c */) const {
[5501]109    report_fatal_error("setCapacity is not supported by this buffer type");
110}
111
[5755]112Value * StreamSetBuffer::getStreamSetCount(IDISA::IDISA_Builder * const b, Value *) const {
[5498]113    size_t count = 1;
[5329]114    if (isa<ArrayType>(mBaseType)) {
115        count = mBaseType->getArrayNumElements();
116    }
[5755]117    return b->getSize(count);
[5329]118}
119
[5307]120/**
121 * @brief getRawItemPointer
122 *
123 * get a raw pointer the iN field at position absoluteItemPosition of the stream number streamIndex of the stream set.
124 * In the case of a stream whose fields are less than one byte (8 bits) in size, the pointer is to the containing byte.
125 * The type of the pointer is i8* for fields of 8 bits or less, otherwise iN* for N-bit fields.
126 */
[5755]127Value * StreamSetBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
128    Value * ptr = getBaseAddress(b, handle);
[5446]129    Value * relativePosition = absolutePosition;
[5755]130    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
131    const auto bw = elemTy->getPrimitiveSizeInBits();
132    assert (is_power_2(bw));
[5445]133    if (bw < 8) {
[5755]134        Constant * const fw = ConstantInt::get(relativePosition->getType(), 8 / bw);
135        if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
136            b->CreateAssertZero(b->CreateURem(absolutePosition, fw), "absolutePosition must be byte aligned");
137        }
138        relativePosition = b->CreateUDiv(relativePosition, fw);
139        ptr = b->CreatePointerCast(ptr, b->getInt8PtrTy());
[5446]140    } else {
[5755]141        ptr = b->CreatePointerCast(ptr, elemTy->getPointerTo());
[5445]142    }
[5755]143    return b->CreateGEP(ptr, relativePosition);
[5260]144}
145
[5782]146Value * StreamSetBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const /* handle */, Value * fromPosition, Value * availItems, bool reverse) const {
[5706]147    Constant * bufSize = ConstantInt::get(fromPosition->getType(), mBufferBlocks * b->getStride());
[5650]148    Value * itemsFromBase = b->CreateURem(fromPosition, bufSize);
[5639]149    if (reverse) {
[5650]150        Value * bufAvail = b->CreateSelect(b->CreateICmpEQ(itemsFromBase, b->getSize(0)), bufSize, itemsFromBase);
151        return b->CreateSelect(b->CreateICmpULT(bufAvail, availItems), bufAvail, availItems);
[5706]152    } else {
[5650]153        Value * linearSpace = b->CreateSub(bufSize, itemsFromBase, "linearSpace");
154        return b->CreateSelect(b->CreateICmpULT(availItems, linearSpace), availItems, linearSpace);
155    }
[5301]156}
157
[5782]158Value * StreamSetBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const /* handle */, Value * fromPosition, Value * consumed, bool reverse) const {
159    Constant * const bufferSize = ConstantInt::get(fromPosition->getType(), mBufferBlocks * b->getStride());
160    fromPosition = b->CreateURem(fromPosition, bufferSize);
[5618]161    if (reverse) {
[5782]162        return b->CreateSelect(b->CreateICmpEQ(fromPosition, b->getSize(0)), bufferSize, fromPosition);
[5618]163    }
[5782]164    consumed = b->CreateURem(consumed, bufferSize);
[5793]165    Constant * capacity = bufferSize;
166    if (mOverflowBlocks) {
167        capacity = ConstantInt::get(fromPosition->getType(), (mBufferBlocks + mOverflowBlocks) * b->getStride());
168    }
169    Value * const limit = b->CreateSelect(b->CreateICmpULE(consumed, fromPosition), capacity, consumed);
[5782]170    return b->CreateNUWSub(limit, fromPosition);
[5355]171}
[5301]172
[5755]173Value * StreamSetBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
174    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
175        b->CreateAssert(handle, "handle cannot be null");
176    }
177    return handle;
[5377]178}
179
[5755]180
181Value * StreamSetBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
182    return b->CreateGEP(getBaseAddress(b, handle), blockIndex);
183}
184
185void StreamSetBuffer::createBlockCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * blocksToCopy) const {
186    Type * i8ptr = b->getInt8PtrTy();
187    unsigned alignment = b->getBitBlockWidth() / 8;
[5498]188    size_t numStreams = 1;
[5493]189    if (isa<ArrayType>(mBaseType)) {
190        numStreams = mBaseType->getArrayNumElements();
191    }
192    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
[5755]193    Value * blockCopyBytes = b->CreateMul(blocksToCopy, b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8));
194    b->CreateMemMove(b->CreateBitCast(targetBlockPtr, i8ptr), b->CreateBitCast(sourceBlockPtr, i8ptr), blockCopyBytes, alignment);
[5479]195}
196
[5755]197void StreamSetBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy, const unsigned alignment) const {
198    Constant * const blockSize = ConstantInt::get(itemsToCopy->getType(), b->getBitBlockWidth());
[5498]199    size_t numStreams = 1;
[5493]200    if (isa<ArrayType>(mBaseType)) {
201        numStreams = mBaseType->getArrayNumElements();
202    }
203    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
[5448]204    if (numStreams == 1) {
[5755]205        Value * copyBits = b->CreateMul(itemsToCopy, b->getSize(fieldWidth));
206        Value * copyBytes = b->CreateLShr(b->CreateAdd(copyBits, b->getSize(7)), b->getSize(3));
207        b->CreateMemCpy(targetBlockPtr, sourceBlockPtr, copyBytes, alignment);
[5486]208    } else {
[5755]209        Value * blocksToCopy = b->CreateUDiv(itemsToCopy, blockSize);
210        Value * partialItems = b->CreateURem(itemsToCopy, blockSize);
211        Value * partialBlockTargetPtr = b->CreateGEP(targetBlockPtr, blocksToCopy);
212        Value * partialBlockSourcePtr = b->CreateGEP(sourceBlockPtr, blocksToCopy);
213        Value * blockCopyBytes = b->CreateMul(blocksToCopy, b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8));
214        b->CreateMemCpy(targetBlockPtr, sourceBlockPtr, blockCopyBytes, alignment);
215        Value * partialCopyBitsPerStream = b->CreateMul(partialItems, b->getSize(fieldWidth));
216        Value * partialCopyBytesPerStream = b->CreateLShr(b->CreateAdd(partialCopyBitsPerStream, b->getSize(7)), b->getSize(3));
[5706]217        for (unsigned i = 0; i < numStreams; i++) {
[5755]218            Value * strmTargetPtr = b->CreateGEP(partialBlockTargetPtr, {b->getInt32(0), b->getInt32(i)});
219            Value * strmSourcePtr = b->CreateGEP(partialBlockSourcePtr, {b->getInt32(0), b->getInt32(i)});
220            b->CreateMemCpy(strmTargetPtr, strmSourcePtr, partialCopyBytesPerStream, alignment);
[5486]221        }
[5448]222    }
[5432]223}
224
[5398]225// Source File Buffer
[5506]226
227Type * SourceBuffer::getStreamSetBlockType() const {
228    return cast<PointerType>(mType->getStructElementType(int(SourceBuffer::Field::BaseAddress)))->getElementType();
229}
230
[5755]231Value * SourceBuffer::getBufferedSize(IDISA::IDISA_Builder * const b, Value * const handle) const {
232    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::BufferedSize))});
233    return b->CreateLoad(ptr);
[5398]234}
235
[5755]236void SourceBuffer::setBufferedSize(IDISA::IDISA_Builder * const b, Value * const handle, Value * size) const {
237    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::BufferedSize))});
238    b->CreateStore(size, ptr);
[5398]239}
240
[5755]241Value * SourceBuffer::getCapacity(IDISA::IDISA_Builder * const b, Value * const handle) const {
242    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::Capacity))});
243    return b->CreateLoad(ptr);
[5501]244}
245
[5755]246void SourceBuffer::setCapacity(IDISA::IDISA_Builder * const b, Value * const handle, Value * c) const {
247    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::Capacity))});
248    b->CreateStore(c, ptr);
[5501]249}
250
[5755]251void SourceBuffer::setBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr) const {
252    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
253        b->CreateAssert(handle, "handle cannot be null");
254    }
255    Value * const ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::BaseAddress))});
256    Type * const ptrTy = ptr->getType()->getPointerElementType();
257    if (LLVM_LIKELY(isa<PointerType>(addr->getType()))) {
258        const auto ptrSpace = cast<PointerType>(ptr->getType())->getAddressSpace();
259        const auto addrSpace = cast<PointerType>(ptrTy)->getAddressSpace();
260        if (LLVM_UNLIKELY(addrSpace != ptrSpace)) {
261            report_fatal_error("SourceBuffer: base address was declared with address space "
262                                     + std::to_string(ptrSpace)
263                                     + " but given a pointer in address space "
264                                     + std::to_string(addrSpace));
265        }
266    } else {
267        report_fatal_error("SourceBuffer: base address is not a pointer type");
268    }
269    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
270        b->CreateAssert(ptr, "SourceBuffer: base address cannot be zero");
271        DataLayout DL(b->getModule());
272        IntegerType * const intPtrTy = b->getIntPtrTy(DL, cast<PointerType>(ptrTy)->getAddressSpace());
273        Value * const notAligned = b->CreateURem(b->CreatePtrToInt(ptr, intPtrTy), ConstantInt::get(intPtrTy, b->getBitBlockWidth() / 8));
274        b->CreateAssertZero(notAligned, "SourceBuffer: base address is not aligned with the bit block width");
275    }
276    b->CreateStore(b->CreatePointerCast(addr, ptrTy), ptr);
[5398]277}
278
[5755]279Value * SourceBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
280    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
281        b->CreateAssert(handle, "handle cannot be null");
282    }
283    Value * const ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(SourceBuffer::Field::BaseAddress))});
284    return b->CreateLoad(ptr);
[5398]285}
286
[5755]287Value * SourceBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
[5618]288    if (reverse) report_fatal_error("SourceBuffer cannot be accessed in reverse");
[5755]289    Value * maxAvail = b->CreateSub(getBufferedSize(b, handle), fromPosition);
290    return b->CreateSelect(b->CreateICmpULT(availItems, maxAvail), availItems, maxAvail);
[5398]291}
292
[5782]293Value * SourceBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
[5650]294    report_fatal_error("SourceBuffers cannot be written");
[5503]295}
[5501]296
[5755]297void SourceBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5597]298    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
299        Type * const ty = getType();
[5755]300        mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(ty, b->getSize(mBufferBlocks));
301        b->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, b->getCacheAlignment());
[5597]302    } else {
303        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
304    }
305}
[5503]306
[5755]307void SourceBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
[5597]308
309}
310
[5429]311// External File Buffer
[5436]312void ExternalBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> &) {
[5429]313    report_fatal_error("External buffers cannot be allocated.");
[5377]314}
315
[5597]316void ExternalBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> &) const {
317
318}
319
[5706]320Value * ExternalBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const, Value *, Value *, Value * availItems, const bool reverse) const {
321    // All available items can be accessed.
322    return reverse ? ConstantInt::getAllOnesValue(availItems->getType()) : availItems;
[5377]323}
324
[5782]325Value * ExternalBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const, Value *, Value * fromPosition, Value *consumed, const bool reverse) const {
[5706]326    // Trust that the buffer is large enough to write any amount
327    return reverse ? fromPosition : ConstantInt::getAllOnesValue(fromPosition->getType());
328}
329
[5757]330Value * ExternalBuffer::getCapacity(IDISA::IDISA_Builder * const b, Value * const /* handle */) const {
331    return ConstantInt::getAllOnesValue(b->getSizeTy());
332}
333
334
[5260]335// Circular Buffer
[5755]336Value * CircularBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * const blockIndex) const {
337    return b->CreateGEP(getBaseAddress(b, handle), modBufferSize(b, blockIndex));
[5100]338}
339
[5755]340Value * CircularBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
341    Value * ptr = getBaseAddress(b, handle);
342    Value * relativePosition = b->CreateURem(absolutePosition, ConstantInt::get(absolutePosition->getType(), mBufferBlocks * b->getBitBlockWidth()));
343    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
344    const auto bw = elemTy->getPrimitiveSizeInBits();
345    assert (is_power_2(bw));
[5446]346    if (bw < 8) {
[5755]347        Constant * const fw = ConstantInt::get(relativePosition->getType(), 8 / bw);
348        relativePosition = b->CreateUDiv(relativePosition, fw);
349        ptr = b->CreatePointerCast(ptr, b->getInt8PtrTy());
[5446]350    } else {
[5755]351        ptr = b->CreatePointerCast(ptr, elemTy->getPointerTo());
[5446]352    }
[5755]353    return b->CreateGEP(ptr, relativePosition);
[5446]354}
355
[5301]356// CircularCopybackBuffer Buffer
[5755]357void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5597]358    Type * const ty = getType();
359    Constant * size = ConstantExpr::getSizeOf(ty);
360    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
[5755]361    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
[5301]362}
363
[5434]364
[5355]365// SwizzledCopybackBuffer Buffer
[5755]366void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5597]367    Type * const ty = getType();
368    Constant * size = ConstantExpr::getSizeOf(ty);
369    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
[5755]370    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
[5355]371}
372
[5755]373void SwizzledCopybackBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy, const unsigned alignment) const {
374    Type * int8PtrTy = b->getInt8PtrTy();
375    DataLayout DL(b->getModule());
376    IntegerType * const intAddrTy = b->getIntPtrTy(DL);
[5454]377
[5755]378    Constant * blockSize = ConstantInt::get(itemsToCopy->getType(), b->getBitBlockWidth());
379    Function * f = b->GetInsertBlock()->getParent();
380    BasicBlock * wholeBlockCopy = BasicBlock::Create(b->getContext(), "wholeBlockCopy", f, 0);
381    BasicBlock * partialBlockCopy = BasicBlock::Create(b->getContext(), "partialBlockCopy", f, 0);
382    BasicBlock * copyDone = BasicBlock::Create(b->getContext(), "copyDone", f, 0);
[5454]383    const unsigned numStreams = getType()->getArrayNumElements();
[5755]384    const unsigned swizzleFactor = b->getBitBlockWidth()/mFieldWidth;
[5454]385    const auto elemTy = getType()->getArrayElementType();
386    const unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
[5755]387    Value * blocksToCopy = b->CreateUDiv(itemsToCopy, blockSize);
388    Value * partialItems = b->CreateURem(itemsToCopy, blockSize);
389    Value * partialBlockTargetPtr = b->CreateGEP(targetBlockPtr, blocksToCopy);
390    Value * partialBlockSourcePtr = b->CreateGEP(sourceBlockPtr, blocksToCopy);
391    b->CreateCondBr(b->CreateICmpUGT(blocksToCopy, b->getSize(0)), wholeBlockCopy, partialBlockCopy);
[5454]392
[5755]393    b->SetInsertPoint(wholeBlockCopy);
394    Value * copyLength = b->CreateSub(b->CreatePtrToInt(partialBlockTargetPtr, intAddrTy), b->CreatePtrToInt(targetBlockPtr, intAddrTy));
395    b->CreateMemCpy(b->CreatePointerCast(targetBlockPtr, int8PtrTy), b->CreatePointerCast(sourceBlockPtr, int8PtrTy), copyLength, alignment);
396    b->CreateCondBr(b->CreateICmpUGT(partialItems, b->getSize(0)), partialBlockCopy, copyDone);
397
398    b->SetInsertPoint(partialBlockCopy);
399    Value * copyBits = b->CreateMul(itemsToCopy, b->getSize(fieldWidth * swizzleFactor));
400    Value * copyBytes = b->CreateLShr(b->CreateAdd(copyBits, b->getSize(7)), b->getSize(3));
[5355]401    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
[5755]402        Value * strmTargetPtr = b->CreateGEP(partialBlockTargetPtr, {b->getInt32(0), b->getInt32(strm)});
403        Value * strmSourcePtr = b->CreateGEP(partialBlockSourcePtr, {b->getInt32(0), b->getInt32(strm)});
404        b->CreateMemCpy(b->CreatePointerCast(strmTargetPtr, int8PtrTy), b->CreatePointerCast(strmSourcePtr, int8PtrTy), copyBytes, alignment);
[5355]405    }
[5755]406    b->CreateBr(copyDone);
[5454]407
[5755]408    b->SetInsertPoint(copyDone);
[5355]409}
410
[5755]411Value * SwizzledCopybackBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
412    return b->CreateGEP(getBaseAddress(b, handle), modBufferSize(b, blockIndex));
[5355]413}
414
[5260]415// Expandable Buffer
416
[5755]417void ExpandableBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
418    mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(getType());
419    Value * const capacityPtr = b->CreateGEP(mStreamSetBufferPtr, {b->getInt32(0), b->getInt32(0)});
420    b->CreateStore(b->getSize(mInitialCapacity), capacityPtr);
[5320]421    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
[5755]422    Constant * const bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), b->getSizeTy(), false);
423    Constant * const size = ConstantExpr::getMul(b->getSize(mBufferBlocks * mInitialCapacity), bufferWidth);
424    const auto alignment = std::max(b->getCacheAlignment(), b->getBitBlockWidth() / 8);
425    Value * const ptr = b->CreateAlignedMalloc(size, alignment);
426    b->CreateMemZero(ptr, size, bufferType->getPrimitiveSizeInBits() / 8);
427    Value * const streamSetPtr = b->CreateGEP(mStreamSetBufferPtr, {b->getInt32(0), b->getInt32(1)});
428    b->CreateStore(b->CreatePointerCast(ptr, bufferType->getPointerTo()), streamSetPtr);
[5260]429}
430
[5755]431std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const b, Value * const handle, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
[5340]432
[5320]433    // ENTRY
[5755]434    Value * const capacityPtr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(0)});
435    Value * const capacity = b->CreateLoad(capacityPtr);
436    Value * const streamSetPtr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(1)});
437    Value * const streamSet = b->CreateLoad(streamSetPtr);
438    blockIndex = modBufferSize(b, blockIndex);
[5311]439
[5353]440    assert (streamIndex->getType() == capacity->getType());
[5755]441    Value * const cond = b->CreateICmpULT(streamIndex, capacity);
[5353]442
[5320]443    // Are we guaranteed that we can access this stream?
[5353]444    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
[5755]445        if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
446            b->CreateAssert(cond, "out-of-bounds stream access");
447        }
448        Value * offset = b->CreateAdd(b->CreateMul(blockIndex, capacity), streamIndex);
[5353]449        return {streamSet, offset};
[5320]450    }
[5260]451
[5755]452    BasicBlock * const entry = b->GetInsertBlock();
453    BasicBlock * const expand = BasicBlock::Create(b->getContext(), "expand", entry->getParent());
454    BasicBlock * const resume = BasicBlock::Create(b->getContext(), "resume", entry->getParent());
[5311]455
[5755]456    b->CreateLikelyCondBr(cond, resume, expand);
[5353]457
[5320]458    // EXPAND
[5755]459    b->SetInsertPoint(expand);
[5353]460
461    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
462    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
463
[5755]464    Value * newCapacity = b->CreateAdd(streamIndex, b->getSize(1));
465    newCapacity = b->CreateCeilLog2(newCapacity);
466    newCapacity = b->CreateShl(b->getSize(1), newCapacity, "newCapacity");
[5361]467
[5353]468    std::string tmp;
469    raw_string_ostream out(tmp);
470    out << "__expand";
471    elementType->print(out);
472    std::string name = out.str();
473
[5755]474    Module * const m = b->getModule();
[5353]475    Function * expandFunction = m->getFunction(name);
476
477    if (expandFunction == nullptr) {
478
[5755]479        const auto ip = b->saveIP();
[5353]480
[5755]481        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), b->getSizeTy(), b->getSizeTy()}, false);
[5353]482        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
483
484        auto args = expandFunction->arg_begin();
485        Value * streamSet = &*args++;
486        Value * capacity = &*args++;
487        Value * newCapacity = &*args;
488
[5755]489        BasicBlock * entry = BasicBlock::Create(b->getContext(), "entry", expandFunction);
490        b->SetInsertPoint(entry);
[5353]491
[5755]492        Value * size = b->CreateMul(newCapacity, b->getSize(mBufferBlocks));
493        const auto memAlign = std::max(b->getCacheAlignment(), b->getBitBlockWidth() / 8);
[5486]494
[5755]495        Value * newStreamSet = b->CreatePointerCast(b->CreateAlignedMalloc(b->CreateMul(size, vectorWidth), memAlign), elementType->getPointerTo());
496        Value * const diffCapacity = b->CreateMul(b->CreateSub(newCapacity, capacity), vectorWidth);
[5353]497
498        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
499        for (unsigned i = 0; i < mBufferBlocks; ++i) {
[5755]500            ConstantInt * const offset = b->getSize(i);
501            Value * srcOffset = b->CreateMul(capacity, offset);
502            Value * srcPtr = b->CreateGEP(streamSet, srcOffset);
503            Value * destOffset = b->CreateMul(newCapacity, offset);
504            Value * destPtr = b->CreateGEP(newStreamSet, destOffset);
505            b->CreateMemCpy(destPtr, srcPtr, b->CreateMul(capacity, vectorWidth), alignment);
506            Value * destZeroOffset = b->CreateAdd(destOffset, capacity);
507            Value * destZeroPtr = b->CreateGEP(newStreamSet, destZeroOffset);
508            b->CreateMemZero(destZeroPtr, diffCapacity, alignment);
[5353]509        }
510
[5755]511        b->CreateFree(streamSet);
[5353]512
[5755]513        b->CreateRet(newStreamSet);
[5353]514
[5755]515        b->restoreIP(ip);
[5320]516    }
[5311]517
[5755]518    Value * newStreamSet = b->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
519    b->CreateStore(newStreamSet, streamSetPtr);
520    b->CreateStore(newCapacity, capacityPtr);
[5353]521
[5755]522    b->CreateBr(resume);
[5353]523
[5320]524    // RESUME
[5755]525    b->SetInsertPoint(resume);
[5320]526
[5755]527    PHINode * phiStreamSet = b->CreatePHI(streamSet->getType(), 2);
[5320]528    phiStreamSet->addIncoming(streamSet, entry);
529    phiStreamSet->addIncoming(newStreamSet, expand);
530
[5755]531    PHINode * phiCapacity = b->CreatePHI(capacity->getType(), 2);
[5320]532    phiCapacity->addIncoming(capacity, entry);
533    phiCapacity->addIncoming(newCapacity, expand);
534
[5755]535    Value * offset = b->CreateAdd(b->CreateMul(blockIndex, phiCapacity), streamIndex);
[5320]536
537    return {phiStreamSet, offset};
[5260]538}
539
[5755]540Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
[5706]541    report_fatal_error("temporarily not supported");
542//    Value * ptr, * offset;
[5755]543//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
544//    return b->CreateGEP(ptr, offset);
[5320]545}
546
[5755]547Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
[5706]548    report_fatal_error("temporarily not supported");
549//    Value * ptr, * offset;
[5755]550//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
551//    return b->CreateGEP(ptr, {offset, packIndex});
[5320]552}
553
[5755]554Value * ExpandableBuffer::getStreamSetCount(IDISA::IDISA_Builder * const b, Value * const handle) const {
555    return b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(0)}));
[5329]556}
557
[5755]558Value * ExpandableBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
559    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
560        b->CreateAssert(handle, "handle cannot be null");
561    }
562    Value * const baseAddr = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(1)}));
563    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
564        b->CreateAssert(handle, "base address cannot be 0");
565    }
[5446]566    return baseAddr;
[5377]567}
568
[5544]569void ExpandableBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
570    b->CreateFree(getBaseAddress(b.get(), mStreamSetBufferPtr));
[5386]571}
572
[5755]573Value * ExpandableBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value *, Value *) const {
[5706]574    report_fatal_error("Expandable buffers: getBlockAddress is not supported.");
[5316]575}
576
[5650]577Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const, Value *, Value *, Value *, bool) const {
[5320]578    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
[5311]579}
580
[5260]581
[5541]582Value * DynamicBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
[5755]583    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
584        b->CreateAssert(handle, "handle cannot be null");
585    }
[5541]586    Value * const p = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
587    Value * const addr = b->CreateLoad(p);
[5755]588    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
589        b->CreateAssert(addr, "base address cannot be 0");
590    }
[5541]591    return addr;
592}
593
[5755]594Value * DynamicBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
595    Value * const workingBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::WorkingBlocks))}));
596    assert (blockIndex->getType() == workingBlocks->getType());
597    return b->CreateGEP(getBaseAddress(b, handle), b->CreateURem(blockIndex, workingBlocks));
[5541]598}
599
[5755]600Value * DynamicBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
[5706]601    Constant * blockSize = ConstantInt::get(absolutePosition->getType(), b->getBitBlockWidth());
[5755]602    Value * const absBlock = b->CreateUDiv(absolutePosition, blockSize);
[5706]603    Value * blockPos = b->CreateURem(absolutePosition, blockSize);
604    Value * blockPtr = getBlockAddress(b, handle, absBlock);
[5755]605    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
606    const auto bw = elemTy->getPrimitiveSizeInBits();
607    assert (is_power_2(bw));
[5541]608    if (bw < 8) {
609        blockPos = b->CreateUDiv(blockPos, ConstantInt::get(blockPos->getType(), 8 / bw));
610        blockPtr = b->CreatePointerCast(blockPtr, b->getInt8PtrTy());
611    } else {
[5755]612        blockPtr = b->CreatePointerCast(blockPtr, elemTy->getPointerTo());
[5541]613    }
614    return b->CreateGEP(blockPtr, blockPos);
615}
616
[5597]617
[5755]618Value * DynamicBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
[5639]619    Value * const bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
[5706]620    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
[5639]621    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
[5706]622    assert (bufSize->getType() == fromPosition->getType());
[5650]623    Value * itemsFromBase = b->CreateURem(fromPosition, bufSize);
[5639]624    if (reverse) {
[5650]625        Value * bufAvail = b->CreateSelect(b->CreateICmpEQ(itemsFromBase, b->getSize(0)), bufSize, itemsFromBase);
626        return b->CreateSelect(b->CreateICmpULT(bufAvail, availItems), bufAvail, availItems);
[5706]627    } else {
[5650]628        Value * linearSpace = b->CreateSub(bufSize, itemsFromBase, "linearSpace");
629        return b->CreateSelect(b->CreateICmpULT(availItems, linearSpace), availItems, linearSpace);
630    }
[5541]631}
632
[5782]633Value * DynamicBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
[5650]634    Value * bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
[5706]635    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
[5650]636    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
[5706]637    assert (bufSize->getType() == fromPosition->getType());
[5650]638    Value * bufRem = b->CreateURem(fromPosition, bufSize);
[5618]639    if (reverse) {
[5650]640        return b->CreateSelect(b->CreateICmpEQ(bufRem, b->getSize(0)), bufSize, bufRem);
[5618]641    }
[5706]642    Constant * overflow = ConstantInt::get(bufBlocks->getType(), mOverflowBlocks);
643    bufSize = b->CreateMul(b->CreateAdd(bufBlocks, overflow), blockSize);
[5650]644    return b->CreateSub(bufSize, bufRem, "linearWritable");
[5541]645}
646
[5755]647Value * DynamicBuffer::getBufferedSize(IDISA::IDISA_Builder * const b, Value * const handle) const {
648    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))});
649    return b->CreateMul(b->CreateLoad(ptr), b->getSize(b->getBitBlockWidth()));
[5612]650}
651
[5541]652void DynamicBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
[5755]653    Value * const handle = b->CreateCacheAlignedAlloca(mBufferStructType);
[5541]654    size_t numStreams = 1;
655    if (isa<ArrayType>(mBaseType)) {
656        numStreams = mBaseType->getArrayNumElements();
657    }
658    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
659    Value * bufSize = b->getSize((mBufferBlocks + mOverflowBlocks) * b->getBitBlockWidth() * numStreams * fieldWidth/8);
[5543]660    bufSize = b->CreateRoundUp(bufSize, b->getSize(b->getCacheAlignment()));
[5597]661    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::BaseAddress))});
[5612]662    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
663    Value * bufPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(bufSize), bufPtrType);
[5618]664    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
665        b->CallPrintInt("allocated: ", bufPtr);
666        b->CallPrintInt("allocated capacity: ", bufSize);
667    }
[5541]668    b->CreateStore(bufPtr, bufBasePtrField);
[5612]669    b->CreateStore(ConstantPointerNull::getNullValue(bufPtrType), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))}));
[5597]670    b->CreateStore(bufSize, b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::AllocatedCapacity))}));
671    b->CreateStore(b->getSize(mBufferBlocks), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
672    b->CreateStore(b->getSize(-1), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::Length))}));
673    b->CreateStore(b->getSize(0), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::ProducedPosition))}));
674    b->CreateStore(b->getSize(0), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::ConsumedPosition))}));
[5541]675    mStreamSetBufferPtr = handle;
676}
677
[5544]678void DynamicBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
[5755]679    Value * const handle = mStreamSetBufferPtr;
[5541]680    /* Free the dynamically allocated buffer, but not the stack-allocated buffer struct. */
[5612]681    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
682    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
683    Value * priorBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))});
684    BasicBlock * freePrior = b->CreateBasicBlock("freePrior");
685    BasicBlock * freeCurrent = b->CreateBasicBlock("freeCurrent");
686    Value * priorBuf = b->CreateLoad(priorBasePtrField);
687    Value * priorBufIsNonNull = b->CreateICmpNE(priorBuf, ConstantPointerNull::get(cast<PointerType>(bufPtrType)));
688    b->CreateCondBr(priorBufIsNonNull, freePrior, freeCurrent);
689    b->SetInsertPoint(freePrior);
[5618]690    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
691        b->CallPrintInt("releasing: ", priorBuf);
692    }
[5612]693    b->CreateFree(priorBuf);
694    b->CreateBr(freeCurrent);
695    b->SetInsertPoint(freeCurrent);
696    b->CreateFree(b->CreateLoad(bufBasePtrField));
[5541]697}
698
[5612]699//
700//  Simple capacity doubling.  Use the circular buffer property: duplicating buffer data
701//  ensures that we have correct data.   TODO: consider optimizing based on actual
702//  consumer and producer positions.
703//
[5755]704void DynamicBuffer::doubleCapacity(IDISA::IDISA_Builder * const b, Value * const handle) {
[5612]705    size_t numStreams = 1;
706    if (isa<ArrayType>(mBaseType)) {
707        numStreams = mBaseType->getArrayNumElements();
708    }
709    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
710    Constant * blockBytes = b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8);
711    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
712    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
713    Value * priorBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))});
714    Value * workingBlocksField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::WorkingBlocks))});
715    Value * capacityField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::AllocatedCapacity))});
[5706]716
[5612]717    Value * oldBufPtr = b->CreateLoad(bufBasePtrField);
[5618]718    Value * currentWorkingBlocks = b->CreateLoad(workingBlocksField);
[5612]719    Value * workingBytes = b->CreateMul(currentWorkingBlocks, blockBytes);
720    Value * const curAllocated = b->CreateLoad(capacityField);
721    Value * neededCapacity = b->CreateAdd(workingBytes, workingBytes);
722    if (mOverflowBlocks > 0) {
723        Constant * overflowBytes = b->getSize(mOverflowBlocks * b->getBitBlockWidth() * numStreams * fieldWidth/8);
724        neededCapacity = b->CreateAdd(neededCapacity, overflowBytes);
725    }
726    neededCapacity = b->CreateRoundUp(neededCapacity, b->getSize(b->getCacheAlignment()));
727    BasicBlock * doubleEntry = b->GetInsertBlock();
728    BasicBlock * doRealloc = b->CreateBasicBlock("doRealloc");
729    BasicBlock * doCopy2 = b->CreateBasicBlock("doCopy2");
730    b->CreateCondBr(b->CreateICmpULT(curAllocated, neededCapacity), doRealloc, doCopy2);
731    b->SetInsertPoint(doRealloc);
732    // If there is a non-null priorBasePtr, free it.
733    Value * priorBuf = b->CreateLoad(priorBasePtrField);
734    Value * priorBufIsNonNull = b->CreateICmpNE(priorBuf, ConstantPointerNull::get(cast<PointerType>(bufPtrType)));
735    BasicBlock * deallocatePrior = b->CreateBasicBlock("deallocatePrior");
736    BasicBlock * allocateNew = b->CreateBasicBlock("allocateNew");
737    b->CreateCondBr(priorBufIsNonNull, deallocatePrior, allocateNew);
738    b->SetInsertPoint(deallocatePrior);
[5618]739    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
740        b->CallPrintInt("deallocating: ", priorBuf);
741    }
[5612]742    b->CreateFree(priorBuf);
743    b->CreateBr(allocateNew);
744    b->SetInsertPoint(allocateNew);
745    b->CreateStore(oldBufPtr, priorBasePtrField);
746    Value * newBufPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(neededCapacity), bufPtrType);
[5618]747    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
748        b->CallPrintInt("re-allocated: ", newBufPtr);
749        b->CallPrintInt("allocated capacity: ", neededCapacity);
750    }
[5612]751    b->CreateStore(newBufPtr, bufBasePtrField);
752    createBlockCopy(b, newBufPtr, oldBufPtr, currentWorkingBlocks);
753    b->CreateStore(neededCapacity, capacityField);
754    b->CreateBr(doCopy2);
755    b->SetInsertPoint(doCopy2);
756    PHINode * bufPtr = b->CreatePHI(oldBufPtr->getType(), 2);
757    bufPtr->addIncoming(oldBufPtr, doubleEntry);
[5615]758    bufPtr->addIncoming(newBufPtr, allocateNew);
[5612]759    createBlockCopy(b, b->CreateGEP(bufPtr, currentWorkingBlocks), bufPtr, currentWorkingBlocks);
[5618]760    currentWorkingBlocks = b->CreateAdd(currentWorkingBlocks, currentWorkingBlocks);
761    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
762        b->CallPrintInt("currentWorkingBlocks: ", currentWorkingBlocks);
763    }
764    b->CreateStore(currentWorkingBlocks, workingBlocksField);
[5612]765}
[5541]766
[5755]767inline StructType * getSourceBufferType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * const type, const unsigned MemoryAddressSpace) {
768    return StructType::get(b->getContext(), {resolveStreamSetType(b, type)->getPointerTo(MemoryAddressSpace), b->getSizeTy(), b->getSizeTy()});
769}
770
[5706]771SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
[5755]772: StreamSetBuffer(BufferKind::SourceBuffer, type, getSourceBufferType(b, type, MemoryAddressSpace), 0, 0, StructAddressSpace) {
[5706]773    mUniqueID = "B";
774    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
775        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
776    }
777}
778
[5755]779ExternalBuffer::ExternalBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, Value * addr, unsigned AddressSpace)
780: StreamSetBuffer(BufferKind::ExternalBuffer, type, resolveStreamSetType(b, type), 0, 0, AddressSpace) {
[5706]781    mUniqueID = "E";
782    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
783    mStreamSetBufferPtr = b->CreatePointerBitCastOrAddrSpaceCast(addr, getPointerType());
784}
785
786CircularBuffer::CircularBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
[5755]787: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, 0, AddressSpace) {
[5706]788    mUniqueID = "C" + std::to_string(bufferBlocks);
789    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
790}
791
[5755]792CircularBuffer::CircularBuffer(const BufferKind k, const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
793: StreamSetBuffer(k, type, resolveStreamSetType(b, type), bufferBlocks, overflowBlocks, AddressSpace) {
[5706]794
795}
796
797CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
[5755]798: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, overflowBlocks, AddressSpace) {
[5706]799    if (bufferBlocks < 2 * overflowBlocks) {
800        report_fatal_error("CircularCopybackBuffer: bufferBlocks < 2 * overflowBlocks");
801    }
802    mUniqueID = "CC" + std::to_string(bufferBlocks);
803    if (mOverflowBlocks != 1) mUniqueID += "_" + std::to_string(mOverflowBlocks);
804    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
805}
806
807ExpandableBuffer::ExpandableBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
[5755]808: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, 0, AddressSpace)
[5706]809, mInitialCapacity(type->getArrayNumElements()) {
810    mUniqueID = "XP" + std::to_string(bufferBlocks);
811    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
812}
813
814SwizzledCopybackBuffer::SwizzledCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned fieldwidth, unsigned AddressSpace)
[5755]815: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, overflowBlocks, AddressSpace), mFieldWidth(fieldwidth) {
[5706]816    mUniqueID = "SW" + std::to_string(fieldwidth) + ":" + std::to_string(bufferBlocks);
817    if (bufferBlocks < 2 * overflowBlocks) {
818        report_fatal_error("SwizzledCopybackBuffer: bufferBlocks < 2 * overflowBlocks");
819    }
[5755]820    if (overflowBlocks != 1) {
[5706]821        mUniqueID += "_" + std::to_string(mOverflowBlocks);
822    }
823    if (AddressSpace > 0) {
824        mUniqueID += "@" + std::to_string(AddressSpace);
825    }
826}
827
[5620]828inline StructType * getDynamicBufferStructType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * baseType, const unsigned addrSpace) {
829    IntegerType * sizeTy = b->getSizeTy();
830    PointerType * typePtr = baseType->getPointerTo(addrSpace);
[5733]831    return StructType::get(b->getContext(), {typePtr, typePtr, sizeTy, sizeTy, sizeTy, sizeTy, sizeTy});
[5620]832}
833
[5541]834DynamicBuffer::DynamicBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t initialCapacity, size_t overflow, unsigned swizzle, unsigned addrSpace)
[5755]835: StreamSetBuffer(BufferKind::DynamicBuffer, type, resolveStreamSetType(b, type), initialCapacity, overflow, addrSpace)
[5620]836, mBufferStructType(getDynamicBufferStructType(b, mType, addrSpace))
[5755]837, mSwizzleFactor(swizzle) {
[5641]838    if (initialCapacity * b->getBitBlockWidth() < 2 * overflow) {
839        report_fatal_error("DynamicBuffer: initialCapacity * b->getBitBlockWidth() < 2 * overflow");
840    }
[5541]841    mUniqueID = "DB";
842    if (swizzle != 1) {
843        mUniqueID += "s" + std::to_string(swizzle);
844    }
845        if (overflow != 0) {
846        mUniqueID += "o" + std::to_string(overflow);
847    }
848    if (addrSpace != 0) {
849        mUniqueID += "@" + std::to_string(addrSpace);
850    }
851}
852
853
[5755]854inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned OverflowBlocks, unsigned AddressSpace)
[5320]855: mBufferKind(k)
856, mType(resolvedType)
[5446]857, mBufferBlocks(BufferBlocks)
[5755]858, mOverflowBlocks(OverflowBlocks)
[5320]859, mAddressSpace(AddressSpace)
860, mStreamSetBufferPtr(nullptr)
[5408]861, mBaseType(baseType)
862, mProducer(nullptr) {
[5755]863    assert((k == BufferKind::SourceBuffer || k == BufferKind::ExternalBuffer) ^ (BufferBlocks > 0));
864    assert ("A zero length buffer cannot have overflow blocks!" && ((BufferBlocks > 0) || (OverflowBlocks == 0)));
[5320]865}
866
[5377]867StreamSetBuffer::~StreamSetBuffer() { }
868
[5320]869// Helper routines
[5436]870ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
[5320]871    unsigned numElements = 1;
872    if (LLVM_LIKELY(type->isArrayTy())) {
873        numElements = type->getArrayNumElements();
874        type = type->getArrayElementType();
875    }
876    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
877        type = type->getVectorElementType();
878        if (LLVM_LIKELY(type->isIntegerTy())) {
879            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
880            type = b->getBitBlockType();
881            if (fieldWidth != 1) {
882                type = ArrayType::get(type, fieldWidth);
[5307]883            }
[5320]884            return ArrayType::get(type, numElements);
[5307]885        }
886    }
887    std::string tmp;
888    raw_string_ostream out(tmp);
889    type->print(out);
890    out << " is an unvalid stream set buffer type.";
891    report_fatal_error(out.str());
892}
[5301]893
[5436]894StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
[5320]895    if (LLVM_LIKELY(type->isArrayTy())) {
896        type = type->getArrayElementType();
897    }
898    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
899        type = type->getVectorElementType();
900        if (LLVM_LIKELY(type->isIntegerTy())) {
901            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
902            type = b->getBitBlockType();
903            if (fieldWidth != 1) {
904                type = ArrayType::get(type, fieldWidth);
905            }
[5733]906            return StructType::get(b->getContext(), {b->getSizeTy(), type->getPointerTo()});
[5320]907        }
908    }
909    std::string tmp;
910    raw_string_ostream out(tmp);
911    type->print(out);
912    out << " is an unvalid stream set buffer type.";
913    report_fatal_error(out.str());
[5260]914}
Note: See TracBrowser for help on using the repository browser.