source: icGREP/icgrep-devel/icgrep/icgrep.cpp @ 5338

Last change on this file since 5338 was 5338, checked in by lindanl, 2 years ago

Provide option to build separated kernels for each regular expression.

File size: 17.2 KB
Line 
1/*
2 *  Copyright (c) 2016 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 <cstdio>
8#include <vector>
9#include <llvm/Support/CommandLine.h>
10#include <llvm/Support/ErrorHandling.h>
11#include <llvm/Support/Signals.h>
12#include <llvm/Support/raw_ostream.h>
13#include <re/re_alt.h>
14#include <re/re_seq.h>
15#include <re/re_start.h>
16#include <re/re_end.h>
17#include <re/re_parser.h>
18#include <re/re_utility.h>
19#include <grep_engine.h>
20#include <fstream>
21#include <string>
22#include <boost/uuid/sha1.hpp>
23#include <toolchain.h>
24#include <re/re_toolchain.h>
25#include <pablo/pablo_toolchain.h>
26#include <mutex>
27#include <boost/filesystem.hpp>
28#include <iostream> // MEEE
29#ifdef PRINT_TIMING_INFORMATION
30#include <hrtime.h>
31#include <util/papi_helper.hpp>
32#endif
33
34using namespace llvm;
35
36static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
37                                       "These are standard grep options intended for compatibility with typical grep usage.");
38
39#ifdef FUTURE
40static cl::OptionCategory RegexpOptions("Regular Expression Interpretation", "These options control regular expression interpretation");
41static cl::opt<re::RE_Syntax> RegexpSyntax(cl::desc("Regular expression syntax:"),
42    cl::values(
43        clEnumValN(re::RE_Syntax::FixedStrings, "F", "Fixed strings, separated by newlines"),
44        clEnumValN(re::RE_Syntax::BRE, "G", "Posix basic regular expression (BRE) syntax"),
45        clEnumValN(re::RE_Syntax::ERE, "E", "Posix extended regular expression (ERE) syntax"),
46        clEnumValN(re::RE_Syntax::PROSITE, "PRO", "PROSITE protein patterns syntax"),
47        clEnumValN(re::RE_Syntax::PCRE, "P", "Perl-compatible regular expression (PCRE) syntax - default"),
48               clEnumValEnd), cl::cat(LegacyGrepOptions), cl::Grouping, cl::init(re::RE_Syntax::PCRE));
49#endif
50
51static cl::opt<bool> EntireLineMatching("x", cl::desc("Require that entire lines be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
52static cl::alias  EntireLineMatchingAlias("line-regexp", cl::desc("Alias for -x"), cl::aliasopt(EntireLineMatching));
53
54static cl::opt<bool> WholeWordMatching("w", cl::desc("Require that whole words be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
55static cl::alias WholeWordMatchingAlias("word-regexp", cl::desc("Alias for -w"), cl::aliasopt(WholeWordMatching));
56
57static cl::opt<bool> UTF_16("UTF-16", cl::desc("Regular expressions over the UTF-16 representation of Unicode."), cl::cat(LegacyGrepOptions));
58static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
59                                       "These are additional options for icgrep functionality and performance.");
60
61static cl::opt<bool> FileNamesOnly("l", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
62static cl::alias FileNamesAlias("files-with-matches", cl::desc("Alias for -l"), cl::aliasopt(FileNamesOnly));
63
64static cl::opt<bool> NonMatchingFileNamesOnly("L", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
65static cl::alias NonMatchingFileNamesAlias("files-without-match", cl::desc("Alias for -L"), cl::aliasopt(NonMatchingFileNamesOnly));
66
67
68static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions), cl::Grouping);
69static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
70
71
72static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
73
74static cl::opt<bool> EnterDirectoriesRecursively("r", cl::desc("Recursively process files within directories, (but follow only top-level symlinks unless -R)."), cl::cat(LegacyGrepOptions), cl::Grouping);
75static cl::opt<bool> FollowSubdirectorySymlinks("R", cl::desc("Recursively process files within directories, following symlinks at all levels."), cl::cat(LegacyGrepOptions), cl::Grouping);
76static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions), cl::Grouping);
77static cl::alias CaseInsensitiveAlisas("ignore-case", cl::desc("Ignore case distinctions in the pattern and the file."), cl::aliasopt(CaseInsensitive));
78
79static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
80static cl::opt<std::string> RegexFilename("f", cl::desc("Take regular expressions (one per line) from a file"), cl::value_desc("regex file"), cl::init(""), cl::cat(LegacyGrepOptions));
81static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
82
83static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
84
85static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
86         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
87
88static cl::opt<bool> MultiGrepKernels("enable-multiGrep-kernels", cl::desc("Construct separated kernels for each regular expression"), cl::cat(EnhancedGrepOptions));
89
90static std::vector<std::string> allFiles;
91//
92// Handler for errors reported through llvm::report_fatal_error.  Report
93// and signal error code 2 (grep convention).
94//
95static void icgrep_error_handler(void *UserData, const std::string &Message, bool GenCrashDiag) {
96    #ifndef NDEBUG
97    throw std::runtime_error(Message);
98    #else
99    // Modified from LLVM's internal report_fatal_error logic.
100    SmallVector<char, 64> Buffer;
101    raw_svector_ostream OS(Buffer);
102    OS << "icgrep ERROR: " << Message << "\n";
103    StringRef MessageStr = OS.str();
104    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
105    (void)written; // If something went wrong, we deliberately just give up.
106    // Run the interrupt handlers to make sure any special cleanups get done, in
107    // particular that we remove files registered with RemoveFileOnSignal.
108    llvm::sys::RunInterruptHandlers();
109    exit(2);
110    #endif
111}
112
113static std::string allREs;
114static re::ModeFlagSet globalFlags = 0;
115std::vector<re::RE *> REs;
116
117re::RE * get_icgrep_RE() {
118 
119    //std::vector<std::string> regexVector;
120    if (RegexFilename != "") {
121        std::ifstream regexFile(RegexFilename.c_str());
122        std::string r;
123        if (regexFile.is_open()) {
124            while (std::getline(regexFile, r)) {
125                regexVector.push_back(r);
126            }
127            regexFile.close();
128        }
129    }
130   
131    // if there are no regexes specified through -e or -f, the first positional argument
132    // must be a regex, not an input file.
133   
134    if (regexVector.size() == 0) {
135        regexVector.push_back(inputFiles[0]);
136        inputFiles.erase(inputFiles.begin());
137    }
138    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
139
140
141    re::RE * re_ast = nullptr;
142    for (unsigned i = 0; i < regexVector.size(); i++) {
143#ifdef FUTURE
144        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags, RegexpSyntax);
145#else
146        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
147#endif
148        REs.push_back(re_ast);
149        allREs += regexVector[i] + "\n";
150    }
151    if (REs.size() > 1) {
152        re_ast = re::makeAlt(REs.begin(), REs.end());
153    }
154    if (WholeWordMatching) {
155        re_ast = re::makeSeq({re::makeWordBoundary(), re_ast, re::makeWordBoundary()});
156    }
157    if (EntireLineMatching) {
158        re_ast = re::makeSeq({re::makeStart(), re_ast, re::makeEnd()});
159    }   
160    return re_ast;
161}
162
163std::string sha1sum(const std::string & str) {
164    char buffer[41];    // 40 hex-digits and the terminating null
165    unsigned int digest[5];     // 160 bits in total
166
167    boost::uuids::detail::sha1 sha1;
168    sha1.process_bytes(str.c_str(), str.size());
169    sha1.get_digest(digest);
170    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
171             digest[0], digest[1], digest[2], digest[3], digest[4]);
172    return std::string(buffer);
173}
174
175std::vector<size_t> total_CountOnly;
176std::mutex count_mutex;
177size_t fileCount;
178void *DoGrep(void *args)
179{
180    size_t fileIdx;
181    GrepEngine * grepEngine = (GrepEngine *)args;
182
183    count_mutex.lock();
184    fileIdx = fileCount;
185    fileCount++;
186    count_mutex.unlock();
187
188    while (fileIdx < allFiles.size()){
189        grepEngine->doGrep(allFiles[fileIdx], fileIdx, CountOnly, total_CountOnly, UTF_16);
190       
191        count_mutex.lock();
192        fileIdx = fileCount;
193        fileCount++;
194        count_mutex.unlock();
195    }
196
197    pthread_exit(nullptr);
198}
199
200
201// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
202bool isArgUnwantedForAll(char *argument) {
203    std::vector<std::string> unwantedFlags = {"-gs"};
204    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
205        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
206            return true;
207        }
208    }
209    return false;
210}
211// Filters out the command line strings that shouldn't be passed on to Grep
212bool isArgUnwantedForGrep(char *argument) {
213#ifdef FUTURE
214    std::vector<std::string> unwantedFlags = {"-n", "-P", "-G", "-E", "-PRO"};
215#else
216    std::vector<std::string> unwantedFlags = {"-n"};
217#endif
218
219    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
220        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
221            return true;
222        }
223    }
224
225    for (unsigned i = 0; i < inputFiles.size(); ++i){    // filter out input content files.
226        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
227            return true;
228        }
229    }
230
231    return false;
232}
233// Filters out the command line strings that shouldn't be passed on to IcGrep
234bool isArgUnwantedForIcGrep(char *argument) {
235    bool isUnwanted = false;
236    std::vector<std::string> unwantedFlags = {"-c"};
237
238    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
239        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
240            isUnwanted = true;
241        }
242    }
243
244    return isUnwanted;
245}
246
247/*
248* Constructs a shell command that calls icgrep and then pipes the output to grep.
249* Then executs this shell command using the "system()" function.
250* This allows the output to be colored since all output is piped to grep.
251*/ 
252void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
253    std::string icGrepArguments = "";
254    std::string grepArguments = "";
255
256    // Construct the shell arguments for icgrep and grep
257    // by filtering out the command line arguments passed into this process.
258    for (int i = 1; i < argc; i++) {
259        if (!isArgUnwantedForAll(argv[i])) {
260
261            if (!isArgUnwantedForIcGrep(argv[i])) {
262                // Wrap everything in quotes since the arguments passed into this program had them stripped by bash.
263                icGrepArguments.append("\"");       
264                icGrepArguments.append(argv[i]);
265                icGrepArguments.append("\" ");
266            }
267
268            if (!isArgUnwantedForGrep(argv[i])) {
269                grepArguments.append("\"");
270                grepArguments.append(argv[i]);
271                grepArguments.append("\" ");
272            }
273        }
274    }
275
276#ifdef FUTURE
277    switch (RegexpSyntax) {
278        case re::RE_Syntax::BRE:
279            grepArguments.append("\"-G\" ");
280            break;
281        case re::RE_Syntax::ERE:
282            grepArguments.append("\"-E\" ");
283            break;
284        case re::RE_Syntax::PROSITE:
285            grepArguments.append("\"-PRO\" ");
286            break;
287        case re::RE_Syntax::PCRE:
288            grepArguments.append("\"-P\" ");
289            break;
290        default:
291            //TODO: handle fix string
292            break;
293    }
294#endif
295
296    std::string systemCall = argv[0];
297    systemCall.append(" ");
298    systemCall.append(icGrepArguments);
299    systemCall.append(" ");
300#ifdef FUTURE
301    systemCall.append(" | grep --color=always ");
302#else
303    systemCall.append(" | grep --color=always -P ");
304#endif
305    systemCall.append(grepArguments);
306
307    const auto rc = system(systemCall.c_str());
308    if (LLVM_UNLIKELY(rc < 0)) {
309        throw std::runtime_error("Error calling grep: " + std::string(strerror(errno)));
310    }
311}
312
313
314// This is a stub, to be expanded later.
315bool excludeDirectory(boost::filesystem::path dirpath) { return dirpath.filename() == ".svn";}
316
317std::vector<std::string> getFullFileList(cl::list<std::string> & inputFiles) {
318    using namespace boost::filesystem;
319    symlink_option follow_symlink = FollowSubdirectorySymlinks ? symlink_option::recurse : symlink_option::none;
320    std::vector<std::string> expanded_paths;
321    boost::system::error_code errc;
322    if (FollowSubdirectorySymlinks) {
323        EnterDirectoriesRecursively = true;
324    }
325    for (auto & f : inputFiles) {
326        path p(f);
327        if (EnterDirectoriesRecursively && is_directory(p)) {
328            if (!excludeDirectory(p)) {
329                recursive_directory_iterator di(p, follow_symlink, errc), end;
330                if (errc) {
331                    // If we cannot enter the directory, keep it in the list of files.
332                    expanded_paths.push_back(f); 
333                    continue;
334                }
335                while (di != end) {
336                    auto & e = di->path();
337                    if (is_directory(e)) {
338                        if (excludeDirectory(e)) di.no_push();
339                    }
340                    else expanded_paths.push_back(e.string());
341                    di.increment(errc);
342                    if (errc) {
343                        expanded_paths.push_back(e.string()); 
344                    }
345                }
346            }
347        }
348        else expanded_paths.push_back(p.string());
349    }
350    return expanded_paths;
351}
352
353
354int main(int argc, char *argv[]) {
355    llvm::install_fatal_error_handler(&icgrep_error_handler);
356#ifndef USE_LLVM_3_6
357    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
358#endif
359    cl::ParseCommandLineOptions(argc, argv);
360#ifdef FUTURE
361    if (RegexpSyntax == re::RE_Syntax::FixedStrings) {
362        llvm::report_fatal_error("Sorry, FixedStrings syntax is not fully supported\n.");
363    }
364#endif
365    re::RE * re_ast = get_icgrep_RE();
366    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
367   
368    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
369        pipeIcGrepOutputToGrep(argc, argv);
370        return 0;   // icgrep is called again, so we need to end this process.
371    }
372   
373    GrepEngine grepEngine;
374    if(MultiGrepKernels){
375        grepEngine.multiGrepCodeGen(module_name, REs, CountOnly, UTF_16);
376    }
377    else{
378        grepEngine.grepCodeGen(module_name, re_ast, CountOnly, UTF_16);
379    }
380
381    allFiles = getFullFileList(inputFiles);
382   
383    if (FileNamesOnly && NonMatchingFileNamesOnly) {
384        // Strange request: print names of all matching files and all non-matching files: i.e., all of them.
385        // (Although GNU grep prints nothing.)
386        for (auto & f : allFiles) {
387            if (boost::filesystem::exists(f)) {
388                std::cout << f << "\n";
389            } else {
390                std::cerr << "Error: cannot open " << f << " for processing. Skipped.\n";
391            }
392        }
393        exit(0);
394    }
395    if (FileNamesOnly) {
396        llvm::report_fatal_error("Sorry, -l/-files-with-matches not yet supported\n.");
397    }
398    if (NonMatchingFileNamesOnly) {
399        llvm::report_fatal_error("Sorry, -L/-files-without-match not yet supported\n.");
400    }
401   
402    initResult(allFiles);
403    for (unsigned i=0; i < allFiles.size(); ++i){
404        total_CountOnly.push_back(0);
405    }
406
407    if (Threads <= 1) {
408
409        #ifdef PRINT_TIMING_INFORMATION
410        // PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY
411        // PAPI_RES_STL, PAPI_BR_MSP, PAPI_LST_INS, PAPI_L1_TCM
412        papi::PapiCounter<4> papiCounters({PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY});
413        #endif
414        for (unsigned i = 0; i != allFiles.size(); ++i) {
415            #ifdef PRINT_TIMING_INFORMATION
416            papiCounters.start();
417            const timestamp_t execution_start = read_cycle_counter();
418            #endif
419            grepEngine.doGrep(allFiles[i], i, CountOnly, total_CountOnly, UTF_16);
420            #ifdef PRINT_TIMING_INFORMATION
421            const timestamp_t execution_end = read_cycle_counter();
422            papiCounters.stop();
423            std::cerr << "EXECUTION TIME: " << allFiles[i] << ":" << "CYCLES|" << (execution_end - execution_start) << papiCounters << std::endl;
424            #endif
425        }       
426    } else if (Threads > 1) {
427        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
428        pthread_t threads[numOfThreads];
429
430        for(unsigned long i = 0; i < numOfThreads; ++i){
431            const int rc = pthread_create(&threads[i], nullptr, DoGrep, (void *)&grepEngine);
432            if (rc) {
433                llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
434            }
435        }
436
437        for(unsigned i = 0; i < numOfThreads; ++i) {
438            void * status = nullptr;
439            const int rc = pthread_join(threads[i], &status);
440            if (rc) {
441                llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
442            }
443        }
444    }
445   
446    PrintResult(CountOnly, total_CountOnly);
447   
448    return 0;
449}
Note: See TracBrowser for help on using the repository browser.