source: icGREP/icgrep-devel/icgrep/grep/grep_engine.cpp @ 5892

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

Restructuring: integrating grep_engine and grep_pipeline

File size: 27.7 KB
Line 
1/*
2 *  Copyright (c) 2018 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#include <set>
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/UCD_property_kernel.h>
16#include <kernels/grapheme_kernel.h>
17#include <kernels/linebreak_kernel.h>
18#include <kernels/streams_merge.h>
19#include <kernels/source_kernel.h>
20#include <kernels/s2p_kernel.h>
21#include <kernels/scanmatchgen.h>
22#include <kernels/streamset.h>
23#include <kernels/until_n.h>
24#include <kernels/kernel_builder.h>
25#include <pablo/pablo_kernel.h>
26#include <re/re_cc.h>
27#include <re/re_name.h>
28#include <re/casing.h>
29#include <re/exclude_CC.h>
30#include <re/re_toolchain.h>
31#include <toolchain/toolchain.h>
32#include <re/re_name_resolve.h>
33#include <re/re_name_gather.h>
34#include <re/re_collect_unicodesets.h>
35#include <re/re_multiplex.h>
36#include <re/grapheme_clusters.h>
37#include <re/printer_re.h>
38#include <toolchain/toolchain.h>
39#include <toolchain/cpudriver.h>
40#include <iostream>
41#include <cc/multiplex_CCs.h>
42#include <llvm/Support/raw_ostream.h>
43#include <util/aligned_allocator.h>
44#include <sys/stat.h>
45#include <fcntl.h>
46#include <errno.h>
47#include <llvm/ADT/STLExtras.h> // for make_unique
48#include <llvm/Support/CommandLine.h>
49#include <llvm/Support/Debug.h>
50#include <sched.h>
51
52using namespace parabix;
53using namespace llvm;
54using namespace cc;
55using namespace kernel;
56
57static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
58static cl::opt<bool> PabloTransposition("enable-pablo-s2p", cl::desc("Enable experimental pablo transposition."));
59static cl::opt<bool> CC_Multiplexing("CC-multiplexing", cl::desc("Enable CC multiplexing."), cl::init(false));
60static cl::opt<bool> PropertyKernels("enable-property-kernels", cl::desc("Enable Unicode property kernels."), cl::init(false));
61
62
63namespace grep {
64   
65
66void accumulate_match_wrapper(intptr_t accum_addr, const size_t lineNum, char * line_start, char * line_end) {
67    reinterpret_cast<MatchAccumulator *>(accum_addr)->accumulate_match(lineNum, line_start, line_end);
68}
69
70void finalize_match_wrapper(intptr_t accum_addr, char * buffer_end) {
71    reinterpret_cast<MatchAccumulator *>(accum_addr)->finalize_match(buffer_end);
72}
73
74void grepBuffer(re::RE * pattern, const char * search_buffer, size_t bufferLength, MatchAccumulator * accum) {
75    const unsigned segmentSize = codegen::BufferSegments * codegen::SegmentSize * codegen::ThreadNum;
76   
77    pattern = resolveCaseInsensitiveMode(pattern, false);
78    pattern = regular_expression_passes(pattern);
79   
80   
81    ParabixDriver pxDriver("codepointEngine");
82    auto & idb = pxDriver.getBuilder();
83    Module * M = idb->getModule();
84   
85    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
86    mainFunc->setCallingConv(CallingConv::C);
87    auto args = mainFunc->arg_begin();
88    Value * const buffer = &*(args++);
89    buffer->setName("buffer");
90    Value * length = &*(args++);
91    length->setName("length");
92   
93    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
94   
95    StreamSetBuffer * ByteStream = pxDriver.addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, 8));
96    kernel::Kernel * sourceK = pxDriver.addKernelInstance<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy());
97    sourceK->setInitialArguments({buffer, length});
98    pxDriver.makeKernelCall(sourceK, {}, {ByteStream});
99   
100   
101    StreamSetBuffer * BasisBits = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize);
102    kernel::Kernel * s2pk = pxDriver.addKernelInstance<kernel::S2PKernel>(idb);
103    pxDriver.makeKernelCall(s2pk, {ByteStream}, {BasisBits});
104   
105    StreamSetBuffer * LineFeedStream = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
106    kernel::Kernel * linefeedK = pxDriver.addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
107    pxDriver.makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
108   
109    StreamSetBuffer * LineBreakStream = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
110   
111    kernel::Kernel * requiredStreamsK = pxDriver.addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
112    StreamSetBuffer * RequiredStreams = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
113    pxDriver.makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, LineBreakStream});
114   
115    StreamSetBuffer * MatchResults = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
116    kernel::Kernel * icgrepK = pxDriver.addKernelInstance<kernel::ICGrepKernel>(idb, pattern, std::vector<std::string>{"UTF8_LB", "UTF8_nonfinal"});
117    pxDriver.makeKernelCall(icgrepK, {BasisBits, LineBreakStream, RequiredStreams}, {MatchResults});
118   
119    StreamSetBuffer * MatchedLines = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
120    kernel::Kernel * matchedLinesK = pxDriver.addKernelInstance<kernel::MatchedLinesKernel>(idb);
121    pxDriver.makeKernelCall(matchedLinesK, {MatchResults, LineBreakStream}, {MatchedLines});
122   
123    kernel::Kernel * scanMatchK = pxDriver.addKernelInstance<kernel::ScanMatchKernel>(idb);
124    scanMatchK->setInitialArguments({ConstantInt::get(idb->getIntAddrTy(), reinterpret_cast<intptr_t>(accum))});
125    pxDriver.makeKernelCall(scanMatchK, {MatchedLines, LineBreakStream, ByteStream}, {});
126    pxDriver.LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
127    pxDriver.LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
128   
129    pxDriver.generatePipelineIR();
130    pxDriver.deallocateBuffers();
131    idb->CreateRetVoid();
132    pxDriver.finalizeObject();
133   
134    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
135    auto f = reinterpret_cast<GrepFunctionType>(pxDriver.getMain());
136    f(search_buffer, bufferLength);
137}
138
139
140
141// Grep Engine construction and initialization.
142
143GrepEngine::GrepEngine() :
144    mGrepDriver(nullptr),
145    mNextFileToGrep(0),
146    mNextFileToPrint(0),
147    grepMatchFound(false),
148    mMoveMatchesToEOL(true),
149    mEngineThread(pthread_self()) {}
150
151GrepEngine::~GrepEngine() {
152    delete mGrepDriver;
153}
154
155QuietModeEngine::QuietModeEngine() : GrepEngine() {
156    mMoveMatchesToEOL = false;
157}
158
159MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch) :
160    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
161    mFileSuffix = NullFlag ? std::string("\0", 1) : "\n";
162    mMoveMatchesToEOL = false;
163}
164
165CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
166    mFileSuffix = ":";
167}
168
169EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
170    mFileSuffix = InitialTabFlag ? "\t:" : ":";
171    if (LineRegexpFlag) mMoveMatchesToEOL = false;
172}
173
174void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
175    const unsigned n = filenames.size();
176    mResultStrs.resize(n);
177    mFileStatus.resize(n, FileStatus::Pending);
178    inputFiles = filenames;
179}
180
181// Code Generation
182//
183// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
184
185unsigned LLVM_READNONE calculateMaxCountRate(const std::unique_ptr<kernel::KernelBuilder> & b) {
186    const unsigned packSize = b->getSizeTy()->getBitWidth();
187    return (packSize * packSize) / b->getBitBlockWidth();
188}
189
190std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(std::vector<re::RE *> & REs, StreamSetBuffer * ByteStream) {
191    auto & idb = mGrepDriver->getBuilder();
192    const unsigned segmentSize = codegen::SegmentSize;
193    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
194    // TODO: until we automate stream buffer sizing, use this calculation to determine how large our matches buffer needs to be.
195    const unsigned baseBufferSize = segmentSize * (MaxCountFlag > 0 ? (std::max(bufferSegments, calculateMaxCountRate(idb))) : bufferSegments);
196    const unsigned encodingBits = 8;
197   
198   
199    //  Regular Expression Processing and Analysis Phase
200    const auto nREs = REs.size();
201    bool hasGCB[nREs];
202    bool anyGCB = false;
203   
204    std::set<re::Name *> UnicodeProperties;
205   
206    for(unsigned i = 0; i < nREs; ++i) {
207        REs[i] = resolveModesAndExternalSymbols(REs[i]);
208        REs[i] = excludeUnicodeLineBreak(REs[i]);
209        re::gatherUnicodeProperties(REs[i], UnicodeProperties);
210       //re::Name * unicodeLB = re::makeName("UTF8_LB", re::Name::Type::Unicode);
211        //unicodeLB->setDefinition(re::makeCC(0x0A));
212        //REs[i] = resolveAnchors(REs[i], unicodeLB);
213        REs[i] = regular_expression_passes(REs[i]);
214        hasGCB[i] = hasGraphemeClusterBoundary(REs[i]);
215        anyGCB |= hasGCB[i];
216    }
217   
218    StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
219
220    #ifdef USE_DIRECT_LF_BUILDER
221    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(1, 8), "byteStream", FixedRate(), Principal()});
222    mGrepDriver->makeKernelCall(linefeedK, {ByteStream}, {LineFeedStream});
223    #endif
224
225    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), baseBufferSize);
226    kernel::Kernel * s2pk = nullptr;
227    if (PabloTransposition) {
228        s2pk = mGrepDriver->addKernelInstance<kernel::S2P_PabloKernel>(idb);
229    }
230    else {
231        s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
232    }
233    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
234
235    #ifndef USE_DIRECT_LF_BUILDER
236    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
237    mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
238    #endif
239
240    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
241
242    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
243    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
244    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, LineBreakStream});
245
246   
247    std::map<std::string, StreamSetBuffer *> propertyStream;
248    if (PropertyKernels) {
249        for (auto p : UnicodeProperties) {
250            auto name = p->getFullName();
251            StreamSetBuffer * s = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
252            propertyStream.emplace(std::make_pair(name, s));
253            kernel::Kernel * propertyK = mGrepDriver->addKernelInstance<kernel::UnicodePropertyKernelBuilder>(idb, p);
254            mGrepDriver->makeKernelCall(propertyK, {BasisBits}, {s});
255        }
256    }
257    StreamSetBuffer * GCB_stream = nullptr;
258    if (anyGCB) {
259        GCB_stream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
260        kernel::Kernel * gcbK = mGrepDriver->addKernelInstance<kernel::GraphemeClusterBreakKernel>(idb);
261        mGrepDriver->makeKernelCall(gcbK, {BasisBits, RequiredStreams}, {GCB_stream});
262    }
263
264    std::vector<StreamSetBuffer *> MatchResultsBufs(nREs);
265    for(unsigned i = 0; i < nREs; ++i) {
266        REs[i] = resolveModesAndExternalSymbols(REs[i]);
267        REs[i] = excludeUnicodeLineBreak(REs[i]);
268        //re::Name * unicodeLB = re::makeName("UTF8_LB", re::Name::Type::Unicode);
269        //unicodeLB->setDefinition(re::makeCC(0x0A));
270        //REs[i] = resolveAnchors(REs[i], unicodeLB);
271        REs[i] = regular_expression_passes(REs[i]);
272        std::vector<std::string> externalStreamNames = std::vector<std::string>{"UTF8_LB", "UTF8_nonfinal"};
273        std::vector<StreamSetBuffer *> icgrepInputSets = {BasisBits, LineBreakStream, RequiredStreams};
274        std::set<re::Name *> UnicodeProperties;
275        if (PropertyKernels) {
276            re::gatherUnicodeProperties(REs[i], UnicodeProperties);
277            for (auto p : UnicodeProperties) {
278                auto name = p->getFullName();
279                auto f = propertyStream.find(name);
280                if (f == propertyStream.end()) report_fatal_error(name + " not found\n");
281                externalStreamNames.push_back(name);
282                icgrepInputSets.push_back(f->second);
283            }
284        }
285        if (hasGCB[i]) {
286            externalStreamNames.push_back("\\b{g}");
287            icgrepInputSets.push_back(GCB_stream);
288        }
289        if (CC_Multiplexing) {
290            const auto UnicodeSets = re::collectUnicodeSets(REs[i], std::set<re::Name *>({re::makeZeroWidth("\\b{g}")}));
291            StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
292            if (UnicodeSets.size() <= 1) {
293                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames);
294                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
295                MatchResultsBufs[i] = MatchResults;
296            } else {
297                mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
298                REs[i] = transformCCs(mpx.get(), REs[i]);
299                std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
300                auto numOfCharacterClasses = mpx_basis.size();
301                StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
302                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
303                mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
304//                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
305//                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
306                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames, std::vector<cc::Alphabet *>{mpx.get()});
307                icgrepInputSets.push_back(CharClasses);
308                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
309                MatchResultsBufs[i] = MatchResults;
310            }
311        } else {
312            StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
313            kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames);
314            mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
315            MatchResultsBufs[i] = MatchResults;
316        }
317    }
318    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
319    if (REs.size() > 1) {
320        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
321        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
322        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
323    }
324    StreamSetBuffer * Matches = MergedResults;
325
326    if (mMoveMatchesToEOL) {
327        StreamSetBuffer * OriginalMatches = Matches;
328        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
329        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
330        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
331    }
332
333    if (InvertMatchFlag) {
334        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
335        StreamSetBuffer * OriginalMatches = Matches;
336        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
337        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
338    }
339    if (MaxCountFlag > 0) {
340        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
341        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
342        StreamSetBuffer * const AllMatches = Matches;
343        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
344        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
345    }
346    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
347}
348
349// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
350// which returns a count of the matches found (possibly subject to a MaxCount).
351//
352
353void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
354
355    assert (mGrepDriver == nullptr);
356    mGrepDriver = new ParabixDriver("engine");
357    auto & idb = mGrepDriver->getBuilder();
358    Module * M = idb->getModule();
359
360    const unsigned encodingBits = 8;
361
362    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), nullptr));
363    mainFunc->setCallingConv(CallingConv::C);
364    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
365    auto args = mainFunc->arg_begin();
366
367    Value * const fileDescriptor = &*(args++);
368    fileDescriptor->setName("fileDescriptor");
369
370    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
371    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
372    sourceK->setInitialArguments({fileDescriptor});
373    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
374
375    StreamSetBuffer * LineBreakStream;
376    StreamSetBuffer * Matches;
377    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
378
379    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
380    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
381    mGrepDriver->generatePipelineIR();
382    idb->setKernel(matchCountK);
383    Value * matchedLineCount = idb->getAccumulator("countResult");
384    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
385    mGrepDriver->deallocateBuffers();
386    idb->CreateRet(matchedLineCount);
387    mGrepDriver->finalizeObject();
388}
389
390//
391// The EmitMatches engine uses an EmitMatchesAccumulator object to concatenate together
392// matched lines.
393
394class EmitMatch : public MatchAccumulator {
395    friend class EmitMatchesEngine;
396public:
397    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
398    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
399    void finalize_match(char * buffer_end) override;
400protected:
401    std::string mLinePrefix;
402    size_t mLineCount;
403    bool mTerminated;
404    std::ostringstream & mResultStr;
405};
406
407//
408//  Default Report Match:  lines are emitted with whatever line terminators are found in the
409//  input.  However, if the final line is not terminated, a new line is appended.
410//
411void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
412    if (WithFilenameFlag) {
413        mResultStr << mLinePrefix;
414    }
415    if (LineNumberFlag) {
416        // Internally line numbers are counted from 0.  For display, adjust
417        // the line number so that lines are numbered from 1.
418        if (InitialTabFlag) {
419            mResultStr << lineNum+1 << "\t:";
420        }
421        else {
422            mResultStr << lineNum+1 << ":";
423        }
424    }
425    size_t bytes = line_end - line_start + 1;
426    mResultStr.write(line_start, bytes);
427    mLineCount++;
428    unsigned last_byte = *line_end;
429    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
430    if (LLVM_UNLIKELY(!mTerminated)) {
431        if (last_byte == 0x85) {  //  Possible NEL terminator.
432            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
433        }
434        else {
435            // Possible LS or PS terminators.
436            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
437                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
438                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
439        }
440    }
441}
442
443void EmitMatch::finalize_match(char * buffer_end) {
444    if (!mTerminated) mResultStr << "\n";
445}
446
447void EmitMatchesEngine::grepCodeGen(std::vector<re::RE *> REs) {
448    assert (mGrepDriver == nullptr);
449    mGrepDriver = new ParabixDriver("engine");
450    auto & idb = mGrepDriver->getBuilder();
451    Module * M = idb->getModule();
452
453    const unsigned encodingBits = 8;
454
455    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
456    mainFunc->setCallingConv(CallingConv::C);
457    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
458    auto args = mainFunc->arg_begin();
459
460    Value * const fileDescriptor = &*(args++);
461    fileDescriptor->setName("fileDescriptor");
462    Value * match_accumulator = &*(args++);
463    match_accumulator->setName("match_accumulator");
464
465    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
466    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
467    sourceK->setInitialArguments({fileDescriptor});
468    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
469
470    StreamSetBuffer * LineBreakStream;
471    StreamSetBuffer * Matches;
472    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
473
474    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
475    scanMatchK->setInitialArguments({match_accumulator});
476    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
477    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
478    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
479
480    mGrepDriver->generatePipelineIR();
481    mGrepDriver->deallocateBuffers();
482    idb->CreateRet(idb->getInt64(0));
483    mGrepDriver->finalizeObject();
484}
485
486
487//
488//  The doGrep methods apply a GrepEngine to a single file, processing the results
489//  differently based on the engine type.
490
491uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
492    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor);
493    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
494
495    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
496    if (fileDescriptor == -1) return 0;
497
498    uint64_t grepResult = f(fileDescriptor);
499    close(fileDescriptor);
500    return grepResult;
501}
502
503uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
504    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
505    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
506    mResultStrs[fileIdx] << grepResult << "\n";
507    return grepResult;
508}
509
510std::string GrepEngine::linePrefix(std::string fileName) {
511    if (fileName == "-") {
512        return LabelFlag + mFileSuffix;
513    }
514    else {
515        return fileName + mFileSuffix;
516    }
517}
518
519uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
520    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
521    if (grepResult == mRequiredCount) {
522       mResultStrs[fileIdx] << linePrefix(fileName);
523    }
524    return grepResult;
525}
526
527uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
528    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, intptr_t accum_addr);
529    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
530
531    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
532    if (fileDescriptor == -1) return 0;
533    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
534    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
535    close(fileDescriptor);
536    if (accum.mLineCount > 0) grepMatchFound = true;
537    return accum.mLineCount;
538}
539
540// Open a file and return its file desciptor.
541int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
542    if (fileName == "-") {
543        return STDIN_FILENO;
544    }
545    else {
546        struct stat sb;
547        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
548        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
549            if (!NoMessagesFlag) {
550                if (errno == EACCES) {
551                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
552                }
553                else if (errno == ENOENT) {
554                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
555                }
556                else {
557                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
558                }
559            }
560            return fileDescriptor;
561        }
562        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
563            if (!NoMessagesFlag) {
564                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
565            }
566            close(fileDescriptor);
567            return -1;
568        }
569        return fileDescriptor;
570    }
571}
572
573// The process of searching a group of files may use a sequential or a task
574// parallel approach.
575
576void * DoGrepThreadFunction(void *args) {
577    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
578}
579
580bool GrepEngine::searchAllFiles() {
581    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
582    std::vector<pthread_t> threads(numOfThreads);
583
584    for(unsigned long i = 1; i < numOfThreads; ++i) {
585        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
586        if (rc) {
587            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
588        }
589    }
590    // Main thread also does the work;
591
592    DoGrepThreadMethod();
593    for(unsigned i = 1; i < numOfThreads; ++i) {
594        void * status = nullptr;
595        const int rc = pthread_join(threads[i], &status);
596        if (rc) {
597            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
598        }
599    }
600    return grepMatchFound;
601}
602
603
604// DoGrep thread function.
605void * GrepEngine::DoGrepThreadMethod() {
606
607    unsigned fileIdx = mNextFileToGrep++;
608    while (fileIdx < inputFiles.size()) {
609        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
610        mFileStatus[fileIdx] = FileStatus::GrepComplete;
611        if (grepResult > 0) {
612            grepMatchFound = true;
613        }
614        if (QuietMode && grepMatchFound) {
615            if (pthread_self() != mEngineThread) {
616                pthread_exit(nullptr);
617            }
618            return nullptr;
619        }
620        fileIdx = mNextFileToGrep++;
621    }
622
623    unsigned printIdx = mNextFileToPrint++;
624    while (printIdx < inputFiles.size()) {
625        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
626        if (readyToPrint) {
627            const auto output = mResultStrs[printIdx].str();
628            if (!output.empty()) {
629                llvm::outs() << output;
630            }
631            mFileStatus[printIdx] = FileStatus::PrintComplete;
632            printIdx = mNextFileToPrint++;
633        } else {
634            mGrepDriver->performIncrementalCacheCleanupStep();
635        }
636        sched_yield();
637    }
638
639    if (pthread_self() != mEngineThread) {
640        pthread_exit(nullptr);
641    } else {
642        // Always perform one final cache cleanup step.
643        mGrepDriver->performIncrementalCacheCleanupStep();
644    }
645    return nullptr;
646}
647
648}
Note: See TracBrowser for help on using the repository browser.