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

Last change on this file since 5353 was 5353, checked in by nmedfort, 3 years ago

Progress on parenthesis matching example

File size: 19.4 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(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(self, blockIndex), {iBuilder->getInt32(0), streamIndex, packIndex});
44}
45
46inline bool StreamSetBuffer::isCapacityGuaranteed(const llvm::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
55llvm::Value * 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 llvm::Value * StreamSetBuffer::modByBufferBlocks(llvm::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 = 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(llvm::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    }
107    else {
108        Constant * bufSize = iBuilder->getSize(mBufferBlocks * iBuilder->getStride());
109        return iBuilder->CreateSub(bufSize, iBuilder->CreateURem(fromPosition, bufSize));
110    }
111}
112
113
114// Single Block Buffer
115
116// For a single block buffer, the block pointer is always the buffer base pointer.
117Value * SingleBlockBuffer::getStreamSetBlockPtr(Value * self, Value *) const {
118    return self;
119}
120
121// External File Buffer
122void ExternalFileBuffer::setStreamSetBuffer(Value * ptr, Value * /* fileSize */) {
123    mStreamSetBufferPtr = iBuilder->CreatePointerBitCastOrAddrSpaceCast(ptr, getPointerType());
124}
125
126void ExternalFileBuffer::setEmptyBuffer(Value * ptr) {   
127    mStreamSetBufferPtr = iBuilder->CreatePointerBitCastOrAddrSpaceCast(ptr, getPointerType());
128}
129
130void ExternalFileBuffer::allocateBuffer() {
131    report_fatal_error("External buffers cannot be allocated.");
132}
133
134Value * ExternalFileBuffer::getStreamSetBlockPtr(Value * self, Value * blockNo) const {
135    return iBuilder->CreateGEP(self, blockNo);
136}
137
138Value * ExternalFileBuffer::getLinearlyAccessibleItems(llvm::Value *) const {
139    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
140}
141
142// Circular Buffer
143
144Value * CircularBuffer::getStreamSetBlockPtr(Value * self, Value * blockIndex) const {
145    return iBuilder->CreateGEP(self, modByBufferBlocks(blockIndex));
146}
147
148// CircularCopybackBuffer Buffer
149
150void CircularCopybackBuffer::allocateBuffer() {
151    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
152}
153
154void CircularCopybackBuffer::createCopyBack(Value * self, Value * overFlowItems) const {
155    Function * f = iBuilder->GetInsertBlock()->getParent();
156    BasicBlock * wholeBlockCopy = BasicBlock::Create(iBuilder->getContext(), "wholeBlockCopy", f, 0);
157    BasicBlock * partialBlockCopy = BasicBlock::Create(iBuilder->getContext(), "partialBlockCopy", f, 0);
158    BasicBlock * copyBackDone = BasicBlock::Create(iBuilder->getContext(), "copyBackDone", f, 0);
159    Type * i8ptr = iBuilder->getInt8PtrTy();
160    unsigned numStreams = getType()->getArrayNumElements();
161    auto elemTy = getType()->getArrayElementType();
162    unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
163    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
164    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
165    Value * overFlowBlocks = iBuilder->CreateUDiv(overFlowItems, blockSize);
166    Value * partialItems = iBuilder->CreateURem(overFlowItems, blockSize);
167    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(overFlowBlocks, iBuilder->getSize(0)), wholeBlockCopy, partialBlockCopy);
168    iBuilder->SetInsertPoint(wholeBlockCopy);
169    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
170    Constant * blockBytes = iBuilder->getSize(fieldWidth * iBuilder->getBitBlockWidth()/8);
171    Value * copyLength = iBuilder->CreateMul(overFlowBlocks, blockBytes);
172    iBuilder->CreateMemMove(iBuilder->CreateBitCast(self, i8ptr), iBuilder->CreateBitCast(overFlowAreaPtr, i8ptr), copyLength, alignment);
173    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(partialItems, iBuilder->getSize(0)), partialBlockCopy, copyBackDone);
174    iBuilder->SetInsertPoint(partialBlockCopy);
175    Value * partialBlockTargetPtr = iBuilder->CreateGEP(self, overFlowBlocks);
176    Value * partialBlockSourcePtr = iBuilder->CreateGEP(overFlowAreaPtr, overFlowBlocks);
177    Value * copyBits = iBuilder->CreateMul(overFlowItems, iBuilder->getSize(fieldWidth));
178    Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
179    for (unsigned strm = 0; strm < numStreams; strm++) {
180        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
181        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
182        iBuilder->CreateMemMove(iBuilder->CreateBitCast(strmTargetPtr, i8ptr), iBuilder->CreateBitCast(strmSourcePtr, i8ptr), copyBytes, alignment);
183    }
184    iBuilder->CreateBr(copyBackDone);
185    iBuilder->SetInsertPoint(copyBackDone);
186}
187
188Value * CircularCopybackBuffer::getStreamSetBlockPtr(Value * self, Value * blockIndex) const {
189    return iBuilder->CreateGEP(self, modByBufferBlocks(blockIndex));
190}
191
192// Expandable Buffer
193
194void ExpandableBuffer::allocateBuffer() {
195    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType());
196    Value * const capacityPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
197    iBuilder->CreateStore(iBuilder->getSize(mInitialCapacity), capacityPtr);
198    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
199    ConstantInt * const size = iBuilder->getSize(mBufferBlocks * mInitialCapacity);
200    Value * const ptr = iBuilder->CreateAlignedMalloc(bufferType, size, iBuilder->getCacheAlignment());
201    const auto alignment = bufferType->getPrimitiveSizeInBits() / 8;
202    Constant * bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), size->getType(), false);
203    iBuilder->CreateMemZero(ptr, iBuilder->CreateMul(size, bufferWidth), alignment);
204    Value * const streamSetPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
205    iBuilder->CreateStore(ptr, streamSetPtr);
206}
207
208std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(llvm::Value * self, llvm::Value * streamIndex, Value * blockIndex, const bool readOnly) const {
209
210    // ENTRY
211    Value * const capacityPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
212    Value * const capacity = iBuilder->CreateLoad(capacityPtr);
213    Value * const streamSetPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
214    Value * const streamSet = iBuilder->CreateLoad(streamSetPtr);
215    blockIndex = modByBufferBlocks(blockIndex);
216
217    assert (streamIndex->getType() == capacity->getType());
218    Value * const cond = iBuilder->CreateICmpULT(streamIndex, capacity);
219
220    // Are we guaranteed that we can access this stream?
221    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
222        iBuilder->CreateAssert(cond, "ExpandableBuffer: out-of-bounds stream access");
223        Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, capacity), streamIndex);
224        return {streamSet, offset};
225    }
226
227    BasicBlock * const entry = iBuilder->GetInsertBlock();
228    BasicBlock * const expand = BasicBlock::Create(iBuilder->getContext(), "expand", entry->getParent());
229    BasicBlock * const resume = BasicBlock::Create(iBuilder->getContext(), "resume", entry->getParent());
230
231    iBuilder->CreateLikelyCondBr(cond, resume, expand);
232
233    // EXPAND
234    iBuilder->SetInsertPoint(expand);
235
236    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
237    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
238    Value * newCapacity = iBuilder->CreateMul(iBuilder->CreateAdd(streamIndex, iBuilder->getSize(1)), iBuilder->getSize(2), "newCapacity");
239
240    std::string tmp;
241    raw_string_ostream out(tmp);
242    out << "__expand";
243    elementType->print(out);
244    std::string name = out.str();
245
246    Module * const m = iBuilder->getModule();
247    Function * expandFunction = m->getFunction(name);
248
249    if (expandFunction == nullptr) {
250
251        const auto ip = iBuilder->saveIP();
252
253        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), iBuilder->getSizeTy(), iBuilder->getSizeTy()}, false);
254        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
255
256        auto args = expandFunction->arg_begin();
257        Value * streamSet = &*args++;
258        Value * capacity = &*args++;
259        Value * newCapacity = &*args;
260
261        BasicBlock * entry = BasicBlock::Create(iBuilder->getContext(), "entry", expandFunction);
262        iBuilder->SetInsertPoint(entry);
263
264        Value * size = iBuilder->CreateMul(newCapacity, iBuilder->getSize(mBufferBlocks));
265        Value * newStreamSet = iBuilder->CreateAlignedMalloc(elementType, size, iBuilder->getCacheAlignment());
266        Value * const diffCapacity = iBuilder->CreateMul(iBuilder->CreateSub(newCapacity, capacity), vectorWidth);
267
268        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
269        for (unsigned i = 0; i < mBufferBlocks; ++i) {
270            ConstantInt * const offset = iBuilder->getSize(i);
271            Value * srcOffset = iBuilder->CreateMul(capacity, offset);
272            Value * srcPtr = iBuilder->CreateGEP(streamSet, srcOffset);
273            Value * destOffset = iBuilder->CreateMul(newCapacity, offset);
274            Value * destPtr = iBuilder->CreateGEP(newStreamSet, destOffset);
275            iBuilder->CreateMemCpy(destPtr, srcPtr, iBuilder->CreateMul(capacity, vectorWidth), alignment);
276            Value * destZeroOffset = iBuilder->CreateAdd(destOffset, capacity);
277            Value * destZeroPtr = iBuilder->CreateGEP(newStreamSet, destZeroOffset);
278            iBuilder->CreateMemZero(destZeroPtr, diffCapacity, alignment);
279        }
280
281        iBuilder->CreateAlignedFree(streamSet);
282
283        iBuilder->CreateRet(newStreamSet);
284
285        iBuilder->restoreIP(ip);
286    }
287
288    Value * newStreamSet = iBuilder->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
289    iBuilder->CreateStore(newStreamSet, streamSetPtr);
290    iBuilder->CreateStore(newCapacity, capacityPtr);
291
292    iBuilder->CreateBr(resume);
293
294    // RESUME
295    iBuilder->SetInsertPoint(resume);
296
297    PHINode * phiStreamSet = iBuilder->CreatePHI(streamSet->getType(), 2);
298    phiStreamSet->addIncoming(streamSet, entry);
299    phiStreamSet->addIncoming(newStreamSet, expand);
300
301    PHINode * phiCapacity = iBuilder->CreatePHI(capacity->getType(), 2);
302    phiCapacity->addIncoming(capacity, entry);
303    phiCapacity->addIncoming(newCapacity, expand);
304
305    Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, phiCapacity), streamIndex);
306
307    return {phiStreamSet, offset};
308}
309
310llvm::Value * ExpandableBuffer::getStreamBlockPtr(llvm::Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
311    Value * ptr, * offset;
312    std::tie(ptr, offset) = getInternalStreamBuffer(self, streamIndex, blockIndex, readOnly);
313    return iBuilder->CreateGEP(ptr, offset);
314}
315
316llvm::Value * ExpandableBuffer::getStreamPackPtr(llvm::Value * self, llvm::Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
317    Value * ptr, * offset;
318    std::tie(ptr, offset) = getInternalStreamBuffer(self, streamIndex, blockIndex, readOnly);
319    return iBuilder->CreateGEP(ptr, {offset, packIndex});
320}
321
322llvm::Value * ExpandableBuffer::getStreamSetCount(llvm::Value * self) const {
323    return iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
324}
325
326Value * ExpandableBuffer::getStreamSetBlockPtr(Value *, Value *) const {
327    report_fatal_error("Expandable buffers: getStreamSetBlockPtr is not supported.");
328}
329
330Value * ExpandableBuffer::getLinearlyAccessibleItems(llvm::Value *) const {
331    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
332}
333
334// Constructors
335SingleBlockBuffer::SingleBlockBuffer(IDISA::IDISA_Builder * b, llvm::Type * type)
336: StreamSetBuffer(BufferKind::BlockBuffer, b, type, resolveStreamSetType(b, type), 1, 0) {
337
338}
339
340ExternalFileBuffer::ExternalFileBuffer(IDISA::IDISA_Builder * b, llvm::Type * type, unsigned AddressSpace)
341: StreamSetBuffer(BufferKind::ExternalFileBuffer, b, type, resolveStreamSetType(b, type), 0, AddressSpace) {
342
343}
344
345CircularBuffer::CircularBuffer(IDISA::IDISA_Builder * b, llvm::Type * type, size_t bufferBlocks, unsigned AddressSpace)
346: StreamSetBuffer(BufferKind::CircularBuffer, b, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
347
348}
349
350CircularCopybackBuffer::CircularCopybackBuffer(IDISA::IDISA_Builder * b, llvm::Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
351: StreamSetBuffer(BufferKind::CircularCopybackBuffer, b, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace), mOverflowBlocks(overflowBlocks) {
352
353}
354
355ExpandableBuffer::ExpandableBuffer(IDISA::IDISA_Builder * b, llvm::Type * type, size_t bufferBlocks, unsigned AddressSpace)
356: StreamSetBuffer(BufferKind::ExpandableBuffer, b, type, resolveExpandableStreamSetType(b, type), bufferBlocks, AddressSpace)
357, mInitialCapacity(type->getArrayNumElements()) {
358
359}
360
361inline StreamSetBuffer::StreamSetBuffer(BufferKind k, IDISA::IDISA_Builder * b, Type * baseType, Type * resolvedType, unsigned blocks, unsigned AddressSpace)
362: mBufferKind(k)
363, iBuilder(b)
364, mType(resolvedType)
365, mBufferBlocks(blocks)
366, mAddressSpace(AddressSpace)
367, mStreamSetBufferPtr(nullptr)
368, mBaseType(baseType) {
369
370}
371
372// Helper routines
373ArrayType * resolveStreamSetType(IDISA_Builder * const b, Type * type) {
374    unsigned numElements = 1;
375    if (LLVM_LIKELY(type->isArrayTy())) {
376        numElements = type->getArrayNumElements();
377        type = type->getArrayElementType();
378    }
379    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
380        type = type->getVectorElementType();
381        if (LLVM_LIKELY(type->isIntegerTy())) {
382            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
383            type = b->getBitBlockType();
384            if (fieldWidth != 1) {
385                type = ArrayType::get(type, fieldWidth);
386            }
387            return ArrayType::get(type, numElements);
388        }
389    }
390    std::string tmp;
391    raw_string_ostream out(tmp);
392    type->print(out);
393    out << " is an unvalid stream set buffer type.";
394    report_fatal_error(out.str());
395}
396
397StructType * resolveExpandableStreamSetType(IDISA_Builder * const b, Type * type) {
398    if (LLVM_LIKELY(type->isArrayTy())) {
399        type = type->getArrayElementType();
400    }
401    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
402        type = type->getVectorElementType();
403        if (LLVM_LIKELY(type->isIntegerTy())) {
404            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
405            type = b->getBitBlockType();
406            if (fieldWidth != 1) {
407                type = ArrayType::get(type, fieldWidth);
408            }
409            return StructType::get(b->getSizeTy(), type->getPointerTo(), nullptr);
410        }
411    }
412    std::string tmp;
413    raw_string_ostream out(tmp);
414    type->print(out);
415    out << " is an unvalid stream set buffer type.";
416    report_fatal_error(out.str());
417}
Note: See TracBrowser for help on using the repository browser.