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

Last change on this file since 4972 was 4972, checked in by lindanl, 3 years ago

multithreading with arbitrary number of threads and input files.

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
105GrepEngine grepEngine;
106std::mutex count_mutex;
107
108size_t fileCount;
109void *DoGrep(void *threadid)
110{
111    long tid;
112    tid = (long)threadid;
113    size_t fileIdx;
114
115    count_mutex.lock();
116    fileCount++;
117    fileIdx = fileCount;
118    count_mutex.unlock();
119   
120    while (fileIdx < inputFiles.size()){
121        grepEngine.doGrep(inputFiles[fileIdx]);
122       
123        count_mutex.lock();
124        fileCount++;
125        fileIdx = fileCount;
126        count_mutex.unlock();
127    }
128
129    pthread_exit(NULL);
130}
131
132int main(int argc, char *argv[]) {
133    StringMap<cl::Option*> Map;
134    cl::getRegisteredOptions(Map);
135    Map["time-passes"]->setHiddenFlag(cl::Hidden);
136    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
137    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
138    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
139    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
140    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
141    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
142    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
143    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
144    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
145    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
146    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
147    Map["regalloc"]->setHiddenFlag(cl::Hidden);
148    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
149    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
150    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
151    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
152    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
153    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
154    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
155    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
156    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
157    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
158
159    cl::ParseCommandLineOptions(argc, argv);
160   
161    re::RE * re_ast = get_icgrep_RE();
162    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
163   
164    grepEngine.grepCodeGen(module_name, re_ast);
165
166    initResult(inputFiles, inputFiles.size());
167    if (Threads <= 1) {
168        for (unsigned i = firstInputFile; i != inputFiles.size(); ++i) {
169            grepEngine.doGrep(inputFiles[i]);
170        }       
171    } else if (Threads > 1) {
172        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
173        pthread_t threads[numOfThreads];
174
175        for(unsigned long i = 0; i < numOfThreads; ++i){
176            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)i);
177            if (rc) {
178                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
179            }
180        }
181
182        for(unsigned i = 0; i < numOfThreads; ++i) {
183            void * status = nullptr;
184            const int rc = pthread_join(threads[i], &status);
185            if (rc) {
186                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
187            }
188        }
189    }
190    PrintResult();   
191   
192    return 0;
193}
Note: See TracBrowser for help on using the repository browser.