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

Last change on this file since 5787 was 5782, checked in by nmedfort, 18 months ago

Initial check-in of LookAhead? support; modified LineBreakKernel? to compute CR+LF using LookAhead?(1) + misc. fixes.

File size: 51.3 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    Value * const limit = b->CreateSelect(b->CreateICmpULE(consumed, fromPosition), bufferSize, consumed);
166    return b->CreateNUWSub(limit, fromPosition);
167}
168
169Value * StreamSetBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
170    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
171        b->CreateAssert(handle, "handle cannot be null");
172    }
173    return handle;
174}
175
176
177Value * StreamSetBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
178    return b->CreateGEP(getBaseAddress(b, handle), blockIndex);
179}
180
181void StreamSetBuffer::createBlockCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * blocksToCopy) const {
182    Type * i8ptr = b->getInt8PtrTy();
183    unsigned alignment = b->getBitBlockWidth() / 8;
184    size_t numStreams = 1;
185    if (isa<ArrayType>(mBaseType)) {
186        numStreams = mBaseType->getArrayNumElements();
187    }
188    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
189    Value * blockCopyBytes = b->CreateMul(blocksToCopy, b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8));
190    b->CreateMemMove(b->CreateBitCast(targetBlockPtr, i8ptr), b->CreateBitCast(sourceBlockPtr, i8ptr), blockCopyBytes, alignment);
191}
192
193void StreamSetBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy, const unsigned alignment) const {
194    Constant * const blockSize = ConstantInt::get(itemsToCopy->getType(), b->getBitBlockWidth());
195    size_t numStreams = 1;
196    if (isa<ArrayType>(mBaseType)) {
197        numStreams = mBaseType->getArrayNumElements();
198    }
199    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
200    if (numStreams == 1) {
201        Value * copyBits = b->CreateMul(itemsToCopy, b->getSize(fieldWidth));
202        Value * copyBytes = b->CreateLShr(b->CreateAdd(copyBits, b->getSize(7)), b->getSize(3));
203        b->CreateMemCpy(targetBlockPtr, sourceBlockPtr, copyBytes, alignment);
204    } else {
205        Value * blocksToCopy = b->CreateUDiv(itemsToCopy, blockSize);
206        Value * partialItems = b->CreateURem(itemsToCopy, blockSize);
207        Value * partialBlockTargetPtr = b->CreateGEP(targetBlockPtr, blocksToCopy);
208        Value * partialBlockSourcePtr = b->CreateGEP(sourceBlockPtr, blocksToCopy);
209        Value * blockCopyBytes = b->CreateMul(blocksToCopy, b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8));
210        b->CreateMemCpy(targetBlockPtr, sourceBlockPtr, blockCopyBytes, alignment);
211        Value * partialCopyBitsPerStream = b->CreateMul(partialItems, b->getSize(fieldWidth));
212        Value * partialCopyBytesPerStream = b->CreateLShr(b->CreateAdd(partialCopyBitsPerStream, b->getSize(7)), b->getSize(3));
213        for (unsigned i = 0; i < numStreams; i++) {
214            Value * strmTargetPtr = b->CreateGEP(partialBlockTargetPtr, {b->getInt32(0), b->getInt32(i)});
215            Value * strmSourcePtr = b->CreateGEP(partialBlockSourcePtr, {b->getInt32(0), b->getInt32(i)});
216            b->CreateMemCpy(strmTargetPtr, strmSourcePtr, partialCopyBytesPerStream, alignment);
217        }
218    }
219}
220
221void StreamSetBuffer::genCopyBackLogic(IDISA::IDISA_Builder * const b, Value * const handle, Value * priorProduced, Value * newProduced, const std::string Name) const {
222    report_fatal_error("Copy back not supported for this buffer type:" + Name);
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::getLinearlyCopyableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
341//    Constant * bufSize = ConstantInt::get(priorProduced->getType(), mBufferBlocks * b->getBitBlockWidth());
342//    Value * from = b->CreateURem(fromPosition, bufSize);
343//    Value * avail = b->CreateURem(availItems, bufSize);
344//    Value * wraparound = b->CreateICmpUGT(from, avail);
345
346
347    return nullptr;
348}
349
350Value * CircularBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
351    Value * ptr = getBaseAddress(b, handle);
352    Value * relativePosition = b->CreateURem(absolutePosition, ConstantInt::get(absolutePosition->getType(), mBufferBlocks * b->getBitBlockWidth()));
353    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
354    const auto bw = elemTy->getPrimitiveSizeInBits();
355    assert (is_power_2(bw));
356    if (bw < 8) {
357        Constant * const fw = ConstantInt::get(relativePosition->getType(), 8 / bw);
358        relativePosition = b->CreateUDiv(relativePosition, fw);
359        ptr = b->CreatePointerCast(ptr, b->getInt8PtrTy());
360    } else {
361        ptr = b->CreatePointerCast(ptr, elemTy->getPointerTo());
362    }
363    return b->CreateGEP(ptr, relativePosition);
364}
365
366// CircularCopybackBuffer Buffer
367void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
368    Type * const ty = getType();
369    Constant * size = ConstantExpr::getSizeOf(ty);
370    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
371    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
372}
373
374Value * CircularCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * consumed, bool reverse) const {
375    Value * writableProper = StreamSetBuffer::getLinearlyWritableItems(b, handle, fromPosition, consumed, reverse);
376    if (reverse) return writableProper;
377    return b->CreateAdd(writableProper, b->getSize(mOverflowBlocks * b->getBitBlockWidth()));
378}
379
380void CircularCopybackBuffer::genCopyBackLogic(IDISA::IDISA_Builder * const b, Value * const handle, Value * priorProduced, Value * newProduced, const std::string Name) const {
381    assert (priorProduced->getType() == newProduced->getType());
382    Constant * bufSize = ConstantInt::get(priorProduced->getType(), mBufferBlocks * b->getBitBlockWidth());
383    Value * priorBufPos = b->CreateURem(priorProduced, bufSize);
384    Value * newBufPos = b->CreateURem(newProduced, bufSize);
385    BasicBlock * copyBack = b->CreateBasicBlock(Name + "_circularCopyBack");
386    BasicBlock * done = b->CreateBasicBlock(Name + "_circularCopyBackDone");
387    Value * wraparound = b->CreateICmpUGT(priorBufPos, newBufPos);
388    b->CreateCondBr(wraparound, copyBack, done);
389
390    b->SetInsertPoint(copyBack);
391    Value * const baseAddress = getBaseAddress(b, handle);
392    Value * overflowAddress = b->CreateGEP(baseAddress, b->getInt32(mBufferBlocks));
393    // copyStream(b, baseAddress, b->getSize(0), overflowAddress, b->getSize(0), newBufPos);
394    createBlockAlignedCopy(b, baseAddress, overflowAddress, newBufPos);
395    b->CreateBr(done);
396
397    b->SetInsertPoint(done);
398}
399
400
401// SwizzledCopybackBuffer Buffer
402
403void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
404    Type * const ty = getType();
405    Constant * size = ConstantExpr::getSizeOf(ty);
406    size = ConstantExpr::getMul(size, ConstantInt::get(size->getType(), mBufferBlocks + mOverflowBlocks));
407    mStreamSetBufferPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(size), ty->getPointerTo());
408}
409
410void SwizzledCopybackBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const b, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy, const unsigned alignment) const {
411    Type * int8PtrTy = b->getInt8PtrTy();
412    DataLayout DL(b->getModule());
413    IntegerType * const intAddrTy = b->getIntPtrTy(DL);
414
415    Constant * blockSize = ConstantInt::get(itemsToCopy->getType(), b->getBitBlockWidth());
416    Function * f = b->GetInsertBlock()->getParent();
417    BasicBlock * wholeBlockCopy = BasicBlock::Create(b->getContext(), "wholeBlockCopy", f, 0);
418    BasicBlock * partialBlockCopy = BasicBlock::Create(b->getContext(), "partialBlockCopy", f, 0);
419    BasicBlock * copyDone = BasicBlock::Create(b->getContext(), "copyDone", f, 0);
420    const unsigned numStreams = getType()->getArrayNumElements();
421    const unsigned swizzleFactor = b->getBitBlockWidth()/mFieldWidth;
422    const auto elemTy = getType()->getArrayElementType();
423    const unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
424    Value * blocksToCopy = b->CreateUDiv(itemsToCopy, blockSize);
425    Value * partialItems = b->CreateURem(itemsToCopy, blockSize);
426    Value * partialBlockTargetPtr = b->CreateGEP(targetBlockPtr, blocksToCopy);
427    Value * partialBlockSourcePtr = b->CreateGEP(sourceBlockPtr, blocksToCopy);
428    b->CreateCondBr(b->CreateICmpUGT(blocksToCopy, b->getSize(0)), wholeBlockCopy, partialBlockCopy);
429
430    b->SetInsertPoint(wholeBlockCopy);
431    Value * copyLength = b->CreateSub(b->CreatePtrToInt(partialBlockTargetPtr, intAddrTy), b->CreatePtrToInt(targetBlockPtr, intAddrTy));
432    b->CreateMemCpy(b->CreatePointerCast(targetBlockPtr, int8PtrTy), b->CreatePointerCast(sourceBlockPtr, int8PtrTy), copyLength, alignment);
433    b->CreateCondBr(b->CreateICmpUGT(partialItems, b->getSize(0)), partialBlockCopy, copyDone);
434
435    b->SetInsertPoint(partialBlockCopy);
436    Value * copyBits = b->CreateMul(itemsToCopy, b->getSize(fieldWidth * swizzleFactor));
437    Value * copyBytes = b->CreateLShr(b->CreateAdd(copyBits, b->getSize(7)), b->getSize(3));
438    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
439        Value * strmTargetPtr = b->CreateGEP(partialBlockTargetPtr, {b->getInt32(0), b->getInt32(strm)});
440        Value * strmSourcePtr = b->CreateGEP(partialBlockSourcePtr, {b->getInt32(0), b->getInt32(strm)});
441        b->CreateMemCpy(b->CreatePointerCast(strmTargetPtr, int8PtrTy), b->CreatePointerCast(strmSourcePtr, int8PtrTy), copyBytes, alignment);
442    }
443    b->CreateBr(copyDone);
444
445    b->SetInsertPoint(copyDone);
446}
447
448Value * SwizzledCopybackBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
449    return b->CreateGEP(getBaseAddress(b, handle), modBufferSize(b, blockIndex));
450}
451
452Value * SwizzledCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
453    Value * writableProper = StreamSetBuffer::getLinearlyWritableItems(b, handle, fromPosition, consumed, reverse);
454    if (reverse) return writableProper;
455    return b->CreateAdd(writableProper, b->getSize(mOverflowBlocks * b->getBitBlockWidth()));
456}
457
458void SwizzledCopybackBuffer::genCopyBackLogic(IDISA::IDISA_Builder * const b, Value * const handle, Value * priorProduced, Value * newProduced, const std::string Name) const {
459    assert (priorProduced->getType() == newProduced->getType());
460    Constant * bufSize = ConstantInt::get(priorProduced->getType(), mBufferBlocks * b->getBitBlockWidth());
461    Value * priorBufPos = b->CreateURem(priorProduced, bufSize);
462    Value * newBufPos = b->CreateURem(newProduced, bufSize);
463    BasicBlock * copyBack = b->CreateBasicBlock(Name + "_swizzledCopyBack");
464    BasicBlock * done = b->CreateBasicBlock(Name + "_swizzledCopyBackDone");
465    Value * wraparound = b->CreateICmpUGT(priorBufPos, newBufPos);
466    b->CreateCondBr(wraparound, copyBack, done);
467    b->SetInsertPoint(copyBack);
468    Value * overFlowAreaPtr = b->CreateGEP(handle, b->getSize(mBufferBlocks));
469    createBlockAlignedCopy(b, handle, overFlowAreaPtr, newBufPos);
470    b->CreateBr(done);
471    b->SetInsertPoint(done);
472}
473
474// Expandable Buffer
475
476void ExpandableBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
477    mStreamSetBufferPtr = b->CreateCacheAlignedAlloca(getType());
478    Value * const capacityPtr = b->CreateGEP(mStreamSetBufferPtr, {b->getInt32(0), b->getInt32(0)});
479    b->CreateStore(b->getSize(mInitialCapacity), capacityPtr);
480    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
481    Constant * const bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), b->getSizeTy(), false);
482    Constant * const size = ConstantExpr::getMul(b->getSize(mBufferBlocks * mInitialCapacity), bufferWidth);
483    const auto alignment = std::max(b->getCacheAlignment(), b->getBitBlockWidth() / 8);
484    Value * const ptr = b->CreateAlignedMalloc(size, alignment);
485    b->CreateMemZero(ptr, size, bufferType->getPrimitiveSizeInBits() / 8);
486    Value * const streamSetPtr = b->CreateGEP(mStreamSetBufferPtr, {b->getInt32(0), b->getInt32(1)});
487    b->CreateStore(b->CreatePointerCast(ptr, bufferType->getPointerTo()), streamSetPtr);
488}
489
490std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const b, Value * const handle, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
491
492    // ENTRY
493    Value * const capacityPtr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(0)});
494    Value * const capacity = b->CreateLoad(capacityPtr);
495    Value * const streamSetPtr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(1)});
496    Value * const streamSet = b->CreateLoad(streamSetPtr);
497    blockIndex = modBufferSize(b, blockIndex);
498
499    assert (streamIndex->getType() == capacity->getType());
500    Value * const cond = b->CreateICmpULT(streamIndex, capacity);
501
502    // Are we guaranteed that we can access this stream?
503    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
504        if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
505            b->CreateAssert(cond, "out-of-bounds stream access");
506        }
507        Value * offset = b->CreateAdd(b->CreateMul(blockIndex, capacity), streamIndex);
508        return {streamSet, offset};
509    }
510
511    BasicBlock * const entry = b->GetInsertBlock();
512    BasicBlock * const expand = BasicBlock::Create(b->getContext(), "expand", entry->getParent());
513    BasicBlock * const resume = BasicBlock::Create(b->getContext(), "resume", entry->getParent());
514
515    b->CreateLikelyCondBr(cond, resume, expand);
516
517    // EXPAND
518    b->SetInsertPoint(expand);
519
520    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
521    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
522
523    Value * newCapacity = b->CreateAdd(streamIndex, b->getSize(1));
524    newCapacity = b->CreateCeilLog2(newCapacity);
525    newCapacity = b->CreateShl(b->getSize(1), newCapacity, "newCapacity");
526
527    std::string tmp;
528    raw_string_ostream out(tmp);
529    out << "__expand";
530    elementType->print(out);
531    std::string name = out.str();
532
533    Module * const m = b->getModule();
534    Function * expandFunction = m->getFunction(name);
535
536    if (expandFunction == nullptr) {
537
538        const auto ip = b->saveIP();
539
540        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), b->getSizeTy(), b->getSizeTy()}, false);
541        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
542
543        auto args = expandFunction->arg_begin();
544        Value * streamSet = &*args++;
545        Value * capacity = &*args++;
546        Value * newCapacity = &*args;
547
548        BasicBlock * entry = BasicBlock::Create(b->getContext(), "entry", expandFunction);
549        b->SetInsertPoint(entry);
550
551        Value * size = b->CreateMul(newCapacity, b->getSize(mBufferBlocks));
552        const auto memAlign = std::max(b->getCacheAlignment(), b->getBitBlockWidth() / 8);
553
554        Value * newStreamSet = b->CreatePointerCast(b->CreateAlignedMalloc(b->CreateMul(size, vectorWidth), memAlign), elementType->getPointerTo());
555        Value * const diffCapacity = b->CreateMul(b->CreateSub(newCapacity, capacity), vectorWidth);
556
557        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
558        for (unsigned i = 0; i < mBufferBlocks; ++i) {
559            ConstantInt * const offset = b->getSize(i);
560            Value * srcOffset = b->CreateMul(capacity, offset);
561            Value * srcPtr = b->CreateGEP(streamSet, srcOffset);
562            Value * destOffset = b->CreateMul(newCapacity, offset);
563            Value * destPtr = b->CreateGEP(newStreamSet, destOffset);
564            b->CreateMemCpy(destPtr, srcPtr, b->CreateMul(capacity, vectorWidth), alignment);
565            Value * destZeroOffset = b->CreateAdd(destOffset, capacity);
566            Value * destZeroPtr = b->CreateGEP(newStreamSet, destZeroOffset);
567            b->CreateMemZero(destZeroPtr, diffCapacity, alignment);
568        }
569
570        b->CreateFree(streamSet);
571
572        b->CreateRet(newStreamSet);
573
574        b->restoreIP(ip);
575    }
576
577    Value * newStreamSet = b->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
578    b->CreateStore(newStreamSet, streamSetPtr);
579    b->CreateStore(newCapacity, capacityPtr);
580
581    b->CreateBr(resume);
582
583    // RESUME
584    b->SetInsertPoint(resume);
585
586    PHINode * phiStreamSet = b->CreatePHI(streamSet->getType(), 2);
587    phiStreamSet->addIncoming(streamSet, entry);
588    phiStreamSet->addIncoming(newStreamSet, expand);
589
590    PHINode * phiCapacity = b->CreatePHI(capacity->getType(), 2);
591    phiCapacity->addIncoming(capacity, entry);
592    phiCapacity->addIncoming(newCapacity, expand);
593
594    Value * offset = b->CreateAdd(b->CreateMul(blockIndex, phiCapacity), streamIndex);
595
596    return {phiStreamSet, offset};
597}
598
599Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
600    report_fatal_error("temporarily not supported");
601//    Value * ptr, * offset;
602//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
603//    return b->CreateGEP(ptr, offset);
604}
605
606Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const b, Value * const handle, Value * addr, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
607    report_fatal_error("temporarily not supported");
608//    Value * ptr, * offset;
609//    std::tie(ptr, offset) = getInternalStreamBuffer(b, handle, streamIndex, blockIndex, readOnly);
610//    return b->CreateGEP(ptr, {offset, packIndex});
611}
612
613Value * ExpandableBuffer::getStreamSetCount(IDISA::IDISA_Builder * const b, Value * const handle) const {
614    return b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(0)}));
615}
616
617Value * ExpandableBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
618    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
619        b->CreateAssert(handle, "handle cannot be null");
620    }
621    Value * const baseAddr = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(1)}));
622    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
623        b->CreateAssert(handle, "base address cannot be 0");
624    }
625    return baseAddr;
626}
627
628void ExpandableBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
629    b->CreateFree(getBaseAddress(b.get(), mStreamSetBufferPtr));
630}
631
632Value * ExpandableBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value *, Value *) const {
633    report_fatal_error("Expandable buffers: getBlockAddress is not supported.");
634}
635
636Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const, Value *, Value *, Value *, bool) const {
637    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
638}
639
640
641Value * DynamicBuffer::getBaseAddress(IDISA::IDISA_Builder * const b, Value * const handle) const {
642    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
643        b->CreateAssert(handle, "handle cannot be null");
644    }
645    Value * const p = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
646    Value * const addr = b->CreateLoad(p);
647    if (codegen::DebugOptionIsSet(codegen::EnableAsserts)) {
648        b->CreateAssert(addr, "base address cannot be 0");
649    }
650    return addr;
651}
652
653Value * DynamicBuffer::getBlockAddress(IDISA::IDISA_Builder * const b, Value * const handle, Value * blockIndex) const {
654    Value * const workingBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::WorkingBlocks))}));
655    assert (blockIndex->getType() == workingBlocks->getType());
656    return b->CreateGEP(getBaseAddress(b, handle), b->CreateURem(blockIndex, workingBlocks));
657}
658
659Value * DynamicBuffer::getRawItemPointer(IDISA::IDISA_Builder * const b, Value * const handle, Value * absolutePosition) const {
660    Constant * blockSize = ConstantInt::get(absolutePosition->getType(), b->getBitBlockWidth());
661    Value * const absBlock = b->CreateUDiv(absolutePosition, blockSize);
662    Value * blockPos = b->CreateURem(absolutePosition, blockSize);
663    Value * blockPtr = getBlockAddress(b, handle, absBlock);
664    Type * const elemTy = mBaseType->getArrayElementType()->getVectorElementType();
665    const auto bw = elemTy->getPrimitiveSizeInBits();
666    assert (is_power_2(bw));
667    if (bw < 8) {
668        blockPos = b->CreateUDiv(blockPos, ConstantInt::get(blockPos->getType(), 8 / bw));
669        blockPtr = b->CreatePointerCast(blockPtr, b->getInt8PtrTy());
670    } else {
671        blockPtr = b->CreatePointerCast(blockPtr, elemTy->getPointerTo());
672    }
673    return b->CreateGEP(blockPtr, blockPos);
674}
675
676
677Value * DynamicBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value * availItems, bool reverse) const {
678    Value * const bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
679    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
680    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
681    assert (bufSize->getType() == fromPosition->getType());
682    Value * itemsFromBase = b->CreateURem(fromPosition, bufSize);
683    if (reverse) {
684        Value * bufAvail = b->CreateSelect(b->CreateICmpEQ(itemsFromBase, b->getSize(0)), bufSize, itemsFromBase);
685        return b->CreateSelect(b->CreateICmpULT(bufAvail, availItems), bufAvail, availItems);
686    } else {
687        Value * linearSpace = b->CreateSub(bufSize, itemsFromBase, "linearSpace");
688        return b->CreateSelect(b->CreateICmpULT(availItems, linearSpace), availItems, linearSpace);
689    }
690}
691
692Value * DynamicBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const b, Value * const handle, Value * fromPosition, Value *consumed, bool reverse) const {
693    Value * bufBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
694    Constant * blockSize = ConstantInt::get(bufBlocks->getType(), b->getBitBlockWidth());
695    Value * bufSize = b->CreateMul(bufBlocks, blockSize);
696    assert (bufSize->getType() == fromPosition->getType());
697    Value * bufRem = b->CreateURem(fromPosition, bufSize);
698    if (reverse) {
699        return b->CreateSelect(b->CreateICmpEQ(bufRem, b->getSize(0)), bufSize, bufRem);
700    }
701    Constant * overflow = ConstantInt::get(bufBlocks->getType(), mOverflowBlocks);
702    bufSize = b->CreateMul(b->CreateAdd(bufBlocks, overflow), blockSize);
703    return b->CreateSub(bufSize, bufRem, "linearWritable");
704}
705
706Value * DynamicBuffer::getBufferedSize(IDISA::IDISA_Builder * const b, Value * const handle) const {
707    Value * ptr = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))});
708    return b->CreateMul(b->CreateLoad(ptr), b->getSize(b->getBitBlockWidth()));
709}
710
711void DynamicBuffer::genCopyBackLogic(IDISA::IDISA_Builder * const b, Value * const handle, Value * priorProducedCount, Value * newProducedCount, const std::string Name) const {
712    assert (priorProducedCount->getType() == newProducedCount->getType());   
713    Value * workingBlocks = b->CreateLoad(b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::WorkingBlocks))}));
714    assert (workingBlocks->getType() == newProducedCount->getType());
715    Value * bufSize = b->CreateMul(workingBlocks, ConstantInt::get(workingBlocks->getType(), b->getBitBlockWidth()));
716    Value * priorBufPos = b->CreateURem(priorProducedCount, bufSize);
717    Value * newBufPos = b->CreateURem(newProducedCount, bufSize);
718    BasicBlock * copyBack = b->CreateBasicBlock(Name + "_dynamicCopyBack");
719    BasicBlock * done = b->CreateBasicBlock(Name + "_dynamicCopyBackDone");
720
721    Value * wraparound = b->CreateICmpUGT(priorBufPos, newBufPos);
722    b->CreateCondBr(wraparound, copyBack, done);
723
724    b->SetInsertPoint(copyBack);
725    Value * bufBasePtr = getBaseAddress(b, handle);
726    Value * overFlowAreaPtr = b->CreateGEP(bufBasePtr, workingBlocks);
727    createBlockAlignedCopy(b, bufBasePtr, overFlowAreaPtr, newBufPos);
728    b->CreateBr(done);
729
730    b->SetInsertPoint(done);
731}
732
733void DynamicBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) {
734    Value * const handle = b->CreateCacheAlignedAlloca(mBufferStructType);
735    size_t numStreams = 1;
736    if (isa<ArrayType>(mBaseType)) {
737        numStreams = mBaseType->getArrayNumElements();
738    }
739    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
740    Value * bufSize = b->getSize((mBufferBlocks + mOverflowBlocks) * b->getBitBlockWidth() * numStreams * fieldWidth/8);
741    bufSize = b->CreateRoundUp(bufSize, b->getSize(b->getCacheAlignment()));
742    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::BaseAddress))});
743    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
744    Value * bufPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(bufSize), bufPtrType);
745    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
746        b->CallPrintInt("allocated: ", bufPtr);
747        b->CallPrintInt("allocated capacity: ", bufSize);
748    }
749    b->CreateStore(bufPtr, bufBasePtrField);
750    b->CreateStore(ConstantPointerNull::getNullValue(bufPtrType), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))}));
751    b->CreateStore(bufSize, b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::AllocatedCapacity))}));
752    b->CreateStore(b->getSize(mBufferBlocks), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::WorkingBlocks))}));
753    b->CreateStore(b->getSize(-1), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::Length))}));
754    b->CreateStore(b->getSize(0), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::ProducedPosition))}));
755    b->CreateStore(b->getSize(0), b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(Field::ConsumedPosition))}));
756    mStreamSetBufferPtr = handle;
757}
758
759void DynamicBuffer::releaseBuffer(const std::unique_ptr<kernel::KernelBuilder> & b) const {
760    Value * const handle = mStreamSetBufferPtr;
761    /* Free the dynamically allocated buffer, but not the stack-allocated buffer struct. */
762    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
763    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
764    Value * priorBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))});
765    BasicBlock * freePrior = b->CreateBasicBlock("freePrior");
766    BasicBlock * freeCurrent = b->CreateBasicBlock("freeCurrent");
767    Value * priorBuf = b->CreateLoad(priorBasePtrField);
768    Value * priorBufIsNonNull = b->CreateICmpNE(priorBuf, ConstantPointerNull::get(cast<PointerType>(bufPtrType)));
769    b->CreateCondBr(priorBufIsNonNull, freePrior, freeCurrent);
770    b->SetInsertPoint(freePrior);
771    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
772        b->CallPrintInt("releasing: ", priorBuf);
773    }
774    b->CreateFree(priorBuf);
775    b->CreateBr(freeCurrent);
776    b->SetInsertPoint(freeCurrent);
777    b->CreateFree(b->CreateLoad(bufBasePtrField));
778}
779
780//
781//  Simple capacity doubling.  Use the circular buffer property: duplicating buffer data
782//  ensures that we have correct data.   TODO: consider optimizing based on actual
783//  consumer and producer positions.
784//
785void DynamicBuffer::doubleCapacity(IDISA::IDISA_Builder * const b, Value * const handle) {
786    size_t numStreams = 1;
787    if (isa<ArrayType>(mBaseType)) {
788        numStreams = mBaseType->getArrayNumElements();
789    }
790    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
791    Constant * blockBytes = b->getSize(b->getBitBlockWidth() * numStreams * fieldWidth/8);
792    Value * bufBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::BaseAddress))});
793    Type * bufPtrType = bufBasePtrField->getType()->getPointerElementType();
794    Value * priorBasePtrField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::PriorBaseAddress))});
795    Value * workingBlocksField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::WorkingBlocks))});
796    Value * capacityField = b->CreateGEP(handle, {b->getInt32(0), b->getInt32(int(DynamicBuffer::Field::AllocatedCapacity))});
797
798    Value * oldBufPtr = b->CreateLoad(bufBasePtrField);
799    Value * currentWorkingBlocks = b->CreateLoad(workingBlocksField);
800    Value * workingBytes = b->CreateMul(currentWorkingBlocks, blockBytes);
801    Value * const curAllocated = b->CreateLoad(capacityField);
802    Value * neededCapacity = b->CreateAdd(workingBytes, workingBytes);
803    if (mOverflowBlocks > 0) {
804        Constant * overflowBytes = b->getSize(mOverflowBlocks * b->getBitBlockWidth() * numStreams * fieldWidth/8);
805        neededCapacity = b->CreateAdd(neededCapacity, overflowBytes);
806    }
807    neededCapacity = b->CreateRoundUp(neededCapacity, b->getSize(b->getCacheAlignment()));
808    BasicBlock * doubleEntry = b->GetInsertBlock();
809    BasicBlock * doRealloc = b->CreateBasicBlock("doRealloc");
810    BasicBlock * doCopy2 = b->CreateBasicBlock("doCopy2");
811    b->CreateCondBr(b->CreateICmpULT(curAllocated, neededCapacity), doRealloc, doCopy2);
812    b->SetInsertPoint(doRealloc);
813    // If there is a non-null priorBasePtr, free it.
814    Value * priorBuf = b->CreateLoad(priorBasePtrField);
815    Value * priorBufIsNonNull = b->CreateICmpNE(priorBuf, ConstantPointerNull::get(cast<PointerType>(bufPtrType)));
816    BasicBlock * deallocatePrior = b->CreateBasicBlock("deallocatePrior");
817    BasicBlock * allocateNew = b->CreateBasicBlock("allocateNew");
818    b->CreateCondBr(priorBufIsNonNull, deallocatePrior, allocateNew);
819    b->SetInsertPoint(deallocatePrior);
820    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
821        b->CallPrintInt("deallocating: ", priorBuf);
822    }
823    b->CreateFree(priorBuf);
824    b->CreateBr(allocateNew);
825    b->SetInsertPoint(allocateNew);
826    b->CreateStore(oldBufPtr, priorBasePtrField);
827    Value * newBufPtr = b->CreatePointerCast(b->CreateCacheAlignedMalloc(neededCapacity), bufPtrType);
828    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
829        b->CallPrintInt("re-allocated: ", newBufPtr);
830        b->CallPrintInt("allocated capacity: ", neededCapacity);
831    }
832    b->CreateStore(newBufPtr, bufBasePtrField);
833    createBlockCopy(b, newBufPtr, oldBufPtr, currentWorkingBlocks);
834    b->CreateStore(neededCapacity, capacityField);
835    b->CreateBr(doCopy2);
836    b->SetInsertPoint(doCopy2);
837    PHINode * bufPtr = b->CreatePHI(oldBufPtr->getType(), 2);
838    bufPtr->addIncoming(oldBufPtr, doubleEntry);
839    bufPtr->addIncoming(newBufPtr, allocateNew);
840    createBlockCopy(b, b->CreateGEP(bufPtr, currentWorkingBlocks), bufPtr, currentWorkingBlocks);
841    currentWorkingBlocks = b->CreateAdd(currentWorkingBlocks, currentWorkingBlocks);
842    if (codegen::DebugOptionIsSet(codegen::TraceDynamicBuffers)) {
843        b->CallPrintInt("currentWorkingBlocks: ", currentWorkingBlocks);
844    }
845    b->CreateStore(currentWorkingBlocks, workingBlocksField);
846}
847
848inline StructType * getSourceBufferType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * const type, const unsigned MemoryAddressSpace) {
849    return StructType::get(b->getContext(), {resolveStreamSetType(b, type)->getPointerTo(MemoryAddressSpace), b->getSizeTy(), b->getSizeTy()});
850}
851
852SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
853: StreamSetBuffer(BufferKind::SourceBuffer, type, getSourceBufferType(b, type, MemoryAddressSpace), 0, 0, StructAddressSpace) {
854    mUniqueID = "B";
855    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
856        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
857    }
858}
859
860ExternalBuffer::ExternalBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, Value * addr, unsigned AddressSpace)
861: StreamSetBuffer(BufferKind::ExternalBuffer, type, resolveStreamSetType(b, type), 0, 0, AddressSpace) {
862    mUniqueID = "E";
863    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
864    mStreamSetBufferPtr = b->CreatePointerBitCastOrAddrSpaceCast(addr, getPointerType());
865}
866
867CircularBuffer::CircularBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
868: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, 0, AddressSpace) {
869    mUniqueID = "C" + std::to_string(bufferBlocks);
870    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
871}
872
873CircularBuffer::CircularBuffer(const BufferKind k, const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
874: StreamSetBuffer(k, type, resolveStreamSetType(b, type), bufferBlocks, overflowBlocks, AddressSpace) {
875
876}
877
878CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
879: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, overflowBlocks, AddressSpace) {
880    if (bufferBlocks < 2 * overflowBlocks) {
881        report_fatal_error("CircularCopybackBuffer: bufferBlocks < 2 * overflowBlocks");
882    }
883    mUniqueID = "CC" + std::to_string(bufferBlocks);
884    if (mOverflowBlocks != 1) mUniqueID += "_" + std::to_string(mOverflowBlocks);
885    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
886}
887
888ExpandableBuffer::ExpandableBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
889: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, 0, AddressSpace)
890, mInitialCapacity(type->getArrayNumElements()) {
891    mUniqueID = "XP" + std::to_string(bufferBlocks);
892    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
893}
894
895SwizzledCopybackBuffer::SwizzledCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned fieldwidth, unsigned AddressSpace)
896: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, overflowBlocks, AddressSpace), mFieldWidth(fieldwidth) {
897    mUniqueID = "SW" + std::to_string(fieldwidth) + ":" + std::to_string(bufferBlocks);
898    if (bufferBlocks < 2 * overflowBlocks) {
899        report_fatal_error("SwizzledCopybackBuffer: bufferBlocks < 2 * overflowBlocks");
900    }
901    if (overflowBlocks != 1) {
902        mUniqueID += "_" + std::to_string(mOverflowBlocks);
903    }
904    if (AddressSpace > 0) {
905        mUniqueID += "@" + std::to_string(AddressSpace);
906    }
907}
908
909inline StructType * getDynamicBufferStructType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * baseType, const unsigned addrSpace) {
910    IntegerType * sizeTy = b->getSizeTy();
911    PointerType * typePtr = baseType->getPointerTo(addrSpace);
912    return StructType::get(b->getContext(), {typePtr, typePtr, sizeTy, sizeTy, sizeTy, sizeTy, sizeTy});
913}
914
915DynamicBuffer::DynamicBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t initialCapacity, size_t overflow, unsigned swizzle, unsigned addrSpace)
916: StreamSetBuffer(BufferKind::DynamicBuffer, type, resolveStreamSetType(b, type), initialCapacity, overflow, addrSpace)
917, mBufferStructType(getDynamicBufferStructType(b, mType, addrSpace))
918, mSwizzleFactor(swizzle) {
919    if (initialCapacity * b->getBitBlockWidth() < 2 * overflow) {
920        report_fatal_error("DynamicBuffer: initialCapacity * b->getBitBlockWidth() < 2 * overflow");
921    }
922    mUniqueID = "DB";
923    if (swizzle != 1) {
924        mUniqueID += "s" + std::to_string(swizzle);
925    }
926        if (overflow != 0) {
927        mUniqueID += "o" + std::to_string(overflow);
928    }
929    if (addrSpace != 0) {
930        mUniqueID += "@" + std::to_string(addrSpace);
931    }
932}
933
934
935inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned OverflowBlocks, unsigned AddressSpace)
936: mBufferKind(k)
937, mType(resolvedType)
938, mBufferBlocks(BufferBlocks)
939, mOverflowBlocks(OverflowBlocks)
940, mAddressSpace(AddressSpace)
941, mStreamSetBufferPtr(nullptr)
942, mBaseType(baseType)
943, mProducer(nullptr) {
944    assert((k == BufferKind::SourceBuffer || k == BufferKind::ExternalBuffer) ^ (BufferBlocks > 0));
945    assert ("A zero length buffer cannot have overflow blocks!" && ((BufferBlocks > 0) || (OverflowBlocks == 0)));
946}
947
948StreamSetBuffer::~StreamSetBuffer() { }
949
950// Helper routines
951ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
952    unsigned numElements = 1;
953    if (LLVM_LIKELY(type->isArrayTy())) {
954        numElements = type->getArrayNumElements();
955        type = type->getArrayElementType();
956    }
957    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
958        type = type->getVectorElementType();
959        if (LLVM_LIKELY(type->isIntegerTy())) {
960            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
961            type = b->getBitBlockType();
962            if (fieldWidth != 1) {
963                type = ArrayType::get(type, fieldWidth);
964            }
965            return ArrayType::get(type, numElements);
966        }
967    }
968    std::string tmp;
969    raw_string_ostream out(tmp);
970    type->print(out);
971    out << " is an unvalid stream set buffer type.";
972    report_fatal_error(out.str());
973}
974
975StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
976    if (LLVM_LIKELY(type->isArrayTy())) {
977        type = type->getArrayElementType();
978    }
979    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
980        type = type->getVectorElementType();
981        if (LLVM_LIKELY(type->isIntegerTy())) {
982            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
983            type = b->getBitBlockType();
984            if (fieldWidth != 1) {
985                type = ArrayType::get(type, fieldWidth);
986            }
987            return StructType::get(b->getContext(), {b->getSizeTy(), type->getPointerTo()});
988        }
989    }
990    std::string tmp;
991    raw_string_ostream out(tmp);
992    type->print(out);
993    out << " is an unvalid stream set buffer type.";
994    report_fatal_error(out.str());
995}
Note: See TracBrowser for help on using the repository browser.