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

Last change on this file since 5992 was 5992, checked in by cameron, 12 months ago

Setting BinaryFilesMode? to Text (temporary); conversion to unique_ptr progress

File size: 40.1 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 <llvm/IR/Module.h>
9#include <boost/filesystem.hpp>
10#include <UCD/resolve_properties.h>
11#include <kernels/charclasses.h>
12#include <kernels/cc_kernel.h>
13#include <kernels/grep_kernel.h>
14#include <kernels/UCD_property_kernel.h>
15#include <kernels/grapheme_kernel.h>
16#include <kernels/linebreak_kernel.h>
17#include <kernels/streams_merge.h>
18#include <kernels/source_kernel.h>
19#include <kernels/s2p_kernel.h>
20#include <kernels/scanmatchgen.h>
21#include <kernels/streamset.h>
22#include <kernels/until_n.h>
23#include <kernels/kernel_builder.h>
24#include <pablo/pablo_kernel.h>
25#include <cc/alphabet.h>
26#include <re/re_cc.h>
27#include <re/re_alt.h>
28#include <re/re_end.h>
29#include <re/re_name.h>
30#include <re/casing.h>
31#include <re/exclude_CC.h>
32#include <re/to_utf8.h>
33#include <re/re_toolchain.h>
34#include <toolchain/toolchain.h>
35#include <re/re_analysis.h>
36#include <re/re_name_resolve.h>
37#include <re/re_name_gather.h>
38#include <re/collect_ccs.h>
39#include <re/replaceCC.h>
40#include <re/re_multiplex.h>
41#include <re/grapheme_clusters.h>
42#include <re/printer_re.h>
43#include <toolchain/toolchain.h>
44#include <toolchain/cpudriver.h>
45#include <iostream>
46#include <cc/multiplex_CCs.h>
47#include <llvm/Support/raw_ostream.h>
48#include <util/file_select.h>
49#include <util/aligned_allocator.h>
50#include <sys/stat.h>
51#include <fcntl.h>
52#include <errno.h>
53#include <llvm/ADT/STLExtras.h> // for make_unique
54#include <llvm/Support/CommandLine.h>
55#include <llvm/Support/Debug.h>
56#include <llvm/Support/Casting.h>
57#include <sched.h>
58
59using namespace parabix;
60using namespace llvm;
61using namespace cc;
62using namespace kernel;
63
64static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
65static cl::opt<bool> PabloTransposition("enable-pablo-s2p", cl::desc("Enable experimental pablo transposition."));
66static cl::opt<bool> CC_Multiplexing("CC-multiplexing", cl::desc("Enable CC multiplexing."), cl::init(false));
67static cl::opt<bool> PropertyKernels("enable-property-kernels", cl::desc("Enable Unicode property kernels."), cl::init(false));
68static cl::opt<bool> MultithreadedSimpleRE("enable-simple-RE-kernels", cl::desc("Enable individual CC kernels for simple REs."), cl::init(false));
69const unsigned DefaultByteCClimit = 6;
70
71static cl::opt<unsigned> ByteCClimit("byte-CC-limit", cl::desc("Max number of CCs for byte CC pipeline."), cl::init(DefaultByteCClimit));
72
73
74namespace grep {
75   
76extern "C" void signal_dispatcher(intptr_t callback_object_addr, unsigned signal) {
77    reinterpret_cast<GrepCallBackObject *>(callback_object_addr)->handle_signal(signal);
78}
79   
80void GrepCallBackObject::handle_signal(unsigned s) {
81    if (static_cast<GrepSignal>(s) == GrepSignal::BinaryFile) {
82        mBinaryFile = true;
83    } else {
84        llvm::report_fatal_error("Unknown GrepSignal");
85    }
86}
87
88extern "C" void accumulate_match_wrapper(intptr_t accum_addr, const size_t lineNum, char * line_start, char * line_end) {
89    reinterpret_cast<MatchAccumulator *>(accum_addr)->accumulate_match(lineNum, line_start, line_end);
90}
91
92extern "C" void finalize_match_wrapper(intptr_t accum_addr, char * buffer_end) {
93    reinterpret_cast<MatchAccumulator *>(accum_addr)->finalize_match(buffer_end);
94}
95   
96
97inline static size_t ceil_log2(const size_t v) {
98    assert ("log2(0) is undefined!" && v != 0);
99    assert ("sizeof(size_t) == sizeof(long)" && sizeof(size_t) == sizeof(long));
100    return (sizeof(size_t) * CHAR_BIT) - __builtin_clzl(v - 1UL);
101}
102
103void SearchableBuffer::addSearchCandidate(const char * C_string_ptr) {
104    size_t length = strlen(C_string_ptr)+1;
105    if (mSpace_used + length >= mAllocated_capacity) {
106        size_t new_capacity = size_t{1} << (ceil_log2(mSpace_used + length + 1));
107        AlignedAllocator<char, BUFFER_ALIGNMENT> alloc;
108        char * new_buffer = mAllocator.allocate(new_capacity, 0);
109        memcpy(new_buffer, mBuffer_base, mSpace_used);
110        memset(&new_buffer[mSpace_used], 0, new_capacity-mSpace_used);
111        if (mBuffer_base != mInitial_buffer) {
112            alloc.deallocate(mBuffer_base, 0);
113        }
114        mBuffer_base = new_buffer;
115        mAllocated_capacity = new_capacity;
116    }
117    memcpy((void * ) &mBuffer_base[mSpace_used], C_string_ptr, length);
118    mSpace_used += length;
119    assert("Search candidate not null terminated" && (mBuffer_base[mSpace_used] == '\0'));
120    mEntries++;
121}
122
123SearchableBuffer::SearchableBuffer() :
124    mAllocated_capacity(INITIAL_CAPACITY),
125    mSpace_used(0),
126    mEntries(0),
127    mBuffer_base(mInitial_buffer) {
128    memset(mBuffer_base, 0, INITIAL_CAPACITY);
129}
130
131SearchableBuffer::~SearchableBuffer() {
132    if (mBuffer_base != mInitial_buffer) {
133        mAllocator.deallocate(mBuffer_base, 0);
134    }
135}
136
137
138
139// Grep Engine construction and initialization.
140
141GrepEngine::GrepEngine() :
142    mSuppressFileMessages(false),
143    mBinaryFilesMode(argv::Text),
144    mPreferMMap(true),
145    mShowFileNames(false),
146    mStdinLabel("(stdin)"),
147    mShowLineNumbers(false),
148    mInitialTab(false),
149    mCaseInsensitive(false),
150    mInvertMatches(false),
151    mMaxCount(0),
152    mGrepStdIn(false),
153    mGrepDriver(make_unique<ParabixDriver>("engine")),
154    mNextFileToGrep(0),
155    mNextFileToPrint(0),
156    grepMatchFound(false),
157    mGrepRecordBreak(GrepRecordBreakKind::LF),
158    mMoveMatchesToEOL(true),
159    mEngineThread(pthread_self()) {}
160
161GrepEngine::~GrepEngine() {
162    //delete mGrepDriver;
163}
164
165QuietModeEngine::QuietModeEngine() : GrepEngine() {
166    mEngineKind = EngineKind::QuietMode;
167    mMoveMatchesToEOL = false;
168    mMaxCount = 1;
169}
170
171MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithMatch, bool useNullSeparators) :
172    GrepEngine(), mRequiredCount(showFilesWithMatch) {
173    mEngineKind = EngineKind::MatchOnly;
174    mFileSuffix = useNullSeparators ? std::string("\0", 1) : "\n";
175    mMoveMatchesToEOL = false;
176    mMaxCount = 1;
177    mShowFileNames = true;
178}
179
180CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
181    mEngineKind = EngineKind::CountOnly;
182    mFileSuffix = ":";
183}
184
185EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
186    mEngineKind = EngineKind::EmitMatches;
187    mFileSuffix = mInitialTab ? "\t:" : ":";
188}
189
190   
191void GrepEngine::setRecordBreak(GrepRecordBreakKind b) {
192    mGrepRecordBreak = b;
193}
194
195   
196
197   
198void GrepEngine::initFileResult(std::vector<boost::filesystem::path> & paths) {
199    const unsigned n = paths.size();
200    mResultStrs.resize(n);
201    mFileStatus.resize(n, FileStatus::Pending);
202    inputPaths = paths;
203}
204
205void GrepEngine::initREs(std::vector<re::RE *> & REs) {
206    if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
207        mBreakCC = re::makeCC(re::makeCC(0x0A, 0x0D), re::makeCC(re::makeCC(0x85), re::makeCC(0x2028, 0x2029)));
208    } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
209        mBreakCC = re::makeByte(0);  // Null
210    } else {
211        mBreakCC = re::makeByte(0x0A); // LF
212    }
213    re::RE * anchorRE = mBreakCC;
214    if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
215        re::Name * anchorName = re::makeName("UTF8_LB", re::Name::Type::Unicode);
216        anchorName->setDefinition(UCD::UnicodeBreakRE());
217        anchorRE = anchorName;
218    }
219   
220    mREs = REs;
221    bool allAnchored = true;
222    for(unsigned i = 0; i < mREs.size(); ++i) {
223        if (!hasEndAnchor(mREs[i])) allAnchored = false;
224        mREs[i] = resolveModesAndExternalSymbols(mREs[i], mCaseInsensitive);
225        mREs[i] = re::exclude_CC(mREs[i], mBreakCC);
226        mREs[i] = resolveAnchors(mREs[i], anchorRE);
227        re::gatherUnicodeProperties(mREs[i], mUnicodeProperties);
228        mREs[i] = regular_expression_passes(mREs[i]);
229    }
230    if (allAnchored && (mGrepRecordBreak != GrepRecordBreakKind::Unicode)) mMoveMatchesToEOL = false;
231
232}
233
234
235   
236// Code Generation
237//
238// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
239
240unsigned LLVM_READNONE calculateMaxCountRate(const std::unique_ptr<kernel::KernelBuilder> & b) {
241    const unsigned packSize = b->getSizeTy()->getBitWidth();
242    return (packSize * packSize) / b->getBitBlockWidth();
243}
244   
245std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(StreamSetBuffer * SourceStream, Value * callback_object_addr) {
246    auto & idb = mGrepDriver->getBuilder();
247    const unsigned segmentSize = codegen::SegmentSize;
248    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
249    // TODO: until we automate stream buffer sizing, use this calculation to determine how large our matches buffer needs to be.
250    const unsigned baseBufferSize = segmentSize * (mMaxCount > 0 ? (std::max(bufferSegments, calculateMaxCountRate(idb))) : bufferSegments);
251    const unsigned encodingBits = 8;
252   
253   
254    //  Regular Expression Processing and Analysis Phase
255    const auto nREs = mREs.size();
256    bool hasGCB[nREs];
257    bool anyGCB = false;
258
259    for(unsigned i = 0; i < nREs; ++i) {
260        hasGCB[i] = hasGraphemeClusterBoundary(mREs[i]);
261        anyGCB |= hasGCB[i];
262    }
263    StreamSetBuffer * ByteStream = nullptr;
264    if (mBinaryFilesMode == argv::Text) {
265        ByteStream = SourceStream;
266    } else if (mBinaryFilesMode == argv::WithoutMatch) {
267        ByteStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 8), baseBufferSize);
268        kernel::Kernel * binaryCheckK = mGrepDriver->addKernelInstance<kernel::AbortOnNull>(idb);
269        binaryCheckK->setInitialArguments({callback_object_addr});
270        mGrepDriver->makeKernelCall(binaryCheckK, {SourceStream}, {ByteStream});
271        mGrepDriver->LinkFunction(*binaryCheckK, "signal_dispatcher", &signal_dispatcher);
272    } else {
273        llvm::report_fatal_error("Binary mode not supported.");
274    }
275    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
276    std::vector<StreamSetBuffer *> MatchResultsBufs(nREs);
277   
278    re::RE * prefixRE;
279    re::RE * suffixRE;
280    // For simple regular expressions with a small number of characters, we
281    // can bypass transposition and use the Direct CC compiler.
282    bool isSimple = (nREs == 1) && (mGrepRecordBreak != GrepRecordBreakKind::Unicode) && (!anyGCB);
283    if (isSimple) {
284        mREs[0] = toUTF8(mREs[0]);
285    }
286    if (isSimple && byteTestsWithinLimit(mREs[0], ByteCClimit)) {
287        std::vector<std::string> externalStreamNames;
288        std::vector<StreamSetBuffer *> icgrepInputSets = {ByteStream};
289        if (MultithreadedSimpleRE && hasTriCCwithinLimit(mREs[0], ByteCClimit, prefixRE, suffixRE)) {
290            auto CCs = re::collectCCs(prefixRE, &cc::Byte);
291            for (auto cc : CCs) {
292                auto ccName = makeName(cc);
293                mREs[0] = re::replaceCC(mREs[0], cc, ccName);
294                std::string ccNameStr = ccName->getFullName();
295                StreamSetBuffer * ccStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
296                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, ccNameStr, std::vector<re::CC *>{cc});
297                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {ccStream});
298                externalStreamNames.push_back(ccNameStr);
299                icgrepInputSets.push_back(ccStream);
300            }
301        }
302        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
303        kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ByteGrepKernel>(idb, mREs[0], externalStreamNames);
304        mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
305        MatchResultsBufs[0] = MatchResults;
306        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, "breakCC", std::vector<re::CC *>{mBreakCC});
307        mGrepDriver->makeKernelCall(breakK, {ByteStream}, {LineBreakStream});
308    } else if (isSimple && hasTriCCwithinLimit(mREs[0], ByteCClimit, prefixRE, suffixRE)) {
309        std::vector<std::string> externalStreamNames;
310        std::vector<StreamSetBuffer *> icgrepInputSets = {ByteStream};
311        if (MultithreadedSimpleRE) {
312            auto CCs = re::collectCCs(prefixRE, &cc::Byte);
313            for (auto cc : CCs) {
314                auto ccName = makeName(cc);
315                mREs[0] = re::replaceCC(mREs[0], cc, ccName);
316                std::string ccNameStr = ccName->getFullName();
317                StreamSetBuffer * ccStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
318                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, ccNameStr, std::vector<re::CC *>{cc});
319                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {ccStream});
320                externalStreamNames.push_back(ccNameStr);
321                icgrepInputSets.push_back(ccStream);
322            }
323        }
324        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
325        kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ByteBitGrepKernel>(idb, prefixRE, suffixRE, externalStreamNames);
326        mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
327        MatchResultsBufs[0] = MatchResults;
328        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, "breakCC", std::vector<re::CC *>{mBreakCC});
329        mGrepDriver->makeKernelCall(breakK, {ByteStream}, {LineBreakStream});
330    } else {
331       
332        StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), baseBufferSize);
333        kernel::Kernel * s2pk = nullptr;
334        if (PabloTransposition) {
335            s2pk = mGrepDriver->addKernelInstance<kernel::S2P_PabloKernel>(idb);
336        }
337        else {
338            s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
339        }
340        mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
341
342        StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
343        StreamSetBuffer * UnicodeLB = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
344
345        StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
346        kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
347        mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
348       
349        kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
350        mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, UnicodeLB});
351
352        if (mGrepRecordBreak == GrepRecordBreakKind::LF) {
353            LineBreakStream = LineFeedStream;
354        } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
355            kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::ParabixCharacterClassKernelBuilder>(idb, "Null", std::vector<re::CC *>{mBreakCC}, 8);
356            mGrepDriver->makeKernelCall(breakK, {BasisBits}, {LineBreakStream});
357        } else {
358            LineBreakStream = UnicodeLB;
359        }
360       
361        std::map<std::string, StreamSetBuffer *> propertyStream;
362        if (PropertyKernels) {
363            for (auto p : mUnicodeProperties) {
364                auto name = p->getFullName();
365                StreamSetBuffer * s = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
366                propertyStream.emplace(std::make_pair(name, s));
367                kernel::Kernel * propertyK = mGrepDriver->addKernelInstance<kernel::UnicodePropertyKernelBuilder>(idb, p);
368                mGrepDriver->makeKernelCall(propertyK, {BasisBits}, {s});
369            }
370        }
371        StreamSetBuffer * GCB_stream = nullptr;
372        if (anyGCB) {
373            GCB_stream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
374            kernel::Kernel * gcbK = mGrepDriver->addKernelInstance<kernel::GraphemeClusterBreakKernel>(idb);
375            mGrepDriver->makeKernelCall(gcbK, {BasisBits, RequiredStreams}, {GCB_stream});
376        }
377
378        for(unsigned i = 0; i < nREs; ++i) {
379            std::vector<std::string> externalStreamNames;
380            std::vector<StreamSetBuffer *> icgrepInputSets = {BasisBits};
381            if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
382                externalStreamNames.push_back("UTF8_LB");
383                icgrepInputSets.push_back(LineBreakStream);
384                externalStreamNames.push_back("UTF8_nonfinal");
385                icgrepInputSets.push_back(RequiredStreams);
386            }
387            std::set<re::Name *> UnicodeProperties;
388            if (PropertyKernels) {
389                re::gatherUnicodeProperties(mREs[i], UnicodeProperties);
390                for (auto p : UnicodeProperties) {
391                    auto name = p->getFullName();
392                    auto f = propertyStream.find(name);
393                    if (f == propertyStream.end()) report_fatal_error(name + " not found\n");
394                    externalStreamNames.push_back(name);
395                    icgrepInputSets.push_back(f->second);
396                }
397            }
398            if (hasGCB[i]) {
399                externalStreamNames.push_back("\\b{g}");
400                icgrepInputSets.push_back(GCB_stream);
401            }
402            if (CC_Multiplexing) {
403                const auto UnicodeSets = re::collectCCs(mREs[i], &cc::Unicode, std::set<re::Name *>({re::makeZeroWidth("\\b{g}")}));
404                StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
405                if (UnicodeSets.size() <= 1) {
406                    kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames);
407                    mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
408                    MatchResultsBufs[i] = MatchResults;
409                } else {
410                    mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
411                    mREs[i] = transformCCs(mpx.get(), mREs[i]);
412                    std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
413                    auto numOfCharacterClasses = mpx_basis.size();
414                    StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
415                    kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
416                    mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
417    //                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
418    //                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
419                    kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames, std::vector<cc::Alphabet *>{mpx.get()});
420                    icgrepInputSets.push_back(CharClasses);
421                    mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
422                    MatchResultsBufs[i] = MatchResults;
423                }
424            } else {
425                StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
426                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames);
427                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
428                MatchResultsBufs[i] = MatchResults;
429            }
430        }
431    }
432
433    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
434    if (mREs.size() > 1) {
435        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
436        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, mREs.size());
437        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
438    }
439    StreamSetBuffer * Matches = MergedResults;
440    if (mMoveMatchesToEOL) {
441        StreamSetBuffer * OriginalMatches = Matches;
442        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
443        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
444        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
445    }
446    if (mInvertMatches) {
447        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
448        StreamSetBuffer * OriginalMatches = Matches;
449        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
450        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
451    }
452    if (mMaxCount > 0) {
453        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
454        untilK->setInitialArguments({idb->getSize(mMaxCount)});
455        StreamSetBuffer * const AllMatches = Matches;
456        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
457        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
458    }
459
460    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
461}
462
463// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
464// which returns a count of the matches found (possibly subject to a MaxCount).
465//
466
467void GrepEngine::grepCodeGen() {
468    auto & idb = mGrepDriver->getBuilder();
469    Module * M = idb->getModule();
470
471    const unsigned encodingBits = 8;
472
473    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt8Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
474    mainFunc->setCallingConv(CallingConv::C);
475    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
476    auto args = mainFunc->arg_begin();
477
478    Value * const useMMap = &*(args++);
479    useMMap->setName("useMMap");
480    Value * const fileDescriptor = &*(args++);
481    fileDescriptor->setName("fileDescriptor");
482    Value * call_back_object = &*(args++);
483    call_back_object->setName("call_back_object");
484
485    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
486    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
487    sourceK->setInitialArguments({useMMap, fileDescriptor});
488    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
489
490    StreamSetBuffer * LineBreakStream;
491    StreamSetBuffer * Matches;
492    std::tie(LineBreakStream, Matches) = grepPipeline(ByteStream, call_back_object);
493
494    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
495    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
496    mGrepDriver->generatePipelineIR();
497    idb->setKernel(matchCountK);
498    Value * matchedLineCount = idb->getAccumulator("countResult");
499    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
500    mGrepDriver->deallocateBuffers();
501    idb->CreateRet(matchedLineCount);
502   
503    mGrepDriver->finalizeObject();
504}
505
506//
507//  Default Report Match:  lines are emitted with whatever line terminators are found in the
508//  input.  However, if the final line is not terminated, a new line is appended.
509//
510void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
511    mResultStr << mLinePrefix;
512    if (mShowLineNumbers) {
513        // Internally line numbers are counted from 0.  For display, adjust
514        // the line number so that lines are numbered from 1.
515        if (mInitialTab) {
516            mResultStr << lineNum+1 << "\t:";
517        }
518        else {
519            mResultStr << lineNum+1 << ":";
520        }
521    }
522    size_t bytes = line_end - line_start + 1;
523    mResultStr.write(line_start, bytes);
524    mLineCount++;
525    unsigned last_byte = *line_end;
526    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
527    if (LLVM_UNLIKELY(!mTerminated)) {
528        if (last_byte == 0x85) {  //  Possible NEL terminator.
529            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
530        }
531        else {
532            // Possible LS or PS terminators.
533            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
534                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
535                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
536        }
537    }
538}
539
540void EmitMatch::finalize_match(char * buffer_end) {
541    if (!mTerminated) mResultStr << "\n";
542}
543
544void EmitMatchesEngine::grepCodeGen() {
545    auto & idb = mGrepDriver->getBuilder();
546    Module * M = idb->getModule();
547
548    const unsigned encodingBits = 8;
549
550    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt8Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
551    mainFunc->setCallingConv(CallingConv::C);
552    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
553    auto args = mainFunc->arg_begin();
554
555    Value * const useMMap = &*(args++);
556    useMMap->setName("useMMap");
557    Value * const fileDescriptor = &*(args++);
558    fileDescriptor->setName("fileDescriptor");
559    Value * match_accumulator = &*(args++);
560    match_accumulator->setName("match_accumulator");
561
562    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
563    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
564    sourceK->setInitialArguments({useMMap, fileDescriptor});
565    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
566
567    StreamSetBuffer * LineBreakStream;
568    StreamSetBuffer * Matches;
569    std::tie(LineBreakStream, Matches) = grepPipeline(ByteStream, match_accumulator);
570
571    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
572    scanMatchK->setInitialArguments({match_accumulator});
573    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
574    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
575    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
576
577    mGrepDriver->generatePipelineIR();
578    mGrepDriver->deallocateBuffers();
579    idb->CreateRet(idb->getInt64(0));
580    mGrepDriver->finalizeObject();
581}
582
583
584//
585//  The doGrep methods apply a GrepEngine to a single file, processing the results
586//  differently based on the engine type.
587
588uint64_t GrepEngine::doGrep(const std::string & fileName, std::ostringstream & strm) {
589    typedef uint64_t (*GrepFunctionType)(bool useMMap, int32_t fileDescriptor, intptr_t callback_addr);
590    using namespace boost::filesystem;
591    path p(fileName);
592    bool useMMap = mPreferMMap;
593    if (p == "-") useMMap = false;
594    if (!is_regular_file(p)) useMMap = false;
595
596    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
597
598    int32_t fileDescriptor = openFile(fileName, strm);
599    if (fileDescriptor == -1) return 0;
600    GrepCallBackObject handler;
601    uint64_t grepResult = f(useMMap, fileDescriptor, reinterpret_cast<intptr_t>(&handler));
602    close(fileDescriptor);
603    if (handler.binaryFileSignalled()) {
604        return 0;
605    }
606    else {
607        showResult(grepResult, fileName, strm);
608        return grepResult;
609    }
610}
611
612std::string GrepEngine::linePrefix(std::string fileName) {
613    if (!mShowFileNames) return "";
614    if (fileName == "-") {
615        return mStdinLabel + mFileSuffix;
616    }
617    else {
618        return fileName + mFileSuffix;
619    }
620}
621
622// Default: do not show anything
623void GrepEngine::showResult(uint64_t grepResult, const std::string & fileName, std::ostringstream & strm) {
624}
625   
626void CountOnlyEngine::showResult(uint64_t grepResult, const std::string & fileName, std::ostringstream & strm) {
627    if (mShowFileNames) strm << linePrefix(fileName);
628    strm << grepResult << "\n";
629}
630   
631void MatchOnlyEngine::showResult(uint64_t grepResult, const std::string & fileName, std::ostringstream & strm) {
632    if (grepResult == mRequiredCount) {
633       strm << linePrefix(fileName);
634    }
635}
636
637uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, std::ostringstream & strm) {
638    typedef uint64_t (*GrepFunctionType)(bool useMMap, int32_t fileDescriptor, intptr_t accum_addr);
639    using namespace boost::filesystem;
640    path p(fileName);
641    bool useMMap = mPreferMMap;
642    if (p == "-") useMMap = false;
643    if (!is_regular_file(p)) useMMap = false;
644    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
645    int32_t fileDescriptor = openFile(fileName, strm);
646    if (fileDescriptor == -1) return 0;
647    EmitMatch accum(linePrefix(fileName), mShowLineNumbers, mInitialTab, strm);
648    f(useMMap, fileDescriptor, reinterpret_cast<intptr_t>(&accum));
649    close(fileDescriptor);
650    if (accum.binaryFileSignalled()) {
651        accum.mResultStr.clear();
652    }
653    if (accum.mLineCount > 0) grepMatchFound = true;
654    return accum.mLineCount;
655}
656
657// Open a file and return its file desciptor.
658int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
659    if (fileName == "-") {
660        return STDIN_FILENO;
661    }
662    else {
663        struct stat sb;
664        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
665        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
666            if (!mSuppressFileMessages) {
667                if (errno == EACCES) {
668                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
669                }
670                else if (errno == ENOENT) {
671                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
672                }
673                else {
674                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
675                }
676            }
677            return fileDescriptor;
678        }
679        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
680            if (!mSuppressFileMessages) {
681                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
682            }
683            close(fileDescriptor);
684            return -1;
685        }
686        return fileDescriptor;
687    }
688}
689
690// The process of searching a group of files may use a sequential or a task
691// parallel approach.
692
693void * DoGrepThreadFunction(void *args) {
694    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
695}
696
697bool GrepEngine::searchAllFiles() {
698    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputPaths.size()));
699    std::vector<pthread_t> threads(numOfThreads);
700
701    for(unsigned long i = 1; i < numOfThreads; ++i) {
702        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
703        if (rc) {
704            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
705        }
706    }
707    // Main thread also does the work;
708    DoGrepThreadMethod();
709    for(unsigned i = 1; i < numOfThreads; ++i) {
710        void * status = nullptr;
711        const int rc = pthread_join(threads[i], &status);
712        if (rc) {
713            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
714        }
715    }
716    return grepMatchFound;
717}
718
719
720// DoGrep thread function.
721void * GrepEngine::DoGrepThreadMethod() {
722
723    unsigned fileIdx = mNextFileToGrep++;
724    while (fileIdx < inputPaths.size()) {
725        if (codegen::DebugOptionIsSet(codegen::TraceCounts)) {
726            errs() << "Tracing " << inputPaths[fileIdx].string() << "\n";
727        }
728        const auto grepResult = doGrep(inputPaths[fileIdx].string(), mResultStrs[fileIdx]);
729        mFileStatus[fileIdx] = FileStatus::GrepComplete;
730        if (grepResult > 0) {
731            grepMatchFound = true;
732        }
733        if ((mEngineKind == EngineKind::QuietMode) && grepMatchFound) {
734            if (pthread_self() != mEngineThread) {
735                pthread_exit(nullptr);
736            }
737            return nullptr;
738        }
739        fileIdx = mNextFileToGrep++;
740    }
741
742    unsigned printIdx = mNextFileToPrint++;
743    while (printIdx < inputPaths.size()) {
744        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
745        if (readyToPrint) {
746            const auto output = mResultStrs[printIdx].str();
747            if (!output.empty()) {
748                llvm::outs() << output;
749            }
750            mFileStatus[printIdx] = FileStatus::PrintComplete;
751            printIdx = mNextFileToPrint++;
752        } else {
753            mGrepDriver->performIncrementalCacheCleanupStep();
754        }
755        sched_yield();
756    }
757
758    if (pthread_self() != mEngineThread) {
759        pthread_exit(nullptr);
760    } else {
761        // Always perform one final cache cleanup step.
762        mGrepDriver->performIncrementalCacheCleanupStep();
763        if (mGrepStdIn) {
764            std::ostringstream s;
765            const auto grepResult = doGrep("-", s);
766            llvm::outs() << s.str();
767            if (grepResult) grepMatchFound = true;
768        }
769    }
770    return nullptr;
771}
772
773   
774   
775InternalSearchEngine::InternalSearchEngine() :
776    mGrepRecordBreak(GrepRecordBreakKind::LF),
777    mCaseInsensitive(false),
778    mGrepDriver(make_unique<ParabixDriver>("InternalEngine")) {}
779   
780InternalSearchEngine::~InternalSearchEngine() {
781}
782
783void InternalSearchEngine::grepCodeGen(re::RE * matchingRE, re::RE * excludedRE, MatchAccumulator * accum) {
784    auto & idb = mGrepDriver->getBuilder();
785    Module * M = idb->getModule();
786   
787    mSaveSegmentPipelineParallel = codegen::SegmentPipelineParallel;
788    codegen::SegmentPipelineParallel = false;
789    const unsigned segmentSize = codegen::BufferSegments * codegen::SegmentSize * codegen::ThreadNum;
790   
791    re::CC * breakCC = nullptr;
792    if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
793        breakCC = re::makeByte(0x0);
794    } else {// if (mGrepRecordBreak == GrepRecordBreakKind::LF)
795        breakCC = re::makeByte(0x0A);
796    }
797    bool excludeNothing = (excludedRE == nullptr) || (isa<re::Alt>(excludedRE) && cast<re::Alt>(excludedRE)->empty());
798    bool matchAllLines = (matchingRE == nullptr) || isa<re::End>(matchingRE);
799    if (!matchAllLines) {
800        matchingRE = resolveCaseInsensitiveMode(matchingRE, mCaseInsensitive);
801        matchingRE = regular_expression_passes(matchingRE);
802        matchingRE = re::exclude_CC(matchingRE, breakCC);
803        matchingRE = resolveAnchors(matchingRE, breakCC);
804        matchingRE = toUTF8(matchingRE);
805    }
806    if (!excludeNothing) {
807        excludedRE = resolveCaseInsensitiveMode(excludedRE, mCaseInsensitive);
808        excludedRE = regular_expression_passes(excludedRE);
809        excludedRE = re::exclude_CC(excludedRE, breakCC);
810        excludedRE = resolveAnchors(excludedRE, breakCC);
811        excludedRE = toUTF8(excludedRE);
812    }
813    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
814    mainFunc->setCallingConv(CallingConv::C);
815    auto args = mainFunc->arg_begin();
816    Value * const buffer = &*(args++);
817    buffer->setName("buffer");
818    Value * length = &*(args++);
819    length->setName("length");
820   
821    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
822    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, 8));
823    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy());
824    sourceK->setInitialArguments({buffer, length});
825    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
826    StreamSetBuffer * RecordBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
827    std::string RBname = (mGrepRecordBreak == GrepRecordBreakKind::Null) ? "Null" : "LF";
828
829   
830    StreamSetBuffer * BasisBits = nullptr;
831   
832    if (matchAllLines && excludeNothing) {
833        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, RBname, std::vector<re::CC *>{breakCC});
834        mGrepDriver->makeKernelCall(breakK, {ByteStream}, {RecordBreakStream});
835    } else {
836        BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize);
837        kernel::Kernel * s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
838        mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
839       
840        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::ParabixCharacterClassKernelBuilder>(idb, RBname, std::vector<re::CC *>{breakCC}, 8);
841        mGrepDriver->makeKernelCall(breakK, {BasisBits}, {RecordBreakStream});
842    }
843   
844    std::vector<std::string> externalStreamNames;
845    StreamSetBuffer * MatchingRecords = nullptr;
846    if (matchAllLines) {
847        MatchingRecords = RecordBreakStream;
848    } else {
849        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
850        kernel::Kernel * includeK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, matchingRE, externalStreamNames);
851        mGrepDriver->makeKernelCall(includeK, {BasisBits}, {MatchResults});
852        MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
853        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
854        mGrepDriver->makeKernelCall(matchedLinesK, {MatchResults, RecordBreakStream}, {MatchingRecords});
855    }
856    if (!excludeNothing) {
857        StreamSetBuffer * ExcludedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
858        kernel::Kernel * excludeK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, excludedRE, externalStreamNames);
859        mGrepDriver->makeKernelCall(excludeK, {BasisBits}, {ExcludedResults});
860        StreamSetBuffer * ExcludedRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
861        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
862        mGrepDriver->makeKernelCall(matchedLinesK, {ExcludedResults, RecordBreakStream}, {ExcludedRecords});
863
864        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
865        if (!matchAllLines) {
866            StreamSetBuffer * nonExcluded = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
867            mGrepDriver->makeKernelCall(invertK, {ExcludedRecords, RecordBreakStream}, {nonExcluded});
868            StreamSetBuffer * included = MatchingRecords;
869            MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
870            kernel::Kernel * streamsIntersectK = mGrepDriver->addKernelInstance<kernel::StreamsIntersect>(idb, 1, 2);
871            mGrepDriver->makeKernelCall(streamsIntersectK, {included, nonExcluded}, {MatchingRecords});
872        }
873        else {
874            MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
875            mGrepDriver->makeKernelCall(invertK, {ExcludedRecords, RecordBreakStream}, {MatchingRecords});
876        }
877    }
878    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
879    scanMatchK->setInitialArguments({ConstantInt::get(idb->getIntAddrTy(), reinterpret_cast<intptr_t>(accum))});
880    mGrepDriver->makeKernelCall(scanMatchK, {MatchingRecords, RecordBreakStream, ByteStream}, {});
881    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
882    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
883    mGrepDriver->generatePipelineIR();
884    mGrepDriver->deallocateBuffers();
885    idb->CreateRetVoid();
886    mGrepDriver->finalizeObject();
887}
888
889void InternalSearchEngine::doGrep(const char * search_buffer, size_t bufferLength) {
890    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
891    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
892    f(search_buffer, bufferLength);
893    codegen::SegmentPipelineParallel = mSaveSegmentPipelineParallel;
894}
895
896}
Note: See TracBrowser for help on using the repository browser.