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

Last change on this file since 5386 was 5386, checked in by nmedfort, 2 years ago

Replaced stdin input stream with mmap'ed buffer and aligned each read call to the page size.

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