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

Last change on this file since 5831 was 5831, checked in by nmedfort, 20 months ago

Potential bug fix for 32-bit

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