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

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

Bug fixes for MultiBlockKernel?, StdOutKernel?

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