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

Last change on this file since 5816 was 5793, checked in by nmedfort, 21 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
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 "streamset.h"
7#include <llvm/IR/Module.h>
8#include <llvm/Support/raw_ostream.h>
9#include <kernels/kernel.h>
10#include <kernels/kernel_builder.h>
11#include <toolchain/toolchain.h>
12#include <llvm/Support/Debug.h>
13#include <llvm/Support/Format.h>
14
15namespace llvm { class Constant; }
16namespace llvm { class Function; }
17
18using namespace parabix;
19using namespace llvm;
20using namespace IDISA;
21
22inline static bool is_power_2(const uint64_t n) {
23    return ((n & (n - 1)) == 0) && n;
24}
25
26Type * StreamSetBuffer::getStreamSetBlockType() const { return mType;}
27
28ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
29
30StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
31
32void StreamSetBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
33    assert (mBufferBlocks > 0);
34    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
35        Type * const ty = getType();
36        if (mAddressSpace == 0) {
37            Constant * size = ConstantExpr::getSizeOf(ty);
38            size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks));
39            mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
40        } else {
41            mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(ty, b->getSize(mBufferBlocks));
42        }
43        b->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, b->getCacheAlignment());
44    } else {
45        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
46    }
47}
48
49void StreamSetBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
50    if (mAddressSpace == 0) {
51        b->CreateFree(mStreamSetBufferPtr);
52    }
53}
54
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 {
73    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
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");
78    }
79    return b->CreateGEP(addr, {modBufferSize(b, blockIndex), streamIndex});
80}
81
82Value * StreamSetBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool /* readOnly */) const {
83    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
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");
88    }
89    return b->CreateGEP(addr, {modBufferSize(b, blockIndex), streamIndex, packIndex});
90}
91
92void StreamSetBuffer::setBaseAddress(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* addr */) const {
93    report_fatal_error("setBaseAddress is not supported by this buffer type");
94}
95
96Value * StreamSetBuffer::getBufferedSize(IDISA::IDISA_Builder * const b, Value * /* handle */) const {
97    return b->getSize(mBufferBlocks * b->getBitBlockWidth());
98}
99
100void StreamSetBuffer::setBufferedSize(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* size */) const {
101    report_fatal_error("setBufferedSize is not supported by this buffer type");
102}
103
104Value * StreamSetBuffer::getCapacity(IDISA::IDISA_Builder * const b, Value * const /* handle */) const {
105    return b->getSize(mBufferBlocks * b->getBitBlockWidth());
106}
107
108void StreamSetBuffer::setCapacity(IDISA::IDISA_Builder * const /* b */, Value * /* handle */, Value * /* c */) const {
109    report_fatal_error("setCapacity is not supported by this buffer type");
110}
111
112Value * StreamSetBuffer::getStreamSetCount(IDISA::IDISA_Builder * const b, Value *) const {
113    size_t count = 1;
114    if (isa<ArrayType>(mBaseType)) {
115        count = mBaseType->getArrayNumElements();
116    }
117    return b->getSize(count);
118}
119
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 */
127Value * StreamSetBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
128    Value * ptr = getBaseAddress(b, handle);
129    Value * relativePosition = absolutePosition;
130    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
131    const auto bw = elemTy->getPrimitiveSizeInBits();
132    assert (is_power_2(bw));
133    if (bw < 8) {
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());
140    } else {
141        ptr = b->CreatePointerCast(ptr, elemTy->getPointerTo());
142    }
143    return b->CreateGEP(ptr, relativePosition);
144}
145
146Value * StreamSetBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const /* handle */, Value * fromPosition, Value * availItems, bool reverse) const {
147    Constant * bufSize = ConstantInt::get(fromPosition->getType(), mBufferBlocks * b->getStride());
148    Value * itemsFromBase = b->CreateURem(fromPosition, bufSize);
149    if (reverse) {
150        Value * bufAvail = b->CreateSelect(b->CreateICmpEQ(itemsFromBase, b->getSize(0)), bufSize, itemsFromBase);
151        return b->CreateSelect(b->CreateICmpULT(bufAvail, availItems), bufAvail, availItems);
152    } else {
153        Value * linearSpace = b->CreateSub(bufSize, itemsFromBase, "linearSpace");
154        return b->CreateSelect(b->CreateICmpULT(availItems, linearSpace), availItems, linearSpace);
155    }
156}
157
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);
161    if (reverse) {
162        return b->CreateSelect(b->CreateICmpEQ(fromPosition, b->getSize(0)), bufferSize, fromPosition);
163    }
164    consumed = b->CreateURem(consumed, bufferSize);
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);
170    return b->CreateNUWSub(limit, fromPosition);
171}
172
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;
178}
179
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;
188    size_t numStreams = 1;
189    if (isa<ArrayType>(mBaseType)) {
190        numStreams = mBaseType->getArrayNumElements();
191    }
192    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
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);
195}
196
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());
199    size_t numStreams = 1;
200    if (isa<ArrayType>(mBaseType)) {
201        numStreams = mBaseType->getArrayNumElements();
202    }
203    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
204    if (numStreams == 1) {
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);
208    } else {
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));
217        for (unsigned i = 0; i < numStreams; i++) {
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);
221        }
222    }
223}
224
225// Source File Buffer
226
227Type * SourceBuffer::getStreamSetBlockType() const {
228    return cast<PointerType>(mType->getStructElementType(int(SourceBuffer::Field::BaseAddress)))->getElementType();
229}
230
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);
234}
235
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);
239}
240
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);
244}
245
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);
249}
250
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);
277}
278
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);
285}
286
287Value * SourceBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
288    if (reverse) report_fatal_error("SourceBuffer cannot be accessed in reverse");
289    Value * maxAvail = b->CreateSub(getBufferedSize(b, handle), fromPosition);
290    return b->CreateSelect(b->CreateICmpULT(availItems, maxAvail), availItems, maxAvail);
291}
292
293Value * SourceBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
294    report_fatal_error("SourceBuffers cannot be written");
295}
296
297void SourceBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
298    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
299        Type * const ty = getType();
300        mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(ty, b->getSize(mBufferBlocks));
301        b->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, b->getCacheAlignment());
302    } else {
303        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
304    }
305}
306
307void SourceBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
308
309}
310
311// External File Buffer
312void ExternalBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> &) {
313    report_fatal_error("External buffers cannot be allocated.");
314}
315
316void ExternalBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> &) const {
317
318}
319
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;
323}
324
325Value * ExternalBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const, Value *, Value * fromPosition, Value *consumed, const bool reverse) const {
326    // Trust that the buffer is large enough to write any amount
327    return reverse ? fromPosition : ConstantInt::getAllOnesValue(fromPosition->getType());
328}
329
330Value * ExternalBuffer::getCapacity(IDISA::IDISA_Builder * const b, Value * const /* handle */) const {
331    return ConstantInt::getAllOnesValue(b->getSizeTy());
332}
333
334
335// Circular Buffer
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));
338}
339
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));
346    if (bw < 8) {
347        Constant * const fw = ConstantInt::get(relativePosition->getType(), 8 / bw);
348        relativePosition = b->CreateUDiv(relativePosition, fw);
349        ptr = b->CreatePointerCast(ptr, b->getInt8PtrTy());
350    } else {
351        ptr = b->CreatePointerCast(ptr, elemTy->getPointerTo());
352    }
353    return b->CreateGEP(ptr, relativePosition);
354}
355
356// CircularCopybackBuffer Buffer
357void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
358    Type * const ty = getType();
359    Constant * size = ConstantExpr::getSizeOf(ty);
360    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
361    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
362}
363
364
365// SwizzledCopybackBuffer Buffer
366void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
367    Type * const ty = getType();
368    Constant * size = ConstantExpr::getSizeOf(ty);
369    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
370    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
371}
372
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);
377
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);
383    const unsigned numStreams = getType()->getArrayNumElements();
384    const unsigned swizzleFactor = b->getBitBlockWidth()/mFieldWidth;
385    const auto elemTy = getType()->getArrayElementType();
386    const unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
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);
392
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));
401    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
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);
405    }
406    b->CreateBr(copyDone);
407
408    b->SetInsertPoint(copyDone);
409}
410
411Value * SwizzledCopybackBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
412    return b->CreateGEP(getBaseAddress(b, handle), modBufferSize(b, blockIndex));
413}
414
415// Expandable Buffer
416
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);
421    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
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);
429}
430
431std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const b, Value * const handle, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
432
433    // ENTRY
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);
439
440    assert (streamIndex->getType() == capacity->getType());
441    Value * const cond = b->CreateICmpULT(streamIndex, capacity);
442
443    // Are we guaranteed that we can access this stream?
444    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
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);
449        return {streamSet, offset};
450    }
451
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());
455
456    b->CreateLikelyCondBr(cond, resume, expand);
457
458    // EXPAND
459    b->SetInsertPoint(expand);
460
461    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
462    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
463
464    Value * newCapacity = b->CreateAdd(streamIndex, b->getSize(1));
465    newCapacity = b->CreateCeilLog2(newCapacity);
466    newCapacity = b->CreateShl(b->getSize(1), newCapacity, "newCapacity");
467
468    std::string tmp;
469    raw_string_ostream out(tmp);
470    out << "__expand";
471    elementType->print(out);
472    std::string name = out.str();
473
474    Module * const m = b->getModule();
475    Function * expandFunction = m->getFunction(name);
476
477    if (expandFunction == nullptr) {
478
479        const auto ip = b->saveIP();
480
481        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), b->getSizeTy(), b->getSizeTy()}, false);
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
489        BasicBlock * entry = BasicBlock::Create(b->getContext(), "entry", expandFunction);
490        b->SetInsertPoint(entry);
491
492        Value * size = b->CreateMul(newCapacity, b->getSize(mBufferBlocks));
493        const auto memAlign = std::max(b->getCacheAlignment(), b->getBitBlockWidth() / 8);
494
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);
497
498        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
499        for (unsigned i = 0; i < mBufferBlocks; ++i) {
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);
509        }
510
511        b->CreateFree(streamSet);
512
513        b->CreateRet(newStreamSet);
514
515        b->restoreIP(ip);
516    }
517
518    Value * newStreamSet = b->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
519    b->CreateStore(newStreamSet, streamSetPtr);
520    b->CreateStore(newCapacity, capacityPtr);
521
522    b->CreateBr(resume);
523
524    // RESUME
525    b->SetInsertPoint(resume);
526
527    PHINode * phiStreamSet = b->CreatePHI(streamSet->getType(), 2);
528    phiStreamSet->addIncoming(streamSet, entry);
529    phiStreamSet->addIncoming(newStreamSet, expand);
530
531    PHINode * phiCapacity = b->CreatePHI(capacity->getType(), 2);
532    phiCapacity->addIncoming(capacity, entry);
533    phiCapacity->addIncoming(newCapacity, expand);
534
535    Value * offset = b->CreateAdd(b->CreateMul(blockIndex, phiCapacity), streamIndex);
536
537    return {phiStreamSet, offset};
538}
539
540Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
541    report_fatal_error("temporarily not supported");
542//    Value * ptr, * offset;
543//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
544//    return b->CreateGEP(ptr, offset);
545}
546
547Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
548    report_fatal_error("temporarily not supported");
549//    Value * ptr, * offset;
550//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
551//    return b->CreateGEP(ptr, {offset, packIndex});
552}
553
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)}));
556}
557
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    }
566    return baseAddr;
567}
568
569void ExpandableBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
570    b->CreateFree(getBaseAddress(b.get(), mStreamSetBufferPtr));
571}
572
573Value * ExpandableBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value *, Value *) const {
574    report_fatal_error("Expandable buffers: getBlockAddress is not supported.");
575}
576
577Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const, Value *, Value *, Value *, bool) const {
578    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
579}
580
581
582Value * DynamicBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
583    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
584        b->CreateAssert(handle, "handle cannot be null");
585    }
586    Value * const p = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
587    Value * const addr = b->CreateLoad(p);
588    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
589        b->CreateAssert(addr, "base address cannot be 0");
590    }
591    return addr;
592}
593
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));
598}
599
600Value * DynamicBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
601    Constant * blockSize = ConstantInt::get(absolutePosition->getType(), b->getBitBlockWidth());
602    Value * const absBlock = b->CreateUDiv(absolutePosition, blockSize);
603    Value * blockPos = b->CreateURem(absolutePosition, blockSize);
604    Value * blockPtr = getBlockAddress(b, handle, absBlock);
605    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
606    const auto bw = elemTy->getPrimitiveSizeInBits();
607    assert (is_power_2(bw));
608    if (bw < 8) {
609        blockPos = b->CreateUDiv(blockPos, ConstantInt::get(blockPos->getType(), 8 / bw));
610        blockPtr = b->CreatePointerCast(blockPtr, b->getInt8PtrTy());
611    } else {
612        blockPtr = b->CreatePointerCast(blockPtr, elemTy->getPointerTo());
613    }
614    return b->CreateGEP(blockPtr, blockPos);
615}
616
617
618Value * DynamicBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
619    Value * const bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
620    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
621    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
622    assert (bufSize->getType() == fromPosition->getType());
623    Value * itemsFromBase = b->CreateURem(fromPosition, bufSize);
624    if (reverse) {
625        Value * bufAvail = b->CreateSelect(b->CreateICmpEQ(itemsFromBase, b->getSize(0)), bufSize, itemsFromBase);
626        return b->CreateSelect(b->CreateICmpULT(bufAvail, availItems), bufAvail, availItems);
627    } else {
628        Value * linearSpace = b->CreateSub(bufSize, itemsFromBase, "linearSpace");
629        return b->CreateSelect(b->CreateICmpULT(availItems, linearSpace), availItems, linearSpace);
630    }
631}
632
633Value * DynamicBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
634    Value * bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
635    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
636    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
637    assert (bufSize->getType() == fromPosition->getType());
638    Value * bufRem = b->CreateURem(fromPosition, bufSize);
639    if (reverse) {
640        return b->CreateSelect(b->CreateICmpEQ(bufRem, b->getSize(0)), bufSize, bufRem);
641    }
642    Constant * overflow = ConstantInt::get(bufBlocks->getType(), mOverflowBlocks);
643    bufSize = b->CreateMul(b->CreateAdd(bufBlocks, overflow), blockSize);
644    return b->CreateSub(bufSize, bufRem, "linearWritable");
645}
646
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()));
650}
651
652void DynamicBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
653    Value * const handle = b->CreateCacheAlignedAlloca(mBufferStructType);
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);
660    bufSize = b->CreateRoundUp(bufSize, b->getSize(b->getCacheAlignment()));
661    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::BaseAddress))});
662    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
663    Value * bufPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(bufSize), bufPtrType);
664    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
665        b->CallPrintInt("allocated: ", bufPtr);
666        b->CallPrintInt("allocated capacity: ", bufSize);
667    }
668    b->CreateStore(bufPtr, bufBasePtrField);
669    b->CreateStore(ConstantPointerNull::getNullValue(bufPtrType), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))}));
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))}));
675    mStreamSetBufferPtr = handle;
676}
677
678void DynamicBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
679    Value * const handle = mStreamSetBufferPtr;
680    /* Free the dynamically allocated buffer, but not the stack-allocated buffer struct. */
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);
690    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
691        b->CallPrintInt("releasing: ", priorBuf);
692    }
693    b->CreateFree(priorBuf);
694    b->CreateBr(freeCurrent);
695    b->SetInsertPoint(freeCurrent);
696    b->CreateFree(b->CreateLoad(bufBasePtrField));
697}
698
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//
704void DynamicBuffer::doubleCapacity(IDISA::IDISA_Builder * const b, Value * const handle) {
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))});
716
717    Value * oldBufPtr = b->CreateLoad(bufBasePtrField);
718    Value * currentWorkingBlocks = b->CreateLoad(workingBlocksField);
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);
739    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
740        b->CallPrintInt("deallocating: ", priorBuf);
741    }
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);
747    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
748        b->CallPrintInt("re-allocated: ", newBufPtr);
749        b->CallPrintInt("allocated capacity: ", neededCapacity);
750    }
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);
758    bufPtr->addIncoming(newBufPtr, allocateNew);
759    createBlockCopy(b, b->CreateGEP(bufPtr, currentWorkingBlocks), bufPtr, currentWorkingBlocks);
760    currentWorkingBlocks = b->CreateAdd(currentWorkingBlocks, currentWorkingBlocks);
761    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
762        b->CallPrintInt("currentWorkingBlocks: ", currentWorkingBlocks);
763    }
764    b->CreateStore(currentWorkingBlocks, workingBlocksField);
765}
766
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
771SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
772: StreamSetBuffer(BufferKind::SourceBuffer, type, getSourceBufferType(b, type, MemoryAddressSpace), 0, 0, StructAddressSpace) {
773    mUniqueID = "B";
774    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
775        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
776    }
777}
778
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) {
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)
787: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, 0, AddressSpace) {
788    mUniqueID = "C" + std::to_string(bufferBlocks);
789    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
790}
791
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) {
794
795}
796
797CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
798: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, overflowBlocks, AddressSpace) {
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)
808: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, 0, AddressSpace)
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)
815: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, overflowBlocks, AddressSpace), mFieldWidth(fieldwidth) {
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    }
820    if (overflowBlocks != 1) {
821        mUniqueID += "_" + std::to_string(mOverflowBlocks);
822    }
823    if (AddressSpace > 0) {
824        mUniqueID += "@" + std::to_string(AddressSpace);
825    }
826}
827
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);
831    return StructType::get(b->getContext(), {typePtr, typePtr, sizeTy, sizeTy, sizeTy, sizeTy, sizeTy});
832}
833
834DynamicBuffer::DynamicBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t initialCapacity, size_t overflow, unsigned swizzle, unsigned addrSpace)
835: StreamSetBuffer(BufferKind::DynamicBuffer, type, resolveStreamSetType(b, type), initialCapacity, overflow, addrSpace)
836, mBufferStructType(getDynamicBufferStructType(b, mType, addrSpace))
837, mSwizzleFactor(swizzle) {
838    if (initialCapacity * b->getBitBlockWidth() < 2 * overflow) {
839        report_fatal_error("DynamicBuffer: initialCapacity * b->getBitBlockWidth() < 2 * overflow");
840    }
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
854inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned OverflowBlocks, unsigned AddressSpace)
855: mBufferKind(k)
856, mType(resolvedType)
857, mBufferBlocks(BufferBlocks)
858, mOverflowBlocks(OverflowBlocks)
859, mAddressSpace(AddressSpace)
860, mStreamSetBufferPtr(nullptr)
861, mBaseType(baseType)
862, mProducer(nullptr) {
863    assert((k == BufferKind::SourceBuffer || k == BufferKind::ExternalBuffer) ^ (BufferBlocks > 0));
864    assert ("A zero length buffer cannot have overflow blocks!" && ((BufferBlocks > 0) || (OverflowBlocks == 0)));
865}
866
867StreamSetBuffer::~StreamSetBuffer() { }
868
869// Helper routines
870ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
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);
883            }
884            return ArrayType::get(type, numElements);
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}
893
894StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
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            }
906            return StructType::get(b->getContext(), {b->getSizeTy(), type->getPointerTo()});
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());
914}
Note: See TracBrowser for help on using the repository browser.