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

Last change on this file since 5860 was 5860, checked in by cameron, 15 months ago

Revert inadvertent change to grep_engine.cpp

File size: 20.8 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 auto UnicodeSets = re::collectUnicodeSets(REs[i]);
154            StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
155            if (UnicodeSets.size() <= 1) {
156                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i]);
157                mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams}, {MatchResults});
158                MatchResultsBufs[i] = MatchResults;
159            } else {
160                mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
161                REs[i] = transformCCs(mpx.get(), REs[i]);
162                std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
163                auto numOfCharacterClasses = mpx_basis.size();
164                StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
165                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
166                mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
167//                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
168//                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
169                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], std::vector<cc::Alphabet *>{mpx.get()});
170                mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams, CharClasses}, {MatchResults});
171                MatchResultsBufs[i] = MatchResults;
172            }
173        } else {
174            StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
175            kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i]);
176            mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams}, {MatchResults});
177            MatchResultsBufs[i] = MatchResults;
178        }
179    }
180    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
181    if (REs.size() > 1) {
182        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
183        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
184        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
185    }
186    StreamSetBuffer * Matches = MergedResults;
187
188    if (mMoveMatchesToEOL) {
189        StreamSetBuffer * OriginalMatches = Matches;
190        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
191        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
192        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
193    }
194
195    if (InvertMatchFlag) {
196        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
197        StreamSetBuffer * OriginalMatches = Matches;
198        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
199        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
200    }
201    if (MaxCountFlag > 0) {
202        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
203        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
204        StreamSetBuffer * const AllMatches = Matches;
205        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
206        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
207    }
208    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
209}
210
211// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
212// which returns a count of the matches found (possibly subject to a MaxCount).
213//
214
215void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
216
217    assert (mGrepDriver == nullptr);
218    mGrepDriver = new ParabixDriver("engine");
219    auto & idb = mGrepDriver->getBuilder();
220    Module * M = idb->getModule();
221
222    const unsigned encodingBits = 8;
223
224    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), nullptr));
225    mainFunc->setCallingConv(CallingConv::C);
226    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
227    auto args = mainFunc->arg_begin();
228
229    Value * const fileDescriptor = &*(args++);
230    fileDescriptor->setName("fileDescriptor");
231
232    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
233    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
234    sourceK->setInitialArguments({fileDescriptor});
235    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
236
237    StreamSetBuffer * LineBreakStream;
238    StreamSetBuffer * Matches;
239    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
240
241    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
242    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
243    mGrepDriver->generatePipelineIR();
244    idb->setKernel(matchCountK);
245    Value * matchedLineCount = idb->getAccumulator("countResult");
246    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
247    mGrepDriver->deallocateBuffers();
248    idb->CreateRet(matchedLineCount);
249    mGrepDriver->finalizeObject();
250}
251
252//
253// The EmitMatches engine uses an EmitMatchesAccumulator object to concatenate together
254// matched lines.
255
256class EmitMatch : public MatchAccumulator {
257    friend class EmitMatchesEngine;
258public:
259    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
260    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
261    void finalize_match(char * buffer_end) override;
262protected:
263    std::string mLinePrefix;
264    size_t mLineCount;
265    bool mTerminated;
266    std::ostringstream & mResultStr;
267};
268
269//
270//  Default Report Match:  lines are emitted with whatever line terminators are found in the
271//  input.  However, if the final line is not terminated, a new line is appended.
272//
273void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
274    if (WithFilenameFlag) {
275        mResultStr << mLinePrefix;
276    }
277    if (LineNumberFlag) {
278        // Internally line numbers are counted from 0.  For display, adjust
279        // the line number so that lines are numbered from 1.
280        if (InitialTabFlag) {
281            mResultStr << lineNum+1 << "\t:";
282        }
283        else {
284            mResultStr << lineNum+1 << ":";
285        }
286    }
287    size_t bytes = line_end - line_start + 1;
288    mResultStr.write(line_start, bytes);
289    mLineCount++;
290    unsigned last_byte = *line_end;
291    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
292    if (LLVM_UNLIKELY(!mTerminated)) {
293        if (last_byte == 0x85) {  //  Possible NEL terminator.
294            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
295        }
296        else {
297            // Possible LS or PS terminators.
298            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
299                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
300                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
301        }
302    }
303}
304
305void EmitMatch::finalize_match(char * buffer_end) {
306    if (!mTerminated) mResultStr << "\n";
307}
308
309void EmitMatchesEngine::grepCodeGen(std::vector<re::RE *> REs) {
310    assert (mGrepDriver == nullptr);
311    mGrepDriver = new ParabixDriver("engine");
312    auto & idb = mGrepDriver->getBuilder();
313    Module * M = idb->getModule();
314
315    const unsigned encodingBits = 8;
316
317    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
318    mainFunc->setCallingConv(CallingConv::C);
319    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
320    auto args = mainFunc->arg_begin();
321
322    Value * const fileDescriptor = &*(args++);
323    fileDescriptor->setName("fileDescriptor");
324    Value * match_accumulator = &*(args++);
325    match_accumulator->setName("match_accumulator");
326
327    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
328    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
329    sourceK->setInitialArguments({fileDescriptor});
330    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
331
332    StreamSetBuffer * LineBreakStream;
333    StreamSetBuffer * Matches;
334    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
335
336    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
337    scanMatchK->setInitialArguments({match_accumulator});
338    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
339    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
340    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
341
342    mGrepDriver->generatePipelineIR();
343    mGrepDriver->deallocateBuffers();
344    idb->CreateRet(idb->getInt64(0));
345    mGrepDriver->finalizeObject();
346}
347
348
349//
350//  The doGrep methods apply a GrepEngine to a single file, processing the results
351//  differently based on the engine type.
352
353uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
354    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor);
355    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
356
357    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
358    if (fileDescriptor == -1) return 0;
359
360    uint64_t grepResult = f(fileDescriptor);
361    close(fileDescriptor);
362    return grepResult;
363}
364
365uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
366    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
367    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
368    mResultStrs[fileIdx] << grepResult << "\n";
369    return grepResult;
370}
371
372std::string GrepEngine::linePrefix(std::string fileName) {
373    if (fileName == "-") {
374        return LabelFlag + mFileSuffix;
375    }
376    else {
377        return fileName + mFileSuffix;
378    }
379}
380
381uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
382    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
383    if (grepResult == mRequiredCount) {
384       mResultStrs[fileIdx] << linePrefix(fileName);
385    }
386    return grepResult;
387}
388
389uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
390    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, intptr_t accum_addr);
391    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
392
393    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
394    if (fileDescriptor == -1) return 0;
395    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
396    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
397    close(fileDescriptor);
398    if (accum.mLineCount > 0) grepMatchFound = true;
399    return accum.mLineCount;
400}
401
402// Open a file and return its file desciptor.
403int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
404    if (fileName == "-") {
405        return STDIN_FILENO;
406    }
407    else {
408        struct stat sb;
409        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
410        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
411            if (!NoMessagesFlag) {
412                if (errno == EACCES) {
413                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
414                }
415                else if (errno == ENOENT) {
416                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
417                }
418                else {
419                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
420                }
421            }
422            return fileDescriptor;
423        }
424        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
425            if (!NoMessagesFlag) {
426                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
427            }
428            close(fileDescriptor);
429            return -1;
430        }
431        return fileDescriptor;
432    }
433}
434
435// The process of searching a group of files may use a sequential or a task
436// parallel approach.
437
438void * DoGrepThreadFunction(void *args) {
439    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
440}
441
442bool GrepEngine::searchAllFiles() {
443    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
444    std::vector<pthread_t> threads(numOfThreads);
445
446    for(unsigned long i = 1; i < numOfThreads; ++i) {
447        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
448        if (rc) {
449            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
450        }
451    }
452    // Main thread also does the work;
453
454    DoGrepThreadMethod();
455    for(unsigned i = 1; i < numOfThreads; ++i) {
456        void * status = nullptr;
457        const int rc = pthread_join(threads[i], &status);
458        if (rc) {
459            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
460        }
461    }
462    return grepMatchFound;
463}
464
465
466// DoGrep thread function.
467void * GrepEngine::DoGrepThreadMethod() {
468
469    unsigned fileIdx = mNextFileToGrep++;
470    while (fileIdx < inputFiles.size()) {
471        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
472        mFileStatus[fileIdx] = FileStatus::GrepComplete;
473        if (grepResult > 0) {
474            grepMatchFound = true;
475        }
476        if (QuietMode && grepMatchFound) {
477            if (pthread_self() != mEngineThread) {
478                pthread_exit(nullptr);
479            }
480            return nullptr;
481        }
482        fileIdx = mNextFileToGrep++;
483    }
484
485    unsigned printIdx = mNextFileToPrint++;
486    while (printIdx < inputFiles.size()) {
487        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
488        if (readyToPrint) {
489            const auto output = mResultStrs[printIdx].str();
490            if (!output.empty()) {
491                llvm::outs() << output;
492            }
493            mFileStatus[printIdx] = FileStatus::PrintComplete;
494            printIdx = mNextFileToPrint++;
495        } else {
496            mGrepDriver->performIncrementalCacheCleanupStep();
497        }
498        sched_yield();
499    }
500
501    if (pthread_self() != mEngineThread) {
502        pthread_exit(nullptr);
503    } else {
504        // Always perform one final cache cleanup step.
505        mGrepDriver->performIncrementalCacheCleanupStep();
506    }
507    return nullptr;
508}
509
510}
Note: See TracBrowser for help on using the repository browser.