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

Last change on this file since 5682 was 5678, checked in by cameron, 22 months ago

MatchAccumulator? modularization step

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