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

Last change on this file since 5799 was 5795, checked in by cameron, 18 months ago

Adding Alphabet to CCs: initial check-in

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