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

Last change on this file since 5842 was 5841, checked in by cameron, 19 months ago

LLVM_VERSION_CODE macro, CC-multiplex option, performance bug fixes

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