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

Last change on this file since 5694 was 5694, checked in by cameron, 21 months ago

Update scanmatch callback protocol to use line start/end pointers; add finalize callback for buffer end

File size: 15.3 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_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
23inline std::string getGrepTypeId(const GrepType grepType) {
24    switch (grepType) {
25        case GrepType::Normal:
26            return "N";
27        case GrepType::NameExpression:
28            return "E";
29        case GrepType::PropertyValue:
30            return "P";
31        case GrepType::CallBack:
32            return "C";
33        default:
34            llvm_unreachable("unknown grep type!");
35    }
36}
37   
38void ScanMatchKernel::generateMultiBlockLogic(const std::unique_ptr<KernelBuilder> &iBuilder) {
39
40    Module * const m = iBuilder->getModule();
41   
42    BasicBlock * const entryBlock = iBuilder->GetInsertBlock();
43    BasicBlock * const initialBlock = iBuilder->CreateBasicBlock("initialBlock");
44    BasicBlock * const scanWordIteration = iBuilder->CreateBasicBlock("ScanWordIteration");
45    BasicBlock * const matches_test_block = iBuilder->CreateBasicBlock("matches_test_block");
46    BasicBlock * const processMatchesEntry = iBuilder->CreateBasicBlock("process_matches_loop");
47    BasicBlock * const prior_breaks_block = iBuilder->CreateBasicBlock("prior_breaks_block");
48    BasicBlock * const loop_final_block = iBuilder->CreateBasicBlock("loop_final_block");
49    BasicBlock * const processMatchesExit = iBuilder->CreateBasicBlock("matches_done_block");
50    BasicBlock * const remaining_breaks_block = iBuilder->CreateBasicBlock("remaining_breaks_block");
51    BasicBlock * const return_block = iBuilder->CreateBasicBlock("return_block");
52    BasicBlock * const scanWordExit = iBuilder->CreateBasicBlock("ScanWordExit");
53    BasicBlock * const blocksExit = iBuilder->CreateBasicBlock("blocksExit");
54    BasicBlock * const callFinalizeScan = iBuilder->CreateBasicBlock("callFinalizeScan");
55    BasicBlock * const scanReturn = iBuilder->CreateBasicBlock("scanReturn");
56    IntegerType * const sizeTy = iBuilder->getSizeTy();
57    const unsigned fieldCount = iBuilder->getBitBlockWidth() / sizeTy->getBitWidth();
58    VectorType * const scanwordVectorType =  VectorType::get(sizeTy, fieldCount);
59    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
60
61    Function::arg_iterator args = mCurrentMethod->arg_begin();
62    /* self = */ args++;
63    Value * itemsToDo = &*(args++);
64    /* inputStreamAvail = */ args++;
65    Value * match_result = &*(args++);
66    Value * line_break = &*(args++);
67    /* input_stream = */ args++;
68
69    Value * blocksToDo = iBuilder->CreateUDivCeil(itemsToDo, blockSize);
70   
71    Value * match_result_ptr = iBuilder->CreateBitCast(match_result, scanwordVectorType->getPointerTo());
72    Value * line_break_ptr = iBuilder->CreateBitCast(line_break, scanwordVectorType->getPointerTo());
73
74    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToDo, iBuilder->getSize(0)), initialBlock, blocksExit);
75
76    iBuilder->SetInsertPoint(initialBlock);
77    PHINode * const blockBase = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
78    blockBase->addIncoming(iBuilder->getSize(0), entryBlock);
79    Value * const blockNo = iBuilder->getScalarField("BlockNo");
80    Value * const scanwordPos = iBuilder->CreateShl(blockNo, floor_log2(iBuilder->getBitBlockWidth()));
81    Value * const lastRecordStart = iBuilder->getProcessedItemCount("InputStream");
82    Value * const lastRecordNum = iBuilder->getScalarField("LineNum");
83    iBuilder->CreateBr(scanWordIteration);
84
85    iBuilder->SetInsertPoint(scanWordIteration);
86
87        // while (phiIndex < words per stride)
88        PHINode * const phiIndex = iBuilder->CreatePHI(iBuilder->getInt32Ty(), 2, "index");
89        phiIndex->addIncoming(iBuilder->getInt32(0), initialBlock);
90        PHINode * const phiScanwordPos = iBuilder->CreatePHI(scanwordPos->getType(), 2, "pos");
91        phiScanwordPos->addIncoming(scanwordPos, initialBlock);
92        PHINode * const phiLineStart = iBuilder->CreatePHI(lastRecordStart->getType(), 2, "recordstart");
93        phiLineStart->addIncoming(lastRecordStart, initialBlock);
94        PHINode * const phiLineNum = iBuilder->CreatePHI(lastRecordNum->getType(), 2, "recordnum");
95        phiLineNum->addIncoming(lastRecordNum, initialBlock);
96        Value * const matches = iBuilder->CreateLoad(iBuilder->CreateGEP(match_result_ptr, blockBase));
97        Value * const linebreaks = iBuilder->CreateLoad(iBuilder->CreateGEP(line_break_ptr, blockBase));
98        Value * const matchWord = iBuilder->CreateExtractElement(matches, phiIndex);
99        Value * const recordBreaks = iBuilder->CreateExtractElement(linebreaks, phiIndex);
100
101        // The match scanner works with a loop involving four variables:
102        // (a) the bit stream scanword of matches marking the ends of selected records,
103        // (b) the bit stream scanword of record_breaks marking the ends of all records,
104        // (c) the integer lastRecordNum indicating the number of records processed so far,
105        // (d) the index lastRecordStart indicating the file position of the last record.
106        // We set up a loop structure, in which a set of 4 phi nodes initialize these
107        // variables from either the input to the scanner or the computed values within
108        // the loop body.
109
110        iBuilder->CreateBr(matches_test_block);
111
112        // LOOP Test Block
113        iBuilder->SetInsertPoint(matches_test_block);
114        PHINode * phiMatchWord = iBuilder->CreatePHI(sizeTy, 2, "matches");
115        PHINode * phiRecordBreaks = iBuilder->CreatePHI(sizeTy, 2, "recordbreaks");
116        PHINode * phiRecordStart = iBuilder->CreatePHI(sizeTy, 2, "recordstart");
117        PHINode * phiRecordNum = iBuilder->CreatePHI(sizeTy, 2, "recordnum");
118        phiMatchWord->addIncoming(matchWord, scanWordIteration);
119        phiRecordBreaks->addIncoming(recordBreaks, scanWordIteration);
120        phiRecordNum->addIncoming(phiLineNum, scanWordIteration);
121        phiRecordStart->addIncoming(phiLineStart, scanWordIteration);
122        Value * anyMatches = iBuilder->CreateICmpNE(phiMatchWord, ConstantInt::getNullValue(sizeTy));
123        iBuilder->CreateCondBr(anyMatches, processMatchesEntry, processMatchesExit);
124
125            // LOOP BODY
126            // The loop body is entered if we have more matches to process.
127            iBuilder->SetInsertPoint(processMatchesEntry);
128            Value * prior_breaks = iBuilder->CreateAnd(iBuilder->CreateMaskToLowestBitExclusive(phiMatchWord), phiRecordBreaks);
129            // Within the loop we have a conditional block that is executed if there are any prior record breaks.
130            Value * prior_breaks_cond = iBuilder->CreateICmpNE(prior_breaks, ConstantInt::getNullValue(sizeTy));
131            iBuilder->CreateCondBr(prior_breaks_cond, prior_breaks_block, loop_final_block);
132
133                // PRIOR_BREAKS_BLOCK
134                // If there are prior breaks, we count them and compute the record start position.
135                iBuilder->SetInsertPoint(prior_breaks_block);
136                Value * matchedRecordNum = iBuilder->CreateAdd(iBuilder->CreatePopcount(prior_breaks), phiRecordNum);
137                Value * reverseDistance = iBuilder->CreateCountReverseZeroes(prior_breaks);
138                Value * width = ConstantInt::get(sizeTy, sizeTy->getBitWidth());
139                Value * priorRecordStart = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateSub(width, reverseDistance));
140                iBuilder->CreateBr(loop_final_block);
141
142            // LOOP FINAL BLOCK
143            // The prior breaks, if any have been counted.  Set up phi nodes for the recordNum
144            // and recortStart depending on whether the conditional execution of prior_breaks_block.
145            iBuilder->SetInsertPoint(loop_final_block);
146            PHINode * matchRecordNum = iBuilder->CreatePHI(sizeTy, 2, "matchRecordNum");
147            matchRecordNum->addIncoming(phiRecordNum, processMatchesEntry);
148            matchRecordNum->addIncoming(matchedRecordNum, prior_breaks_block);
149            phiRecordNum->addIncoming(matchRecordNum, loop_final_block);
150
151            PHINode * matchRecordStart = iBuilder->CreatePHI(sizeTy, 2, "matchRecordStart");
152            matchRecordStart->addIncoming(phiRecordStart, processMatchesEntry);
153            matchRecordStart->addIncoming(priorRecordStart, prior_breaks_block);
154            phiRecordStart->addIncoming(matchRecordStart, loop_final_block);
155            Value * matchRecordEnd = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateCountForwardZeroes(phiMatchWord));
156            if (mGrepType == GrepType::CallBack) {
157                Value * const inputStream = iBuilder->getRawInputPointer("InputStream", iBuilder->getInt32(0), iBuilder->getInt32(0));
158                Function * dispatcher = m->getFunction("accumulate_match_wrapper"); assert (dispatcher);
159                //Function * dispatcher = iBuilder->LinkFunction<void (intptr_t, size_t, size_t, size_t)>("accumulate_match_wrapper", & grep::accumulate_match_wrapper);
160                Value * accumulator = iBuilder->getScalarField("accumulator_address");
161                Value * start_ptr = iBuilder->CreateGEP(inputStream, matchRecordStart);
162                Value * end_ptr = iBuilder->CreateGEP(inputStream, matchRecordEnd);
163                iBuilder->CreateCall(dispatcher, {accumulator, matchRecordNum, start_ptr, end_ptr});
164            }
165            else {
166                Function * matcher = m->getFunction("matcher"); assert (matcher);
167                auto args_matcher = matcher->arg_begin();
168                Value * const mrn = iBuilder->CreateZExtOrTrunc(matchRecordNum, args_matcher->getType());
169                Value * const mrs = iBuilder->CreateZExtOrTrunc(matchRecordStart, (++args_matcher)->getType());
170                Value * const mre = iBuilder->CreateZExtOrTrunc(matchRecordEnd, (++args_matcher)->getType());
171                Value * const inputStream = iBuilder->getRawInputPointer("InputStream", iBuilder->getInt32(0), iBuilder->getInt32(0));
172                Value * const is = iBuilder->CreatePointerCast(inputStream, (++args_matcher)->getType());
173                if (mGrepType == GrepType::Normal) {
174                    Value * const sz = iBuilder->CreateZExtOrTrunc(iBuilder->getBufferedSize("InputStream"), (++args_matcher)->getType());
175                    Value * const fi = iBuilder->CreateZExtOrTrunc(iBuilder->getScalarField("FileIdx"), (++args_matcher)->getType());
176                    iBuilder->CreateCall(matcher, {mrn, mrs, mre, is, sz, fi});
177                } else {
178                    iBuilder->CreateCall(matcher, {mrn, mrs, mre, is});
179                }
180            }
181            Value * remaining_matches = iBuilder->CreateResetLowestBit(phiMatchWord);
182            phiMatchWord->addIncoming(remaining_matches, loop_final_block);
183
184            Value * remaining_breaks = iBuilder->CreateXor(phiRecordBreaks, prior_breaks);
185            phiRecordBreaks->addIncoming(remaining_breaks, loop_final_block);
186
187            iBuilder->CreateBr(matches_test_block);
188
189        // LOOP EXIT/MATCHES_DONE
190        iBuilder->SetInsertPoint(processMatchesExit);
191        // When the matches are done, there may be additional record breaks remaining
192        Value * more_breaks_cond = iBuilder->CreateICmpNE(phiRecordBreaks, ConstantInt::getNullValue(sizeTy));
193        iBuilder->CreateCondBr(more_breaks_cond, remaining_breaks_block, return_block);
194
195            // REMAINING_BREAKS_BLOCK: process remaining record breaks after all matches are processed
196            iBuilder->SetInsertPoint(remaining_breaks_block);
197            Value * break_count = iBuilder->CreatePopcount(phiRecordBreaks);
198            Value * final_record_num = iBuilder->CreateAdd(phiRecordNum, break_count);
199            Value * reverseZeroes = iBuilder->CreateCountReverseZeroes(phiRecordBreaks);
200            Value * pendingLineStart = iBuilder->CreateAdd(phiScanwordPos, iBuilder->CreateSub(width, reverseZeroes));
201            iBuilder->CreateBr(return_block);
202
203        // RETURN block
204        iBuilder->SetInsertPoint(return_block);
205        PHINode * phiFinalRecordNum = iBuilder->CreatePHI(sizeTy, 2, "finalRecordCount");
206        PHINode * phiFinalRecordStart = iBuilder->CreatePHI(sizeTy, 2, "finalRecordStart");
207
208        phiFinalRecordNum->addIncoming(phiRecordNum, processMatchesExit);
209        phiFinalRecordNum->addIncoming(final_record_num, remaining_breaks_block);
210        phiLineNum->addIncoming(phiFinalRecordNum, return_block);
211
212        phiFinalRecordStart->addIncoming(phiRecordStart, processMatchesExit);
213        phiFinalRecordStart->addIncoming(pendingLineStart, remaining_breaks_block);
214        phiLineStart->addIncoming(phiFinalRecordStart, return_block);
215
216        Value * nextScanwordPos = iBuilder->CreateAdd(phiScanwordPos, ConstantInt::get(sizeTy, sizeTy->getBitWidth()));
217        phiScanwordPos->addIncoming(nextScanwordPos, return_block);
218        Value * nextIndex = iBuilder->CreateAdd(phiIndex, iBuilder->getInt32(1));
219        phiIndex->addIncoming(nextIndex, return_block);
220        iBuilder->CreateLikelyCondBr(iBuilder->CreateICmpNE(nextIndex, iBuilder->getInt32(fieldCount)), scanWordIteration, scanWordExit);
221
222    iBuilder->SetInsertPoint(scanWordExit);
223    iBuilder->setScalarField("BlockNo", iBuilder->CreateAdd(blockNo, ConstantInt::get(blockNo->getType(), 1)));
224    iBuilder->setScalarField("LineNum", phiFinalRecordNum);
225    iBuilder->setProcessedItemCount("InputStream", phiFinalRecordStart);
226    Value * blockBaseNext = iBuilder->CreateAdd(blockBase, ConstantInt::get(iBuilder->getSizeTy(), 1));
227    blockBase->addIncoming(blockBaseNext, scanWordExit);
228    iBuilder->CreateLikelyCondBr(iBuilder->CreateICmpNE(blockBaseNext, blocksToDo), initialBlock, blocksExit);
229
230    iBuilder->SetInsertPoint(blocksExit);
231    iBuilder->CreateCondBr(iBuilder->CreateICmpULT(itemsToDo, blockSize), callFinalizeScan, scanReturn);
232    iBuilder->SetInsertPoint(callFinalizeScan);
233    if (mGrepType == GrepType::CallBack) {
234        Value * bufSize = iBuilder->getBufferedSize("InputStream");
235        Function * finalizer = m->getFunction("finalize_match_wrapper"); assert (finalizer);
236        Value * accumulator = iBuilder->getScalarField("accumulator_address");
237        Value * const buffer_base = iBuilder->getRawInputPointer("InputStream", iBuilder->getInt32(0), iBuilder->getInt32(0));
238        Value * buffer_end_address = iBuilder->CreateGEP(buffer_base, bufSize);
239        iBuilder->CreateCall(finalizer, {accumulator, buffer_end_address});
240    }
241    iBuilder->CreateBr(scanReturn);
242    iBuilder->SetInsertPoint(scanReturn);
243   
244}
245
246ScanMatchKernel::ScanMatchKernel(const std::unique_ptr<kernel::KernelBuilder> & b, GrepType grepType, const unsigned codeUnitWidth)
247: MultiBlockKernel("scanMatch" + getGrepTypeId(grepType) + std::to_string(codeUnitWidth),
248    {Binding{b->getStreamSetTy(1, 1), "matchResult"}, Binding{b->getStreamSetTy(1, 1), "lineBreak"}, Binding{b->getStreamSetTy(1, 8), "InputStream", UnknownRate()}},
249    {},
250    {},
251    {},
252    {Binding{b->getSizeTy(), "BlockNo"}, Binding{b->getSizeTy(), "LineNum"}})
253, mGrepType(grepType) {
254    if (mGrepType == GrepType::CallBack) {
255        mScalarInputs.push_back(Binding{b->getIntAddrTy(), "accumulator_address"});
256    }
257    else {
258        mScalarInputs.push_back(Binding{b->getInt32Ty(), "FileIdx"});
259    }
260}
261
262}
Note: See TracBrowser for help on using the repository browser.