source: icGREP/icgrep-devel/icgrep/kernels/source_kernel.cpp @ 5431

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

partial refactoring check in with change for Linda.

File size: 16.2 KB
Line 
1/*
2 *  Copyright (c) 2017 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5#include "source_kernel.h"
6#include <llvm/IR/Module.h>
7#include <IR_Gen/idisa_builder.h>
8#include <kernels/streamset.h>
9#include <sys/stat.h>
10#include <fcntl.h>
11
12using namespace llvm;
13
14inline static size_t round_up_to_nearest(const size_t x, const size_t y) {
15    return (((x - 1) | (y - 1)) + 1);
16}
17
18uint64_t file_size(const uint32_t fd) {
19    struct stat st;
20    if (LLVM_UNLIKELY(fstat(fd, &st) != 0)) {
21        st.st_size = 0;
22    }
23    return st.st_size;
24}
25
26namespace kernel {
27
28/// MMAP SOURCE KERNEL
29
30void MMapSourceKernel::linkExternalMethods() {
31    mFileSizeFunction = iBuilder->LinkFunction("file_size", &file_size);
32}
33
34void MMapSourceKernel::generateInitializeMethod() {
35    BasicBlock * const emptyFile = CreateBasicBlock("EmptyFile");
36    BasicBlock * const nonEmptyFile = CreateBasicBlock("NonEmptyFile");
37    BasicBlock * const exit = CreateBasicBlock("Exit");
38    IntegerType * const sizeTy = iBuilder->getSizeTy();
39    Value * const fd = getScalarField("fileDescriptor");
40    assert (mFileSizeFunction);
41    Value * fileSize = iBuilder->CreateCall(mFileSizeFunction, fd);
42    fileSize = iBuilder->CreateZExtOrTrunc(fileSize, sizeTy);
43    if (mCodeUnitWidth > 8) {
44        fileSize = iBuilder->CreateUDiv(fileSize, iBuilder->getSize(mCodeUnitWidth / 8));
45    }
46    Value * const isEmpty = iBuilder->CreateICmpEQ(fileSize, ConstantInt::getNullValue(fileSize->getType()));
47    iBuilder->CreateUnlikelyCondBr(isEmpty, emptyFile, nonEmptyFile);
48    // we cannot mmap a 0 length file; just create a 1-page sized fake file buffer for simplicity
49    iBuilder->SetInsertPoint(emptyFile);
50    Constant * pageSize = iBuilder->getSize(getpagesize());
51    Value * fakeFileBuffer = iBuilder->CreateAnonymousMMap(pageSize);
52    iBuilder->CreateBr(exit);
53
54    iBuilder->SetInsertPoint(nonEmptyFile);
55    Value * fileBackedBuffer = iBuilder->CreateFileSourceMMap(fd, fileSize);
56    iBuilder->CreateBr(exit);
57
58    iBuilder->SetInsertPoint(exit);
59    PHINode * buffer = iBuilder->CreatePHI(fileBackedBuffer->getType(), 2);
60    buffer->addIncoming(fakeFileBuffer, emptyFile);
61    buffer->addIncoming(fileBackedBuffer, nonEmptyFile);
62    PHINode * size = iBuilder->CreatePHI(sizeTy, 2);
63    size->addIncoming(pageSize, emptyFile);
64    size->addIncoming(fileSize, nonEmptyFile);
65
66    setBaseAddress("sourceBuffer", buffer);
67    setBufferedSize("sourceBuffer", size);
68    setScalarField("readableBuffer", buffer);
69    setScalarField("fileSize", fileSize);
70    iBuilder->CreateMAdvise(buffer, fileSize, CBuilder::ADVICE_WILLNEED);
71
72}
73
74void MMapSourceKernel::generateDoSegmentMethod() {
75
76    BasicBlock * dropPages = CreateBasicBlock("dropPages");
77    BasicBlock * processSegment = CreateBasicBlock("produceData");
78    BasicBlock * setTermination = CreateBasicBlock("setTermination");
79    BasicBlock * mmapSourceExit = CreateBasicBlock("mmapSourceExit");
80
81    // instruct the OS that it can safely drop any fully consumed pages
82    Value * consumed = getConsumedItemCount("sourceBuffer");
83    Type * const consumedTy = consumed->getType();
84    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
85
86    // multiply the consumed count by the code unit size then mask off any partial pages
87    if (mCodeUnitWidth > 8) {
88        consumed = iBuilder->CreateMul(consumed, iBuilder->getSize(mCodeUnitWidth / 8));
89    }
90    const auto pageSize = getpagesize();
91    if (LLVM_LIKELY((pageSize & (pageSize - 1)) == 0)) {
92        consumed = iBuilder->CreateAnd(consumed, ConstantExpr::getNot(ConstantInt::get(consumedTy, pageSize - 1)));
93    } else {
94        consumed = iBuilder->CreateSub(consumed, iBuilder->CreateURem(consumed, ConstantInt::get(consumedTy, pageSize)));
95    }
96    Value * sourceBuffer = getBaseAddress("sourceBuffer");
97    sourceBuffer = iBuilder->CreatePtrToInt(sourceBuffer, consumedTy);
98    Value * consumedBuffer = iBuilder->CreateAdd(sourceBuffer, consumed);
99
100
101
102
103    Value * readableBuffer = getScalarField("readableBuffer");
104    readableBuffer = iBuilder->CreatePtrToInt(readableBuffer, consumedTy);
105    Value * unnecessaryBytes = iBuilder->CreateSub(consumedBuffer, readableBuffer);
106
107
108
109    // avoid calling madvise unless an actual page table change could occur
110    Value * hasPagesToDrop = iBuilder->CreateICmpEQ(unnecessaryBytes, ConstantInt::getNullValue(unnecessaryBytes->getType()));
111    iBuilder->CreateLikelyCondBr(hasPagesToDrop, processSegment, dropPages);
112
113    iBuilder->SetInsertPoint(dropPages);
114    iBuilder->CreateMAdvise(iBuilder->CreateIntToPtr(readableBuffer, voidPtrTy), unnecessaryBytes, CBuilder::ADVICE_DONTNEED);
115    readableBuffer = iBuilder->CreateIntToPtr(iBuilder->CreateAdd(readableBuffer, unnecessaryBytes), voidPtrTy);
116    setScalarField("readableBuffer", readableBuffer);
117    iBuilder->CreateBr(processSegment);
118
119    // determine whether or not we've exhausted the file buffer
120    iBuilder->SetInsertPoint(processSegment);
121    ConstantInt * segmentItems = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
122    Value * const fileSize = getScalarField("fileSize");
123    Value * const produced = iBuilder->CreateAdd(getProducedItemCount("sourceBuffer"), segmentItems);
124    Value * const lessThanFullSegment = iBuilder->CreateICmpULT(fileSize, produced);
125    iBuilder->CreateUnlikelyCondBr(lessThanFullSegment, setTermination, mmapSourceExit);
126    iBuilder->SetInsertPoint(setTermination);
127
128    setTerminationSignal();
129    iBuilder->CreateBr(mmapSourceExit);
130
131    // finally, set the "produced" count to reflect current position in the file
132    iBuilder->SetInsertPoint(mmapSourceExit);
133    PHINode * itemsRead = iBuilder->CreatePHI(produced->getType(), 2);
134    itemsRead->addIncoming(produced, processSegment);
135    itemsRead->addIncoming(fileSize, setTermination);
136    setProducedItemCount("sourceBuffer", itemsRead);
137}
138
139void MMapSourceKernel::generateFinalizeMethod() {
140    iBuilder->CreateMUnmap(getBaseAddress("sourceBuffer"), getBufferedSize("sourceBuffer"));
141}
142
143MMapSourceKernel::MMapSourceKernel(IDISA::IDISA_Builder * iBuilder, unsigned blocksPerSegment, unsigned codeUnitWidth)
144: SegmentOrientedKernel(iBuilder, "mmap_source" + std::to_string(blocksPerSegment) + "@" + std::to_string(codeUnitWidth),
145{},
146{Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}},
147{Binding{iBuilder->getInt32Ty(), "fileDescriptor"}},
148{Binding{iBuilder->getSizeTy(), "fileSize"}}, {Binding{iBuilder->getVoidPtrTy(), "readableBuffer"}})
149, mSegmentBlocks(blocksPerSegment)
150, mCodeUnitWidth(codeUnitWidth)
151, mFileSizeFunction(nullptr) {
152
153}
154
155/// READ SOURCE KERNEL
156
157void ReadSourceKernel::generateInitializeMethod() {
158    ConstantInt * const bufferSize = iBuilder->getSize(64 * getpagesize());
159    Value * const buffer = iBuilder->CreateAlignedMalloc(bufferSize, iBuilder->getCacheAlignment());
160    setScalarField("buffer", buffer);
161    setScalarField("capacity", bufferSize);
162    setBaseAddress("sourceBuffer", buffer);
163    setBufferedSize("sourceBuffer", iBuilder->getSize(0));
164}
165
166void ReadSourceKernel::generateDoSegmentMethod() {
167
168    ConstantInt * const pageSize = iBuilder->getSize(getpagesize());
169    PointerType * const codeUnitPtrTy = IntegerType::get(iBuilder->getContext(), mCodeUnitWidth)->getPointerTo();
170    BasicBlock * const entryBlock = iBuilder->GetInsertBlock();
171    BasicBlock * const exhaustedBuffer = CreateBasicBlock("ExhaustedBuffer");
172    BasicBlock * const waitOnConsumers = CreateBasicBlock("WaitOnConsumers");
173    BasicBlock * const readData = CreateBasicBlock("ReadData");
174    BasicBlock * const stdInExit = CreateBasicBlock("StdInExit");
175
176    // The ReadSourceKernel begins by checking whether it needs to read another page of data
177    ConstantInt * const segmentSize = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
178    Value * bufferedSize = getBufferedSize("sourceBuffer");
179    Value * const produced = getProducedItemCount("sourceBuffer");
180    Value * unreadSize = iBuilder->CreateSub(bufferedSize, produced);
181    iBuilder->CreateUnlikelyCondBr(iBuilder->CreateICmpULT(unreadSize, segmentSize), exhaustedBuffer, stdInExit);
182
183    // If so, it checks whether it can simply append another page to the existing buffer or whether
184    // we need to perform a copyback.
185
186    iBuilder->SetInsertPoint(exhaustedBuffer);
187
188    // Otherwise, we're going to have to perform a copy back...
189
190    // Let L be the logical buffer address (i.e., the position of the "first byte" of the input stream)
191    // and B be the address pointing to the beginning of our actual buffer. Check whether:
192
193    //     L + produced + pagesize < B + capacity
194
195    // If so, we can append to our existing buffer without impacting any subsequent kernel.
196
197    Value * inputStream = getRawOutputPointer("sourceBuffer", iBuilder->getInt32(0), iBuilder->getInt32(0));
198    inputStream = iBuilder->CreatePointerCast(inputStream, codeUnitPtrTy);
199    Value * const originalPtr = iBuilder->CreateGEP(inputStream, produced);
200    Value * const buffer = iBuilder->CreatePointerCast(getScalarField("buffer"), codeUnitPtrTy);
201    Value * const capacity = getScalarField("capacity");
202    Value * const canAppend = iBuilder->CreateICmpULT(iBuilder->CreateGEP(originalPtr, pageSize), iBuilder->CreateGEP(buffer, capacity));
203    iBuilder->CreateLikelyCondBr(canAppend, readData, waitOnConsumers);
204
205    // First wait on any consumers to finish processing then check how much data has been consumed.
206    iBuilder->SetInsertPoint(waitOnConsumers);
207    CreateWaitForConsumers();
208    // Then determine how much data has been consumed and how much needs to be copied back, noting
209    // that our "unproduced" data must be block aligned.
210    const auto alignment = iBuilder->getBitBlockWidth() / 8;
211    Constant * const alignmentMask = ConstantExpr::getNeg(iBuilder->getSize(alignment));
212    Value * const consumed = iBuilder->CreateAnd(getConsumedItemCount("sourceBuffer"), alignmentMask);
213    Value * const remaining = iBuilder->CreateSub(bufferedSize, consumed);
214    Value * const unconsumedPtr = iBuilder->CreateGEP(inputStream, consumed);
215    Value * const consumedMajority = iBuilder->CreateICmpULT(iBuilder->CreateGEP(buffer, remaining), unconsumedPtr);
216    BasicBlock * const copyBack = CreateBasicBlock("CopyBack");
217    BasicBlock * const expandAndCopyBack = CreateBasicBlock("ExpandAndCopyBack");
218    BasicBlock * const calculateLogicalAddress = CreateBasicBlock("CalculateLogicalAddress");
219    // Have we consumed enough data that we can safely copy back the unconsumed data without needing
220    // a temporary buffer? (i.e., B + remaining < L + consumed)
221    iBuilder->CreateLikelyCondBr(consumedMajority, copyBack, expandAndCopyBack);
222    iBuilder->SetInsertPoint(copyBack);
223    // If so, just copy the data ...
224    iBuilder->CreateMemCpy(buffer, unconsumedPtr, remaining, alignment);
225    iBuilder->CreateBr(calculateLogicalAddress);
226    // Otherwise, allocate a buffer with twice the capacity and copy the unconsumed data back into it
227    iBuilder->SetInsertPoint(expandAndCopyBack);
228    Value * const expandedCapacity = iBuilder->CreateShl(capacity, 1);
229    Value * const expandedBuffer = iBuilder->CreateAlignedMalloc(expandedCapacity, iBuilder->getCacheAlignment());
230    Value * const expandedPtr = iBuilder->CreatePointerCast(expandedBuffer, codeUnitPtrTy);
231    iBuilder->CreateMemCpy(expandedPtr, unconsumedPtr, remaining, alignment);
232    iBuilder->CreateAlignedFree(buffer);
233    setScalarField("buffer", expandedBuffer);
234    setScalarField("capacity", expandedCapacity);   
235    iBuilder->CreateBr(calculateLogicalAddress);
236    // Update the logical address for this buffer....
237    iBuilder->SetInsertPoint(calculateLogicalAddress);
238    PHINode * const baseAddress = iBuilder->CreatePHI(codeUnitPtrTy, 2);
239    baseAddress->addIncoming(buffer, copyBack);
240    baseAddress->addIncoming(expandedPtr, expandAndCopyBack);
241    Value * const modifiedPtr = iBuilder->CreateGEP(baseAddress, remaining);
242    Value * const logicalAddress = iBuilder->CreateGEP(modifiedPtr, iBuilder->CreateNeg(produced));
243    setBaseAddress("sourceBuffer", logicalAddress);
244    iBuilder->CreateBr(readData);
245    // Regardless of whether we're simply appending data or had to allocate a new buffer, read a new page
246    // of data into the input source buffer. If we fail to read a full segment ...
247    readData->moveAfter(calculateLogicalAddress);
248    iBuilder->SetInsertPoint(readData);
249    calculateLogicalAddress->moveAfter(calculateLogicalAddress);
250    PHINode * const addr = iBuilder->CreatePHI(codeUnitPtrTy, 2);
251    addr->addIncoming(originalPtr, exhaustedBuffer);
252    addr->addIncoming(modifiedPtr, calculateLogicalAddress);
253    Value * bytesRead = iBuilder->CreateReadCall(getScalarField("fileDescriptor"), addr, pageSize);
254    unreadSize = iBuilder->CreateAdd(unreadSize, bytesRead);
255    bufferedSize = iBuilder->CreateAdd(bufferedSize, bytesRead);
256    setBufferedSize("sourceBuffer", bufferedSize);
257    Value * const exhaustedInputSource = iBuilder->CreateICmpULT(unreadSize, segmentSize);
258    BasicBlock * const setTermination = CreateBasicBlock("SetTermination");
259    iBuilder->CreateUnlikelyCondBr(exhaustedInputSource, setTermination, stdInExit);
260
261    // ... zero out the remaining bytes and set the termination signal.
262    iBuilder->SetInsertPoint(setTermination);
263    Value * const bytesToZero = iBuilder->CreateSub(segmentSize, unreadSize);
264    iBuilder->CreateMemZero(iBuilder->CreateGEP(addr, unreadSize), bytesToZero);
265    setTerminationSignal();
266    iBuilder->CreateBr(stdInExit);
267
268    // finally add the segment item count to the produced item count to inform the subsequent kernels how
269    // much data is available for processing
270    iBuilder->SetInsertPoint(stdInExit);
271    stdInExit->moveAfter(setTermination);
272    PHINode * const items = iBuilder->CreatePHI(produced->getType(), 3);
273    items->addIncoming(segmentSize, entryBlock);
274    items->addIncoming(segmentSize, readData);
275    items->addIncoming(unreadSize, setTermination);
276    setProducedItemCount("sourceBuffer", iBuilder->CreateAdd(produced, items));
277}
278
279void ReadSourceKernel::generateFinalizeMethod() {
280    iBuilder->CreateAlignedFree(getScalarField("buffer"));
281}
282
283ReadSourceKernel::ReadSourceKernel(IDISA::IDISA_Builder * iBuilder, unsigned blocksPerSegment, unsigned codeUnitWidth)
284: SegmentOrientedKernel(iBuilder, "read_source"
285, {}
286, {Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}}
287, {Binding{iBuilder->getInt32Ty(), "fileDescriptor"}}
288, {}
289, {Binding{iBuilder->getVoidPtrTy(), "buffer"}, Binding{iBuilder->getSizeTy(), "capacity"}})
290, mSegmentBlocks(blocksPerSegment)
291, mCodeUnitWidth(codeUnitWidth) {
292
293}
294
295/// MEMORY SOURCE KERNEL
296
297void MemorySourceKernel::generateInitializeMethod() {
298    setBaseAddress("sourceBuffer", iBuilder->CreatePointerCast(getScalarField("fileSource"), iBuilder->getVoidPtrTy()));
299    setBufferedSize("sourceBuffer", getScalarField("fileSize"));
300}
301
302void MemorySourceKernel::generateDoSegmentMethod() {
303
304    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
305    BasicBlock * setTermination = CreateBasicBlock("setTermination");
306    BasicBlock * mmapSourceExit = CreateBasicBlock("sourceExit");
307    ConstantInt * segmentItems = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
308    Value * fileItems = getScalarField("fileSize");
309    if (mCodeUnitWidth > 8) {
310        fileItems = iBuilder->CreateUDiv(fileItems, iBuilder->getSize(mCodeUnitWidth / 8));
311    }
312    Value * produced = getProducedItemCount("sourceBuffer");
313    produced = iBuilder->CreateAdd(produced, segmentItems);
314    Value * lessThanFullSegment = iBuilder->CreateICmpULT(fileItems, produced);
315    iBuilder->CreateCondBr(lessThanFullSegment, setTermination, mmapSourceExit);
316    iBuilder->SetInsertPoint(setTermination);
317    setTerminationSignal();
318    iBuilder->CreateBr(mmapSourceExit);
319
320    iBuilder->SetInsertPoint(mmapSourceExit);
321
322    PHINode * itemsRead = iBuilder->CreatePHI(produced->getType(), 2);
323    itemsRead->addIncoming(produced, entryBlock);
324    itemsRead->addIncoming(fileItems, setTermination);
325    setProducedItemCount("sourceBuffer", itemsRead);
326}
327
328MemorySourceKernel::MemorySourceKernel(IDISA::IDISA_Builder * iBuilder, Type * type, unsigned blocksPerSegment, unsigned codeUnitWidth)
329: SegmentOrientedKernel(iBuilder, "memory_source",
330    {},
331    {Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}},
332    {Binding{cast<PointerType>(type), "fileSource"}, Binding{iBuilder->getSizeTy(), "fileSize"}}, {}, {})
333, mSegmentBlocks(blocksPerSegment)
334, mCodeUnitWidth(codeUnitWidth) {
335
336}
337
338}
Note: See TracBrowser for help on using the repository browser.