source: icGREP/icgrep-devel/icgrep/grep_engine.cpp @ 5771

Last change on this file since 5771 was 5771, checked in by nmedfort, 15 months ago

Minor changes and hopefully a fix for bug exposed by base64 test

File size: 18.4 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 *  icgrep is a trademark of International Characters.
5 */
6
7#include "grep_engine.h"
8#include "grep_interface.h"
9#include <llvm/IR/Module.h>
10#include <boost/filesystem.hpp>
11#include <UCD/resolve_properties.h>
12#include <kernels/charclasses.h>
13#include <kernels/cc_kernel.h>
14#include <kernels/grep_kernel.h>
15#include <kernels/linebreak_kernel.h>
16#include <kernels/streams_merge.h>
17#include <kernels/source_kernel.h>
18#include <kernels/s2p_kernel.h>
19#include <kernels/scanmatchgen.h>
20#include <kernels/streamset.h>
21#include <kernels/until_n.h>
22#include <kernels/kernel_builder.h>
23#include <pablo/pablo_kernel.h>
24#include <re/re_cc.h>
25#include <re/casing.h>
26#include <re/re_toolchain.h>
27#include <toolchain/toolchain.h>
28#include <re/re_name_resolve.h>
29#include <re/re_collect_unicodesets.h>
30#include <re/re_multiplex.h>
31#include <toolchain/toolchain.h>
32#include <toolchain/cpudriver.h>
33#include <iostream>
34#include <cc/multiplex_CCs.h>
35#include <llvm/Support/raw_ostream.h>
36#include <util/aligned_allocator.h>
37#include <sys/stat.h>
38#include <fcntl.h>
39#include <errno.h>
40#include <llvm/ADT/STLExtras.h> // for make_unique
41#include <llvm/Support/CommandLine.h>
42#include <llvm/Support/Debug.h>
43#include <sched.h>
44
45using namespace parabix;
46using namespace llvm;
47static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
48
49namespace grep {
50
51// Grep Engine construction and initialization.
52
53GrepEngine::GrepEngine() :
54    mGrepDriver(nullptr),
55    mNextFileToGrep(0),
56    mNextFileToPrint(0),
57    grepMatchFound(false),
58    mMoveMatchesToEOL(true),
59    mEngineThread(pthread_self()) {}
60
61GrepEngine::~GrepEngine() {
62    delete mGrepDriver;
63}
64
65QuietModeEngine::QuietModeEngine() : GrepEngine() {
66    mMoveMatchesToEOL = false;
67}
68
69MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch) :
70    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
71    mFileSuffix = NullFlag ? std::string("\0", 1) : "\n";
72    mMoveMatchesToEOL = false;
73}
74
75CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
76    mFileSuffix = ":";
77}
78
79EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
80    mFileSuffix = InitialTabFlag ? "\t:" : ":";
81    if (LineRegexpFlag) mMoveMatchesToEOL = false;
82}
83
84void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
85    const unsigned n = filenames.size();
86    mResultStrs.resize(n);
87    mFileStatus.resize(n, FileStatus::Pending);
88    inputFiles = filenames;
89}
90
91// Code Generation
92//
93// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
94
95std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(std::vector<re::RE *> & REs, StreamSetBuffer * ByteStream) {
96    auto & idb = mGrepDriver->getBuilder();
97    const unsigned segmentSize = codegen::SegmentSize;
98    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
99    const unsigned encodingBits = 8;
100
101    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), segmentSize * bufferSegments);
102    kernel::Kernel * s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
103    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
104
105    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
106    kernel::Kernel * linebreakK = mGrepDriver->addKernelInstance<kernel::LineBreakKernelBuilder>(idb, encodingBits);
107    mGrepDriver->makeKernelCall(linebreakK, {BasisBits}, {LineBreakStream});
108
109    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
110    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(4, 1), segmentSize * bufferSegments);
111    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
112
113    const auto n = REs.size();
114    std::vector<std::vector<re::CC *>> charclasses(n);
115    for (unsigned i = 0; i < n; i++) {
116        REs[i] = resolveCaseInsensitiveMode(REs[i], grep::IgnoreCaseFlag);
117        REs[i] = re::resolveNames(REs[i]);
118        const auto UnicodeSets = re::collectUnicodeSets(REs[i]);
119        std::vector<std::vector<unsigned>> exclusiveSetIDs;
120        doMultiplexCCs(UnicodeSets, exclusiveSetIDs, charclasses[i]);
121        REs[i] = multiplex(REs[i], UnicodeSets, exclusiveSetIDs);
122        REs[i] = regular_expression_passes(REs[i]);
123  }
124
125    std::vector<StreamSetBuffer *> MatchResultsBufs(n);
126
127    for(unsigned i = 0; i < n; ++i){
128        const auto numOfCharacterClasses = charclasses[i].size();
129        StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), segmentSize * bufferSegments);
130        kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(charclasses[i]));
131        mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
132        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
133        kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], numOfCharacterClasses);
134        mGrepDriver->makeKernelCall(icgrepK, {CharClasses, LineBreakStream, RequiredStreams}, {MatchResults});
135        MatchResultsBufs[i] = MatchResults;
136    }
137    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
138    if (REs.size() > 1) {
139        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
140        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
141        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
142    }
143    StreamSetBuffer * Matches = MergedResults;
144
145    if (mMoveMatchesToEOL) {
146        StreamSetBuffer * OriginalMatches = Matches;
147        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
148        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
149        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
150    }
151
152    if (InvertMatchFlag) {
153        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
154        StreamSetBuffer * OriginalMatches = Matches;
155        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
156        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
157    }
158    if (MaxCountFlag > 0) {
159        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
160        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
161        StreamSetBuffer * AllMatches = Matches;
162        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
163        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
164    }
165    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
166}
167
168// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
169// which returns a count of the matches found (possibly subject to a MaxCount).
170//
171
172void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
173
174    assert (mGrepDriver == nullptr);
175    mGrepDriver = new ParabixDriver("engine");
176    auto & idb = mGrepDriver->getBuilder();
177    Module * M = idb->getModule();
178
179    const auto segmentSize = codegen::SegmentSize;
180    const auto bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
181
182    const unsigned encodingBits = 8;
183
184    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), nullptr));
185    mainFunc->setCallingConv(CallingConv::C);
186    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
187    auto args = mainFunc->arg_begin();
188
189    Value * const fileDescriptor = &*(args++);
190    fileDescriptor->setName("fileDescriptor");
191
192    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
193    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb, segmentSize * bufferSegments);
194    sourceK->setInitialArguments({fileDescriptor});
195    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
196
197    StreamSetBuffer * LineBreakStream;
198    StreamSetBuffer * Matches;
199    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
200
201    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
202    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
203    mGrepDriver->generatePipelineIR();
204    idb->setKernel(matchCountK);
205    Value * matchedLineCount = idb->getAccumulator("countResult");
206    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
207    mGrepDriver->deallocateBuffers();
208    idb->CreateRet(matchedLineCount);
209    mGrepDriver->finalizeObject();
210}
211
212//
213// The EmitMatches engine uses an EmitMatchesAccumulator object to concatenate together
214// matched lines.
215
216class EmitMatch : public MatchAccumulator {
217    friend class EmitMatchesEngine;
218public:
219    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
220    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
221    void finalize_match(char * buffer_end) override;
222protected:
223    std::string mLinePrefix;
224    size_t mLineCount;
225    bool mTerminated;
226    std::ostringstream & mResultStr;
227};
228
229//
230//  Default Report Match:  lines are emitted with whatever line terminators are found in the
231//  input.  However, if the final line is not terminated, a new line is appended.
232//
233void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
234    if (WithFilenameFlag) {
235        mResultStr << mLinePrefix;
236    }
237    if (LineNumberFlag) {
238        // Internally line numbers are counted from 0.  For display, adjust
239        // the line number so that lines are numbered from 1.
240        if (InitialTabFlag) {
241            mResultStr << lineNum+1 << "\t:";
242        }
243        else {
244            mResultStr << lineNum+1 << ":";
245        }
246    }
247    size_t bytes = line_end - line_start + 1;
248    mResultStr.write(line_start, bytes);
249    mLineCount++;
250    unsigned last_byte = *line_end;
251    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
252    if (LLVM_UNLIKELY(!mTerminated)) {
253        if (last_byte == 0x85) {  //  Possible NEL terminator.
254            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
255        }
256        else {
257            // Possible LS or PS terminators.
258            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
259                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
260                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
261        }
262    }
263}
264
265void EmitMatch::finalize_match(char * buffer_end) {
266    if (!mTerminated) mResultStr << "\n";
267}
268
269void EmitMatchesEngine::grepCodeGen(std::vector<re::RE *> REs) {
270    assert (mGrepDriver == nullptr);
271    mGrepDriver = new ParabixDriver("engine");
272    auto & idb = mGrepDriver->getBuilder();
273    Module * M = idb->getModule();
274
275    const auto segmentSize = codegen::SegmentSize;
276    const auto bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
277    const unsigned encodingBits = 8;
278
279    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
280    mainFunc->setCallingConv(CallingConv::C);
281    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
282    auto args = mainFunc->arg_begin();
283
284    Value * const fileDescriptor = &*(args++);
285    fileDescriptor->setName("fileDescriptor");
286    Value * match_accumulator = &*(args++);
287    match_accumulator->setName("match_accumulator");
288
289    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
290    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb, segmentSize * bufferSegments);
291    sourceK->setInitialArguments({fileDescriptor});
292    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
293
294    StreamSetBuffer * LineBreakStream;
295    StreamSetBuffer * Matches;
296    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
297
298    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
299    scanMatchK->setInitialArguments({match_accumulator});
300    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
301    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
302    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
303
304    mGrepDriver->generatePipelineIR();
305    mGrepDriver->deallocateBuffers();
306    idb->CreateRet(idb->getInt64(0));
307    mGrepDriver->finalizeObject();
308}
309
310
311//
312//  The doGrep methods apply a GrepEngine to a single file, processing the results
313//  differently based on the engine type.
314
315uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
316    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor);
317    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
318
319    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
320    if (fileDescriptor == -1) return 0;
321
322    uint64_t grepResult = f(fileDescriptor);
323    close(fileDescriptor);
324    return grepResult;
325}
326
327uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
328    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
329    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
330    mResultStrs[fileIdx] << grepResult << "\n";
331    return grepResult;
332}
333
334std::string GrepEngine::linePrefix(std::string fileName) {
335    if (fileName == "-") {
336        return LabelFlag + mFileSuffix;
337    }
338    else {
339        return fileName + mFileSuffix;
340    }
341}
342
343uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
344    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
345    if (grepResult == mRequiredCount) {
346       mResultStrs[fileIdx] << linePrefix(fileName);
347    }
348    return grepResult;
349}
350
351uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
352    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, intptr_t accum_addr);
353    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
354
355    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
356    if (fileDescriptor == -1) return 0;
357    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
358    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
359    close(fileDescriptor);
360    if (accum.mLineCount > 0) grepMatchFound = true;
361    return accum.mLineCount;
362}
363
364// Open a file and return its file desciptor.
365int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
366    if (fileName == "-") {
367        return STDIN_FILENO;
368    }
369    else {
370        struct stat sb;
371        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
372        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
373            if (!NoMessagesFlag) {
374                if (errno == EACCES) {
375                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
376                }
377                else if (errno == ENOENT) {
378                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
379                }
380                else {
381                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
382                }
383            }
384            return fileDescriptor;
385        }
386        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
387            if (!NoMessagesFlag) {
388                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
389            }
390            close(fileDescriptor);
391            return -1;
392        }
393        return fileDescriptor;
394    }
395}
396
397// The process of searching a group of files may use a sequential or a task
398// parallel approach.
399
400void * DoGrepThreadFunction(void *args) {
401    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
402}
403
404bool GrepEngine::searchAllFiles() {
405    const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
406    pthread_t threads[numOfThreads];
407
408    for(unsigned long i = 1; i < numOfThreads; ++i) {
409        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
410        if (rc) {
411            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
412        }
413    }
414    // Main thread also does the work;
415
416    DoGrepThreadMethod();
417    for(unsigned i = 1; i < numOfThreads; ++i) {
418        void * status = nullptr;
419        const int rc = pthread_join(threads[i], &status);
420        if (rc) {
421            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
422        }
423    }
424    return grepMatchFound;
425}
426
427
428// DoGrep thread function.
429void * GrepEngine::DoGrepThreadMethod() {
430
431    unsigned fileIdx = mNextFileToGrep++;
432    while (fileIdx < inputFiles.size()) {
433        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
434        mFileStatus[fileIdx] = FileStatus::GrepComplete;
435        if (grepResult > 0) {
436            grepMatchFound = true;
437        }
438        if (QuietMode && grepMatchFound) {
439            if (pthread_self() != mEngineThread) {
440                pthread_exit(nullptr);
441            }
442            return nullptr;
443        }
444        fileIdx = mNextFileToGrep++;
445    }
446
447    unsigned printIdx = mNextFileToPrint++;
448    while (printIdx < inputFiles.size()) {
449        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
450        if (readyToPrint) {
451            const auto output = mResultStrs[printIdx].str();
452            if (!output.empty()) {
453                llvm::outs() << output;
454            }
455            mFileStatus[printIdx] = FileStatus::PrintComplete;
456            printIdx = mNextFileToPrint++;
457        } else {
458            mGrepDriver->performIncrementalCacheCleanupStep();
459        }
460        sched_yield();
461    }
462
463    if (pthread_self() != mEngineThread) {
464        pthread_exit(nullptr);
465    } else {
466        return nullptr;
467    }
468}
469
470}
Note: See TracBrowser for help on using the repository browser.