source: icGREP/icgrep-devel/icgrep/kernels/scanmatchgen.cpp @ 5941

Last change on this file since 5941 was 5892, checked in by cameron, 15 months ago

Restructuring: integrating grep_engine and grep_pipeline

File size: 13.4 KB
Line 
1/*
2 *  Copyright (c) 2015 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
6#include "scanmatchgen.h"
7#include <llvm/IR/Intrinsics.h>
8#include <llvm/IR/Module.h>
9#include <kernels/kernel_builder.h>
10#include <IR_Gen/FunctionTypeBuilder.h>
11#include <llvm/Support/raw_ostream.h>
12#include <grep/grep_engine.h>
13
14using namespace llvm;
15
16inline static unsigned floor_log2(const unsigned v) {
17    assert ("log2(0) is undefined!" && v != 0);
18    return 31 - __builtin_clz(v);
19}
20
21namespace kernel {
22
23void ScanMatchKernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> & iBuilder, Value * const numOfStrides) {
24
25    Module * const m = iBuilder->getModule();
26   
27    BasicBlock * const entryBlock = iBuilder->GetInsertBlock();
28    BasicBlock * const initialBlock = iBuilder->CreateBasicBlock("initialBlock");
29    BasicBlock * const scanWordIteration = iBuilder->CreateBasicBlock("ScanWordIteration");
30    BasicBlock * const matches_test_block = iBuilder->CreateBasicBlock("matches_test_block");
31    BasicBlock * const processMatchesEntry = iBuilder->CreateBasicBlock("process_matches_loop");
32    BasicBlock * const prior_breaks_block = iBuilder->CreateBasicBlock("prior_breaks_block");
33    BasicBlock * const loop_final_block = iBuilder->CreateBasicBlock("loop_final_block");
34    BasicBlock * const processMatchesExit = iBuilder->CreateBasicBlock("matches_done_block");
35    BasicBlock * const remaining_breaks_block = iBuilder->CreateBasicBlock("remaining_breaks_block");
36    BasicBlock * const return_block = iBuilder->CreateBasicBlock("return_block");
37    BasicBlock * const scanWordExit = iBuilder->CreateBasicBlock("ScanWordExit");
38    BasicBlock * const blocksExit = iBuilder->CreateBasicBlock("blocksExit");
39    BasicBlock * const callFinalizeScan = iBuilder->CreateBasicBlock("callFinalizeScan");
40    BasicBlock * const scanReturn = iBuilder->CreateBasicBlock("scanReturn");
41    IntegerType * const sizeTy = iBuilder->getSizeTy();
42    const unsigned fieldCount = iBuilder->getBitBlockWidth() / sizeTy->getBitWidth();
43    VectorType * const scanwordVectorType =  VectorType::get(sizeTy, fieldCount);
44    Constant * const ZERO = ConstantInt::getNullValue(sizeTy);
45
46    Value * match_result = iBuilder->getInputStreamBlockPtr("matchResult", iBuilder->getInt32(0));
47    Value * line_break = iBuilder->getInputStreamBlockPtr("lineBreak", iBuilder->getInt32(0));
48
49    Value * const blocksToDo = iBuilder->CreateMul(numOfStrides, iBuilder->getSize(mStride / iBuilder->getBitBlockWidth()));
50   
51    Value * match_result_ptr = iBuilder->CreateBitCast(match_result, scanwordVectorType->getPointerTo());
52    Value * line_break_ptr = iBuilder->CreateBitCast(line_break, scanwordVectorType->getPointerTo());
53    Value * accumulator = iBuilder->getScalarField("accumulator_address");
54
55    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToDo, iBuilder->getSize(0)), initialBlock, blocksExit);
56
57    iBuilder->SetInsertPoint(initialBlock);
58    PHINode * const blockBase = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
59    blockBase->addIncoming(iBuilder->getSize(0), entryBlock);
60    Value * const blockNo = iBuilder->getScalarField("BlockNo");
61    Value * const scanwordPos = iBuilder->CreateShl(blockNo, floor_log2(iBuilder->getBitBlockWidth()));
62    Value * const lastRecordStart = iBuilder->getProcessedItemCount("InputStream");
63    Value * const lastRecordNum = iBuilder->getScalarField("LineNum");
64    iBuilder->CreateBr(scanWordIteration);
65
66    iBuilder->SetInsertPoint(scanWordIteration);
67
68        // while (phiIndex < words per stride)
69        PHINode * const phiIndex = iBuilder->CreatePHI(iBuilder->getInt32Ty(), 2, "index");
70        phiIndex->addIncoming(iBuilder->getInt32(0), initialBlock);
71        PHINode * const phiScanwordPos = iBuilder->CreatePHI(scanwordPos->getType(), 2, "pos");
72        phiScanwordPos->addIncoming(scanwordPos, initialBlock);
73        PHINode * const phiLineStart = iBuilder->CreatePHI(lastRecordStart->getType(), 2, "recordstart");
74        phiLineStart->addIncoming(lastRecordStart, initialBlock);
75        PHINode * const phiLineNum = iBuilder->CreatePHI(lastRecordNum->getType(), 2, "recordnum");
76        phiLineNum->addIncoming(lastRecordNum, initialBlock);
77        Value * const matches = iBuilder->CreateLoad(iBuilder->CreateGEP(match_result_ptr, blockBase));
78        Value * const linebreaks = iBuilder->CreateLoad(iBuilder->CreateGEP(line_break_ptr, blockBase));
79        Value * const matchWord = iBuilder->CreateExtractElement(matches, phiIndex);
80        Value * const recordBreaks = iBuilder->CreateExtractElement(linebreaks, phiIndex);
81
82        // The match scanner works with a loop involving four variables:
83        // (a) the bit stream scanword of matches marking the ends of selected records,
84        // (b) the bit stream scanword of record_breaks marking the ends of all records,
85        // (c) the integer lastRecordNum indicating the number of records processed so far,
86        // (d) the index lastRecordStart indicating the file position of the last record.
87        // We set up a loop structure, in which a set of 4 phi nodes initialize these
88        // variables from either the input to the scanner or the computed values within
89        // the loop body.
90
91        iBuilder->CreateBr(matches_test_block);
92
93        // LOOP Test Block
94        iBuilder->SetInsertPoint(matches_test_block);
95        PHINode * phiMatchWord = iBuilder->CreatePHI(sizeTy, 2, "matches");
96        PHINode * phiRecordBreaks = iBuilder->CreatePHI(sizeTy, 2, "recordbreaks");
97        PHINode * phiRecordStart = iBuilder->CreatePHI(sizeTy, 2, "recordstart");
98        PHINode * phiRecordNum = iBuilder->CreatePHI(sizeTy, 2, "recordnum");
99        phiMatchWord->addIncoming(matchWord, scanWordIteration);
100        phiRecordBreaks->addIncoming(recordBreaks, scanWordIteration);
101        phiRecordNum->addIncoming(phiLineNum, scanWordIteration);
102        phiRecordStart->addIncoming(phiLineStart, scanWordIteration);
103        Value * anyMatches = iBuilder->CreateICmpNE(phiMatchWord, ZERO);
104        iBuilder->CreateCondBr(anyMatches, processMatchesEntry, processMatchesExit);
105
106            // LOOP BODY
107            // The loop body is entered if we have more matches to process.
108            iBuilder->SetInsertPoint(processMatchesEntry);
109            Value * prior_breaks = iBuilder->CreateAnd(iBuilder->CreateMaskToLowestBitExclusive(phiMatchWord), phiRecordBreaks);
110            // Within the loop we have a conditional block that is executed if there are any prior record breaks.
111            Value * prior_breaks_cond = iBuilder->CreateICmpNE(prior_breaks, ZERO);
112            iBuilder->CreateCondBr(prior_breaks_cond, prior_breaks_block, loop_final_block);
113
114                // PRIOR_BREAKS_BLOCK
115                // If there are prior breaks, we count them and compute the record start position.
116                iBuilder->SetInsertPoint(prior_breaks_block);
117                Value * matchedRecordNum = iBuilder->CreateAdd(iBuilder->CreatePopcount(prior_breaks), phiRecordNum);
118                Value * reverseDistance = iBuilder->CreateCountReverseZeroes(prior_breaks, true);
119                Value * width = ConstantInt::get(sizeTy, sizeTy->getBitWidth());
120                Value * priorRecordStart = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateSub(width, reverseDistance));               
121                iBuilder->CreateBr(loop_final_block);
122
123            // LOOP FINAL BLOCK
124            // The prior breaks, if any have been counted.  Set up phi nodes for the recordNum
125            // and recortStart depending on whether the conditional execution of prior_breaks_block.
126            iBuilder->SetInsertPoint(loop_final_block);
127            PHINode * matchRecordNum = iBuilder->CreatePHI(sizeTy, 2, "matchRecordNum");
128            matchRecordNum->addIncoming(phiRecordNum, processMatchesEntry);
129            matchRecordNum->addIncoming(matchedRecordNum, prior_breaks_block);
130            phiRecordNum->addIncoming(matchRecordNum, loop_final_block);
131
132            PHINode * const matchRecordStart = iBuilder->CreatePHI(sizeTy, 2, "matchRecordStart");
133            matchRecordStart->addIncoming(phiRecordStart, processMatchesEntry);
134            matchRecordStart->addIncoming(priorRecordStart, prior_breaks_block);
135            phiRecordStart->addIncoming(matchRecordStart, loop_final_block);
136            Value * matchRecordEnd = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateCountForwardZeroes(phiMatchWord, true));
137            // It is possible that the matchRecordEnd position is one past EOF.  Make sure not
138            // to access past EOF.
139            Value * bufLimit = iBuilder->CreateSub(iBuilder->getBufferedSize("InputStream"), ConstantInt::get(sizeTy, 1));
140            matchRecordEnd = iBuilder->CreateSelect(iBuilder->CreateICmpULT(matchRecordEnd, bufLimit), matchRecordEnd, bufLimit);
141            Function * const dispatcher = m->getFunction("accumulate_match_wrapper"); assert (dispatcher);
142            Value * const startPtr = iBuilder->getRawInputPointer("InputStream", matchRecordStart);
143            Value * const endPtr = iBuilder->getRawInputPointer("InputStream", matchRecordEnd);
144            const auto matchRecNumArg = ++dispatcher->getArgumentList().begin();
145            Value * const matchRecNum = iBuilder->CreateZExtOrTrunc(matchRecordNum, matchRecNumArg->getType());
146            iBuilder->CreateCall(dispatcher, {accumulator, matchRecNum, startPtr, endPtr});
147            Value * remaining_matches = iBuilder->CreateResetLowestBit(phiMatchWord);
148            phiMatchWord->addIncoming(remaining_matches, loop_final_block);
149
150            Value * remaining_breaks = iBuilder->CreateXor(phiRecordBreaks, prior_breaks);
151            phiRecordBreaks->addIncoming(remaining_breaks, loop_final_block);
152
153            iBuilder->CreateBr(matches_test_block);
154
155        // LOOP EXIT/MATCHES_DONE
156        iBuilder->SetInsertPoint(processMatchesExit);
157        // When the matches are done, there may be additional record breaks remaining
158        Value * more_breaks_cond = iBuilder->CreateICmpNE(phiRecordBreaks, ZERO);
159        iBuilder->CreateCondBr(more_breaks_cond, remaining_breaks_block, return_block);
160
161            // REMAINING_BREAKS_BLOCK: process remaining record breaks after all matches are processed
162            iBuilder->SetInsertPoint(remaining_breaks_block);
163            Value * break_count = iBuilder->CreatePopcount(phiRecordBreaks);
164            Value * final_record_num = iBuilder->CreateAdd(phiRecordNum, break_count);
165            Value * reverseZeroes = iBuilder->CreateCountReverseZeroes(phiRecordBreaks);
166            Value * pendingLineStart = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateSub(width, reverseZeroes));
167            iBuilder->CreateBr(return_block);
168
169        // RETURN block
170        iBuilder->SetInsertPoint(return_block);
171        PHINode * phiFinalRecordNum = iBuilder->CreatePHI(sizeTy, 2, "finalRecordCount");
172        PHINode * phiFinalRecordStart = iBuilder->CreatePHI(sizeTy, 2, "finalRecordStart");
173
174        phiFinalRecordNum->addIncoming(phiRecordNum, processMatchesExit);
175        phiFinalRecordNum->addIncoming(final_record_num, remaining_breaks_block);
176        phiLineNum->addIncoming(phiFinalRecordNum, return_block);
177
178        phiFinalRecordStart->addIncoming(phiRecordStart, processMatchesExit);
179        phiFinalRecordStart->addIncoming(pendingLineStart, remaining_breaks_block);
180        phiLineStart->addIncoming(phiFinalRecordStart, return_block);
181
182        Value * nextScanwordPos = iBuilder->CreateAdd(phiScanwordPos, ConstantInt::get(sizeTy, sizeTy->getBitWidth()));
183        phiScanwordPos->addIncoming(nextScanwordPos, return_block);
184        Value * nextIndex = iBuilder->CreateAdd(phiIndex, iBuilder->getInt32(1));
185        phiIndex->addIncoming(nextIndex, return_block);
186        iBuilder->CreateLikelyCondBr(iBuilder->CreateICmpNE(nextIndex, iBuilder->getInt32(fieldCount)), scanWordIteration, scanWordExit);
187
188    iBuilder->SetInsertPoint(scanWordExit);
189    iBuilder->setScalarField("BlockNo", iBuilder->CreateAdd(blockNo, ConstantInt::get(blockNo->getType(), 1)));
190    iBuilder->setScalarField("LineNum", phiFinalRecordNum);
191    iBuilder->setProcessedItemCount("InputStream", phiFinalRecordStart);
192    Value * blockBaseNext = iBuilder->CreateAdd(blockBase, ConstantInt::get(iBuilder->getSizeTy(), 1));
193    blockBase->addIncoming(blockBaseNext, scanWordExit);
194    iBuilder->CreateLikelyCondBr(iBuilder->CreateICmpNE(blockBaseNext, blocksToDo), initialBlock, blocksExit);
195
196    iBuilder->SetInsertPoint(blocksExit);
197    iBuilder->CreateCondBr(mIsFinal, callFinalizeScan, scanReturn);
198
199    iBuilder->SetInsertPoint(callFinalizeScan);
200    Value * bufSize = iBuilder->getBufferedSize("InputStream");
201    Function * finalizer = m->getFunction("finalize_match_wrapper"); assert (finalizer);
202    Value * const buffer_base = iBuilder->getRawInputPointer("InputStream", iBuilder->getInt32(0));
203    Value * buffer_end_address = iBuilder->CreateGEP(buffer_base, bufSize);
204    iBuilder->CreateCall(finalizer, {accumulator, buffer_end_address});
205    iBuilder->CreateBr(scanReturn);
206
207    iBuilder->SetInsertPoint(scanReturn);
208}
209
210ScanMatchKernel::ScanMatchKernel(const std::unique_ptr<kernel::KernelBuilder> & b)
211: MultiBlockKernel("scanMatch",
212// inputs
213{Binding{b->getStreamSetTy(1, 1), "matchResult", FixedRate(), Principal()}
214,Binding{b->getStreamSetTy(1, 1), "lineBreak"}
215,Binding{b->getStreamSetTy(1, 8), "InputStream", FixedRate(), Deferred()}},
216// outputs
217{},
218// input scalars
219{Binding{b->getIntAddrTy(), "accumulator_address"}},
220// output scalars
221{},
222// kernel state
223{Binding{b->getSizeTy(), "BlockNo"}
224,Binding{b->getSizeTy(), "LineNum"}}) {
225
226}
227
228}
Note: See TracBrowser for help on using the repository browser.