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

Last change on this file since 5493 was 5493, checked in by cameron, 2 years ago

Restore check-ins from the last several days

File size: 31.9 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
13namespace llvm { class Constant; }
14namespace llvm { class Function; }
15
16using namespace parabix;
17using namespace llvm;
18using namespace IDISA;
19
20ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
21
22StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
23
24void StreamSetBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
25    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
26        Type * const ty = getType();
27        mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(ty, iBuilder->getSize(mBufferBlocks));
28        iBuilder->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, iBuilder->getCacheAlignment());
29    } else {
30        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
31    }
32}
33
34Value * StreamSetBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool /* readOnly */) const {
35    if (codegen::EnableAsserts) {
36        Value * const count = getStreamSetCount(iBuilder, self);
37        Value * const index = iBuilder->CreateZExtOrTrunc(streamIndex, count->getType());
38        Value * const cond = iBuilder->CreateICmpULT(index, count);
39        iBuilder->CreateAssert(cond, "StreamSetBuffer: out-of-bounds stream access");
40    }
41    return iBuilder->CreateGEP(getStreamSetBlockPtr(iBuilder, self, blockIndex), {iBuilder->getInt32(0), streamIndex});
42}
43
44Value * StreamSetBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool /* readOnly */) const {
45    if (codegen::EnableAsserts) {
46        Value * const count = getStreamSetCount(iBuilder, self);
47        Value * const index = iBuilder->CreateZExtOrTrunc(streamIndex, count->getType());
48        Value * const cond = iBuilder->CreateICmpULT(index, count);
49        iBuilder->CreateAssert(cond, "StreamSetBuffer: out-of-bounds stream access");
50    }
51    return iBuilder->CreateGEP(getStreamSetBlockPtr(iBuilder, self, blockIndex), {iBuilder->getInt32(0), streamIndex, packIndex});
52}
53
54void StreamSetBuffer::setBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * /* self */, Value * /* addr */) const {
55    report_fatal_error("setBaseAddress is not supported by this buffer type");
56}
57
58Value * StreamSetBuffer::getBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * /* self */) const {
59    report_fatal_error("getBufferedSize is not supported by this buffer type");
60}
61
62void StreamSetBuffer::setBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * /* self */, llvm::Value * /* size */) const {
63    report_fatal_error("setBufferedSize is not supported by this buffer type");
64}
65
66inline bool StreamSetBuffer::isCapacityGuaranteed(const Value * const index, const size_t capacity) const {
67    if (LLVM_UNLIKELY(isa<ConstantInt>(index))) {
68        if (LLVM_LIKELY(cast<ConstantInt>(index)->getLimitedValue() < capacity)) {
69            return true;
70        }
71    }
72    return false;
73}
74
75Value * StreamSetBuffer::getStreamSetCount(IDISA::IDISA_Builder * const iBuilder, Value *) const {
76    uint64_t count = 1;
77    if (isa<ArrayType>(mBaseType)) {
78        count = mBaseType->getArrayNumElements();
79    }
80    return iBuilder->getSize(count);
81}
82
83inline Value * StreamSetBuffer::modByBufferBlocks(IDISA::IDISA_Builder * const iBuilder, Value * const offset) const {
84    assert (offset->getType()->isIntegerTy());
85    if (isCapacityGuaranteed(offset, mBufferBlocks)) {
86        return offset;
87    } else if (mBufferBlocks == 1) {
88        return ConstantInt::getNullValue(iBuilder->getSizeTy());
89    } else if ((mBufferBlocks & (mBufferBlocks - 1)) == 0) { // is power of 2
90        return iBuilder->CreateAnd(offset, ConstantInt::get(offset->getType(), mBufferBlocks - 1));
91    } else {
92        return iBuilder->CreateURem(offset, ConstantInt::get(offset->getType(), mBufferBlocks));
93    }
94}
95
96/**
97 * @brief getRawItemPointer
98 *
99 * get a raw pointer the iN field at position absoluteItemPosition of the stream number streamIndex of the stream set.
100 * In the case of a stream whose fields are less than one byte (8 bits) in size, the pointer is to the containing byte.
101 * The type of the pointer is i8* for fields of 8 bits or less, otherwise iN* for N-bit fields.
102 */
103Value * StreamSetBuffer::getRawItemPointer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * absolutePosition) const {
104    Value * ptr = iBuilder->CreateGEP(getBaseAddress(iBuilder, self), {iBuilder->getInt32(0), streamIndex});
105    Value * relativePosition = absolutePosition;
106    const auto bw = mBaseType->getArrayElementType()->getScalarSizeInBits();
107    if (bw < 8) {
108        assert (bw  == 1 || bw == 2 || bw == 4);
109        relativePosition = iBuilder->CreateUDiv(relativePosition, ConstantInt::get(relativePosition->getType(), 8 / bw));
110        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getInt8PtrTy());
111    } else {
112        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getIntNTy(bw)->getPointerTo());
113    }
114    return iBuilder->CreateGEP(ptr, relativePosition);
115}
116
117Value * StreamSetBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
118    if (isa<ArrayType>(mType) && dyn_cast<ArrayType>(mType)->getNumElements() > 1) {
119        Constant * stride = iBuilder->getSize(iBuilder->getStride());
120        return iBuilder->CreateSub(stride, iBuilder->CreateURem(fromPosition, stride));
121    } else {
122        Constant * bufSize = iBuilder->getSize(mBufferBlocks * iBuilder->getStride());
123        return iBuilder->CreateSub(bufSize, iBuilder->CreateURem(fromPosition, bufSize));
124    }
125}
126
127Value * StreamSetBuffer::getLinearlyAccessibleBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
128    Constant * bufBlocks = iBuilder->getSize(mBufferBlocks);
129    return iBuilder->CreateSub(bufBlocks, iBuilder->CreateURem(fromBlock, bufBlocks));
130}
131
132Value * StreamSetBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
133    return getLinearlyAccessibleItems(iBuilder, fromPosition);
134}
135
136Value * StreamSetBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
137    return getLinearlyAccessibleBlocks(iBuilder, fromBlock);
138}
139
140Value * StreamSetBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
141    iBuilder->CreateAssert(self, "StreamSetBuffer base address cannot be 0");
142    return self;
143}
144
145void StreamSetBuffer::releaseBuffer(IDISA::IDISA_Builder * const /* iBuilder */, Value * /* self */) const {
146    /* do nothing: memory is stack allocated */
147}
148
149void StreamSetBuffer::createBlockCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * blocksToCopy) const {
150    Type * i8ptr = iBuilder->getInt8PtrTy();
151    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
152    uint64_t numStreams = 1;
153    if (isa<ArrayType>(mBaseType)) {
154        numStreams = mBaseType->getArrayNumElements();
155    }
156    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
157    Value * blockCopyBytes = iBuilder->CreateMul(blocksToCopy, iBuilder->getSize(iBuilder->getBitBlockWidth() * numStreams * fieldWidth/8));
158    iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), blockCopyBytes, alignment);
159}
160
161void StreamSetBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy) const {
162    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
163    const unsigned alignment = iBuilder->getBitBlockWidth() / 8;
164    Constant * const blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
165    uint64_t numStreams = 1;
166    if (isa<ArrayType>(mBaseType)) {
167        numStreams = mBaseType->getArrayNumElements();
168    }
169    const auto fieldWidth = mBaseType->getArrayElementType()->getScalarSizeInBits();
170    if (numStreams == 1) {
171        Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth));
172        Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
173        iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, int8PtrTy), iBuilder->CreateBitCast(sourceBlockPtr, int8PtrTy), copyBytes, alignment);
174    } else {
175        Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
176        Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
177        Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
178        Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
179        Value * blockCopyBytes = iBuilder->CreateMul(blocksToCopy, iBuilder->getSize(iBuilder->getBitBlockWidth() * numStreams * fieldWidth/8));
180        iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, int8PtrTy), iBuilder->CreateBitCast(sourceBlockPtr, int8PtrTy), blockCopyBytes, alignment);
181        Value * partialCopyBitsPerStream = iBuilder->CreateMul(partialItems, iBuilder->getSize(fieldWidth));
182        Value * partialCopyBytesPerStream = iBuilder->CreateLShr(iBuilder->CreateAdd(partialCopyBitsPerStream, iBuilder->getSize(7)), iBuilder->getSize(3));
183        for (unsigned strm = 0; strm < numStreams; strm++) {
184            Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
185            Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
186            strmTargetPtr = iBuilder->CreateBitCast(strmTargetPtr, int8PtrTy);
187            strmSourcePtr = iBuilder->CreateBitCast(strmSourcePtr, int8PtrTy);
188            iBuilder->CreateMemMove(strmTargetPtr, strmSourcePtr, partialCopyBytesPerStream, alignment);
189        }
190    }
191}
192
193// Source File Buffer
194Value * SourceBuffer::getBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
195    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
196    return iBuilder->CreateLoad(ptr);
197}
198
199void SourceBuffer::setBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self, llvm::Value * size) const {
200    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
201    iBuilder->CreateStore(size, ptr);
202}
203
204void SourceBuffer::setBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * addr) const {
205    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
206    iBuilder->CreateStore(iBuilder->CreatePointerCast(addr, ptr->getType()->getPointerElementType()), ptr);
207}
208
209Value * SourceBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * const self) const {
210    iBuilder->CreateAssert(self, "SourceBuffer: instance cannot be null");
211    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
212    Value * const addr = iBuilder->CreateLoad(ptr);
213    iBuilder->CreateAssert(addr, "SourceBuffer: base address cannot be 0");
214    return addr;
215}
216
217Value * SourceBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
218    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
219}
220
221Value * SourceBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
222    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
223}
224
225// External File Buffer
226void ExternalBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> &) {
227    report_fatal_error("External buffers cannot be allocated.");
228}
229
230Value * ExternalBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
231    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
232}
233
234Value * ExternalBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
235    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
236}
237
238// Circular Buffer
239Value * CircularBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * const self, Value * const blockIndex) const {
240    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
241}
242
243Value * CircularBuffer::getRawItemPointer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * absolutePosition) const {
244    Value * ptr = iBuilder->CreateGEP(getBaseAddress(iBuilder, self), {iBuilder->getInt32(0), streamIndex});
245    Value * relativePosition = iBuilder->CreateURem(absolutePosition, ConstantInt::get(absolutePosition->getType(), mBufferBlocks * iBuilder->getBitBlockWidth()));
246    const auto bw = mBaseType->getArrayElementType()->getScalarSizeInBits();
247    if (bw < 8) {
248        assert (bw  == 1 || bw == 2 || bw == 4);
249        relativePosition = iBuilder->CreateUDiv(relativePosition, ConstantInt::get(relativePosition->getType(), 8 / bw));
250        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getInt8PtrTy());
251    } else {
252        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getIntNTy(bw)->getPointerTo());
253    }
254    return iBuilder->CreateGEP(ptr, relativePosition);
255}
256
257// CircularCopybackBuffer Buffer
258void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
259    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
260}
261
262void CircularCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
263    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
264    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
265}
266
267Value * CircularCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
268    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
269}
270
271Value * CircularCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
272    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
273}
274
275// SwizzledCopybackBuffer Buffer
276
277void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
278    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
279}
280
281void SwizzledCopybackBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy) const {
282    Type * int8PtrTy = iBuilder->getInt8PtrTy();
283    DataLayout DL(iBuilder->getModule());
284    IntegerType * const intAddrTy = iBuilder->getIntPtrTy(DL);
285
286    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
287    Function * f = iBuilder->GetInsertBlock()->getParent();
288    BasicBlock * wholeBlockCopy = BasicBlock::Create(iBuilder->getContext(), "wholeBlockCopy", f, 0);
289    BasicBlock * partialBlockCopy = BasicBlock::Create(iBuilder->getContext(), "partialBlockCopy", f, 0);
290    BasicBlock * copyDone = BasicBlock::Create(iBuilder->getContext(), "copyDone", f, 0);
291    const unsigned numStreams = getType()->getArrayNumElements();
292    const unsigned swizzleFactor = iBuilder->getBitBlockWidth()/mFieldWidth;
293    const auto elemTy = getType()->getArrayElementType();
294    const unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
295    Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
296    Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
297    Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
298    Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
299    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToCopy, iBuilder->getSize(0)), wholeBlockCopy, partialBlockCopy);
300
301    iBuilder->SetInsertPoint(wholeBlockCopy);
302    const unsigned alignment = iBuilder->getBitBlockWidth() / 8;
303    Value * copyLength = iBuilder->CreateSub(iBuilder->CreatePtrToInt(partialBlockTargetPtr, intAddrTy), iBuilder->CreatePtrToInt(targetBlockPtr, intAddrTy));
304    iBuilder->CreateMemMove(iBuilder->CreatePointerCast(targetBlockPtr, int8PtrTy), iBuilder->CreatePointerCast(sourceBlockPtr, int8PtrTy), copyLength, alignment);
305    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(partialItems, iBuilder->getSize(0)), partialBlockCopy, copyDone);
306    iBuilder->SetInsertPoint(partialBlockCopy);
307    Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth * swizzleFactor));
308    Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
309    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
310        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
311        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
312        iBuilder->CreateMemMove(iBuilder->CreatePointerCast(strmTargetPtr, int8PtrTy), iBuilder->CreatePointerCast(strmSourcePtr, int8PtrTy), copyBytes, alignment);
313    }
314    iBuilder->CreateBr(copyDone);
315
316    iBuilder->SetInsertPoint(copyDone);
317}
318
319void SwizzledCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
320    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
321    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
322}
323
324Value * SwizzledCopybackBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
325    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
326}
327
328Value * SwizzledCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
329    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
330}
331
332Value * SwizzledCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
333    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
334}
335
336// Expandable Buffer
337
338void ExpandableBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
339    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType());
340    Value * const capacityPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
341    iBuilder->CreateStore(iBuilder->getSize(mInitialCapacity), capacityPtr);
342    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
343    Constant * const bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), iBuilder->getSizeTy(), false);
344    Constant * const size = ConstantExpr::getMul(iBuilder->getSize(mBufferBlocks * mInitialCapacity), bufferWidth);
345    const auto alignment = std::max(iBuilder->getCacheAlignment(), iBuilder->getBitBlockWidth() / 8);
346    Value * const ptr = iBuilder->CreateAlignedMalloc(size, alignment);
347    iBuilder->CreateMemZero(ptr, size, bufferType->getPrimitiveSizeInBits() / 8);
348    Value * const streamSetPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
349    iBuilder->CreateStore(iBuilder->CreatePointerCast(ptr, bufferType->getPointerTo()), streamSetPtr);
350}
351
352std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
353
354    // ENTRY
355    Value * const capacityPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
356    Value * const capacity = iBuilder->CreateLoad(capacityPtr);
357    Value * const streamSetPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
358    Value * const streamSet = iBuilder->CreateLoad(streamSetPtr);
359    blockIndex = modByBufferBlocks(iBuilder, blockIndex);
360
361    assert (streamIndex->getType() == capacity->getType());
362    Value * const cond = iBuilder->CreateICmpULT(streamIndex, capacity);
363
364    // Are we guaranteed that we can access this stream?
365    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
366        iBuilder->CreateAssert(cond, "ExpandableBuffer: out-of-bounds stream access");
367        Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, capacity), streamIndex);
368        return {streamSet, offset};
369    }
370
371    BasicBlock * const entry = iBuilder->GetInsertBlock();
372    BasicBlock * const expand = BasicBlock::Create(iBuilder->getContext(), "expand", entry->getParent());
373    BasicBlock * const resume = BasicBlock::Create(iBuilder->getContext(), "resume", entry->getParent());
374
375    iBuilder->CreateLikelyCondBr(cond, resume, expand);
376
377    // EXPAND
378    iBuilder->SetInsertPoint(expand);
379
380    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
381    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
382
383    Value * newCapacity = iBuilder->CreateAdd(streamIndex, iBuilder->getSize(1));
384    newCapacity = iBuilder->CreateCeilLog2(newCapacity);
385    newCapacity = iBuilder->CreateShl(iBuilder->getSize(1), newCapacity, "newCapacity");
386
387    std::string tmp;
388    raw_string_ostream out(tmp);
389    out << "__expand";
390    elementType->print(out);
391    std::string name = out.str();
392
393    Module * const m = iBuilder->getModule();
394    Function * expandFunction = m->getFunction(name);
395
396    if (expandFunction == nullptr) {
397
398        const auto ip = iBuilder->saveIP();
399
400        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), iBuilder->getSizeTy(), iBuilder->getSizeTy()}, false);
401        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
402
403        auto args = expandFunction->arg_begin();
404        Value * streamSet = &*args++;
405        Value * capacity = &*args++;
406        Value * newCapacity = &*args;
407
408        BasicBlock * entry = BasicBlock::Create(iBuilder->getContext(), "entry", expandFunction);
409        iBuilder->SetInsertPoint(entry);
410
411        Value * size = iBuilder->CreateMul(newCapacity, iBuilder->getSize(mBufferBlocks));
412        const auto memAlign = std::max(iBuilder->getCacheAlignment(), iBuilder->getBitBlockWidth() / 8);
413
414        Value * newStreamSet = iBuilder->CreatePointerCast(iBuilder->CreateAlignedMalloc(iBuilder->CreateMul(size, vectorWidth), memAlign), elementType->getPointerTo());
415        Value * const diffCapacity = iBuilder->CreateMul(iBuilder->CreateSub(newCapacity, capacity), vectorWidth);
416
417        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
418        for (unsigned i = 0; i < mBufferBlocks; ++i) {
419            ConstantInt * const offset = iBuilder->getSize(i);
420            Value * srcOffset = iBuilder->CreateMul(capacity, offset);
421            Value * srcPtr = iBuilder->CreateGEP(streamSet, srcOffset);
422            Value * destOffset = iBuilder->CreateMul(newCapacity, offset);
423            Value * destPtr = iBuilder->CreateGEP(newStreamSet, destOffset);
424            iBuilder->CreateMemCpy(destPtr, srcPtr, iBuilder->CreateMul(capacity, vectorWidth), alignment);
425            Value * destZeroOffset = iBuilder->CreateAdd(destOffset, capacity);
426            Value * destZeroPtr = iBuilder->CreateGEP(newStreamSet, destZeroOffset);
427            iBuilder->CreateMemZero(destZeroPtr, diffCapacity, alignment);
428        }
429
430        iBuilder->CreateFree(streamSet);
431
432        iBuilder->CreateRet(newStreamSet);
433
434        iBuilder->restoreIP(ip);
435    }
436
437    Value * newStreamSet = iBuilder->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
438    iBuilder->CreateStore(newStreamSet, streamSetPtr);
439    iBuilder->CreateStore(newCapacity, capacityPtr);
440
441    iBuilder->CreateBr(resume);
442
443    // RESUME
444    iBuilder->SetInsertPoint(resume);
445
446    PHINode * phiStreamSet = iBuilder->CreatePHI(streamSet->getType(), 2);
447    phiStreamSet->addIncoming(streamSet, entry);
448    phiStreamSet->addIncoming(newStreamSet, expand);
449
450    PHINode * phiCapacity = iBuilder->CreatePHI(capacity->getType(), 2);
451    phiCapacity->addIncoming(capacity, entry);
452    phiCapacity->addIncoming(newCapacity, expand);
453
454    Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, phiCapacity), streamIndex);
455
456    return {phiStreamSet, offset};
457}
458
459Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
460    Value * ptr, * offset;
461    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
462    return iBuilder->CreateGEP(ptr, offset);
463}
464
465Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
466    Value * ptr, * offset;
467    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
468    return iBuilder->CreateGEP(ptr, {offset, packIndex});
469}
470
471Value * ExpandableBuffer::getStreamSetCount(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
472    return iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
473}
474
475Value * ExpandableBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
476    iBuilder->CreateAssert(self, "ExpandableBuffer: instance cannot be null");
477    Value * const baseAddr = iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
478    iBuilder->CreateAssert(self, "ExpandableBuffer: base address cannot be 0");
479    return baseAddr;
480}
481
482void ExpandableBuffer::releaseBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
483    iBuilder->CreateFree(getBaseAddress(iBuilder, self));
484}
485
486Value * ExpandableBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value *, Value *) const {
487    report_fatal_error("Expandable buffers: getStreamSetBlockPtr is not supported.");
488}
489
490Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
491    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
492}
493
494SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
495: StreamSetBuffer(BufferKind::SourceBuffer, type, StructType::get(resolveStreamSetType(b, type)->getPointerTo(MemoryAddressSpace), b->getSizeTy(), nullptr), 0, StructAddressSpace) {
496    mUniqueID = "B";
497    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
498        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
499    }
500}
501
502ExternalBuffer::ExternalBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, llvm::Value * addr, unsigned AddressSpace)
503: StreamSetBuffer(BufferKind::ExternalBuffer, type, resolveStreamSetType(b, type), 0, AddressSpace) {
504    mUniqueID = "E";
505    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
506    mStreamSetBufferPtr = b->CreatePointerBitCastOrAddrSpaceCast(addr, getPointerType());
507}
508
509CircularBuffer::CircularBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
510: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
511    mUniqueID = "C" + std::to_string(bufferBlocks);
512    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
513}
514
515CircularBuffer::CircularBuffer(const BufferKind k, const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
516: StreamSetBuffer(k, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
517
518}
519
520CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
521: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, AddressSpace)
522, mOverflowBlocks(overflowBlocks) {
523    mUniqueID = "CC" + std::to_string(bufferBlocks);
524    if (mOverflowBlocks != 1) mUniqueID += "_" + std::to_string(mOverflowBlocks);
525    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
526}
527
528ExpandableBuffer::ExpandableBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
529: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, AddressSpace)
530, mInitialCapacity(type->getArrayNumElements()) {
531    mUniqueID = "XP" + std::to_string(bufferBlocks);
532    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
533}
534
535SwizzledCopybackBuffer::SwizzledCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned fieldwidth, unsigned AddressSpace)
536: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace), mOverflowBlocks(overflowBlocks), mFieldWidth(fieldwidth) {
537    mUniqueID = "SW" + std::to_string(fieldwidth) + ":" + std::to_string(bufferBlocks);
538    if (mOverflowBlocks != 1) {
539        mUniqueID += "_" + std::to_string(mOverflowBlocks);
540    }
541    if (AddressSpace > 0) {
542        mUniqueID += "@" + std::to_string(AddressSpace);
543    }
544}
545
546inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned AddressSpace)
547: mBufferKind(k)
548, mType(resolvedType)
549, mBufferBlocks(BufferBlocks)
550, mAddressSpace(AddressSpace)
551, mStreamSetBufferPtr(nullptr)
552, mBaseType(baseType)
553, mProducer(nullptr) {
554
555}
556
557StreamSetBuffer::~StreamSetBuffer() { }
558
559// Helper routines
560ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
561    unsigned numElements = 1;
562    if (LLVM_LIKELY(type->isArrayTy())) {
563        numElements = type->getArrayNumElements();
564        type = type->getArrayElementType();
565    }
566    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
567        type = type->getVectorElementType();
568        if (LLVM_LIKELY(type->isIntegerTy())) {
569            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
570            type = b->getBitBlockType();
571            if (fieldWidth != 1) {
572                type = ArrayType::get(type, fieldWidth);
573            }
574            return ArrayType::get(type, numElements);
575        }
576    }
577    std::string tmp;
578    raw_string_ostream out(tmp);
579    type->print(out);
580    out << " is an unvalid stream set buffer type.";
581    report_fatal_error(out.str());
582}
583
584StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
585    if (LLVM_LIKELY(type->isArrayTy())) {
586        type = type->getArrayElementType();
587    }
588    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
589        type = type->getVectorElementType();
590        if (LLVM_LIKELY(type->isIntegerTy())) {
591            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
592            type = b->getBitBlockType();
593            if (fieldWidth != 1) {
594                type = ArrayType::get(type, fieldWidth);
595            }
596            return StructType::get(b->getSizeTy(), type->getPointerTo(), nullptr);
597        }
598    }
599    std::string tmp;
600    raw_string_ostream out(tmp);
601    type->print(out);
602    out << " is an unvalid stream set buffer type.";
603    report_fatal_error(out.str());
604}
Note: See TracBrowser for help on using the repository browser.