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

Last change on this file since 4990 was 4990, checked in by cameron, 3 years ago

Fix for first positional arg not a filename

File size: 7.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
9#include <llvm/Support/CommandLine.h>
10#include <re/re_alt.h>
11#include <re/re_parser.h>
12#include <grep_engine.h>
13#include <fstream>
14#include <string>
15
16#include <boost/uuid/sha1.hpp>
17#include <toolchain.h>
18#include <mutex>
19
20static cl::OptionCategory aRegexSourceOptions("Regular Expression Options",
21                                       "These options control the regular expression source.");
22
23// static cl::OptionCategory bGrepOutputOptions("Output Options",
24//                                       "These options control the output.");
25
26static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
27
28// static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
29// static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
30// static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
31
32// static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
33// static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
34
35static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(aRegexSourceOptions));
36// static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
37// static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
38
39static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(aRegexSourceOptions));
40static 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(aRegexSourceOptions));
41static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""), cl::cat(aRegexSourceOptions));
42
43static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
44
45
46
47static unsigned firstInputFile = 1;  // Normal case when first positional arg is a regex.
48static std::string allREs;
49static re::ModeFlagSet globalFlags = 0;
50
51re::RE * get_icgrep_RE() {
52 
53    //std::vector<std::string> regexVector;
54    if (RegexFilename != "") {
55        std::ifstream regexFile(RegexFilename.c_str());
56        std::string r;
57        if (regexFile.is_open()) {
58            while (std::getline(regexFile, r)) {
59                regexVector.push_back(r);
60            }
61            regexFile.close();
62        }
63    }
64   
65    // if there are no regexes specified through -e or -f, the first positional argument
66    // must be a regex, not an input file.
67   
68    if (regexVector.size() == 0) {
69        regexVector.push_back(inputFiles[0]);
70        firstInputFile = 1;
71    }
72    else {
73        firstInputFile = 0;
74    }
75   
76    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
77
78 
79    std::vector<re::RE *> REs;
80    re::RE * re_ast = nullptr;
81    for (unsigned i = 0; i < regexVector.size(); i++) {
82        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
83        REs.push_back(re_ast);
84        allREs += regexVector[i] + "\n";
85    }
86    if (REs.size() > 1) {
87        re_ast = re::makeAlt(REs.begin(), REs.end());
88    }
89   
90    return re_ast;
91}
92
93std::string sha1sum(const std::string & str) {
94    char buffer[41];    // 40 hex-digits and the terminating null
95    unsigned int digest[5];     // 160 bits in total
96
97    boost::uuids::detail::sha1 sha1;
98    sha1.process_bytes(str.c_str(), str.size());
99    sha1.get_digest(digest);
100    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
101             digest[0], digest[1], digest[2], digest[3], digest[4]);
102    return std::string(buffer);
103}
104
105std::mutex count_mutex;
106size_t fileCount;
107void *DoGrep(void *args)
108{
109    size_t fileIdx;
110    GrepEngine * grepEngine = (GrepEngine *)args;
111
112    count_mutex.lock();
113    fileCount++;
114    fileIdx = fileCount;
115    count_mutex.unlock();
116
117    while (fileIdx < inputFiles.size()){
118        grepEngine->doGrep(inputFiles[fileIdx]);
119       
120        count_mutex.lock();
121        fileCount++;
122        fileIdx = fileCount;
123        count_mutex.unlock();
124    }
125
126    pthread_exit(NULL);
127}
128
129int main(int argc, char *argv[]) {
130    StringMap<cl::Option*> Map;
131    cl::getRegisteredOptions(Map);
132    Map["time-passes"]->setHiddenFlag(cl::Hidden);
133    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
134    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
135    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
136    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
137    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
138    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
139    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
140    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
141    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
142    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
143    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
144    Map["regalloc"]->setHiddenFlag(cl::Hidden);
145    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
146    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
147    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
148    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
149    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
150    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
151    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
152    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
153    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
154    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
155
156    cl::ParseCommandLineOptions(argc, argv);
157   
158    re::RE * re_ast = get_icgrep_RE();
159    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
160   
161    GrepEngine grepEngine;
162    grepEngine.grepCodeGen(module_name, re_ast);
163
164    initResult(inputFiles, firstInputFile, inputFiles.size());
165    if (Threads <= 1) {
166        for (unsigned i = firstInputFile; i != inputFiles.size(); ++i) {
167            grepEngine.doGrep(inputFiles[i]);
168        }       
169    } else if (Threads > 1) {
170        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
171        pthread_t threads[numOfThreads];
172
173        for(unsigned long i = 0; i < numOfThreads; ++i){
174            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
175            if (rc) {
176                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
177            }
178        }
179
180        for(unsigned i = 0; i < numOfThreads; ++i) {
181            void * status = nullptr;
182            const int rc = pthread_join(threads[i], &status);
183            if (rc) {
184                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
185            }
186        }
187    }
188    PrintResult();   
189   
190    return 0;
191}
Note: See TracBrowser for help on using the repository browser.