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

Last change on this file since 4737 was 4737, checked in by cameron, 4 years ago

Handle arbitrary enumerated properties without special casing; improve error reporting

File size: 16.2 KB
Line 
1/*
2 *  Copyright (c) 2015 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 <string>
8#include <iostream>
9#include <fstream>
10
11#include "icgrep.h"
12#include "utf_encoding.h"
13#include "pablo/pablo_compiler.h"
14#include <llvm/IR/Function.h>
15#include <llvm/IR/Module.h>
16#include <llvm/ExecutionEngine/ExecutionEngine.h>
17#include <llvm/ExecutionEngine/MCJIT.h>
18#include <llvm/IRReader/IRReader.h>
19#include <llvm/Support/SourceMgr.h>
20#include <llvm/Support/CommandLine.h>
21#include <llvm/Support/TargetSelect.h>
22#include <llvm/Support/Host.h>
23
24#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
25#include <UCD/precompiled_properties.h>
26#endif
27#include <re/re_cc.h>
28#include <re/re_nullable.h>
29#include <re/re_simplifier.h>
30#include <re/re_alt.h>
31#include <re/parsefailure.h>
32#include <re/re_parser.h>
33#include <re/re_compiler.h>
34#include <utf8_encoder.h>
35#include <cc/cc_compiler.h>
36#include <cc/cc_namemap.hpp>
37#include <pablo/pablo_compiler.h>
38#include <pablo/optimizers/pablo_simplifier.hpp>
39#include <pablo/optimizers/pablo_codesinking.hpp>
40#ifdef ENABLE_MULTIPLEXING
41#include <pablo/optimizers/pablo_automultiplexing.hpp>
42#endif
43#include <pablo/function.h>
44#include <re/printer_re.h>
45#include <pablo/printer_pablos.h>
46
47#include "do_grep.h"
48
49static cl::OptionCategory aRegexSourceOptions("Regular Expression Options",
50                                       "These options control the regular expression source.");
51
52static cl::OptionCategory bGrepOutputOptions("Output Options",
53                                      "These options control the output.");
54
55static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
56
57static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
58static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
59static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
60
61static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
62static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
63
64static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(aRegexSourceOptions));
65static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
66static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
67
68static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(aRegexSourceOptions));
69static 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));
70static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""), cl::cat(aRegexSourceOptions));
71
72static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
73                                      "These options control printing of intermediate regular expression structures.");
74
75static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options",
76                                      "These options control printing of intermediate Pablo code.");
77
78static cl::opt<bool> PrintAllREs("print-REs", cl::init(false), cl::desc("print regular expression passes"), cl::cat(cRegexOutputOptions));
79static cl::opt<bool> PrintParsedREs("print-parsed-REs", cl::init(false), cl::desc("print out parsed regular expressions"), cl::cat(cRegexOutputOptions));
80static cl::opt<bool> PrintStrippedREs("print-stripped-REs", cl::init(false), cl::desc("print out REs with nullable prefixes/suffixes removed"), cl::cat(cRegexOutputOptions));
81static cl::opt<bool> PrintNamedREs("print-named-REs", cl::init(false), cl::desc("print out named REs"), cl::cat(cRegexOutputOptions));
82static cl::opt<bool> PrintUTF8REs("print-utf8-REs", cl::init(false), cl::desc("print out UTF-8 REs"), cl::cat(cRegexOutputOptions));
83static cl::opt<bool> PrintSimplifiedREs("print-simplified-REs", cl::init(false), cl::desc("print out final simplified REs"), cl::cat(cRegexOutputOptions));
84static cl::opt<bool> PrintCompiledCCcode("print-CC-pablo", cl::init(false), cl::desc("print Pablo output from character class compiler"), cl::cat(dPabloDumpOptions));
85static cl::opt<bool> PrintCompiledREcode("print-RE-pablo", cl::init(false), cl::desc("print Pablo output from the regular expression compiler"), cl::cat(dPabloDumpOptions));
86static cl::opt<bool> PrintOptimizedREcode("print-pablo", cl::init(false), cl::desc("print final optimized Pablo code"), cl::cat(dPabloDumpOptions));
87
88static cl::OptionCategory cPabloOptimizationsOptions("Pablo Optimizations", "These options control Pablo optimization passes.");
89
90static cl::opt<bool> DisablePabloCSE("disable-CSE", cl::init(false),
91                                      cl::desc("Disable Pablo common subexpression elimination/dead code elimination"),
92                                      cl::cat(cPabloOptimizationsOptions));
93static cl::opt<bool> PabloSinkingPass("sinking", cl::init(false),
94                                      cl::desc("Moves all instructions into the innermost legal If-scope so that they are only executed when needed."),
95                                      cl::cat(cPabloOptimizationsOptions));
96
97#ifdef ENABLE_MULTIPLEXING
98static cl::opt<bool> EnableMultiplexing("multiplexing", cl::init(false),
99    cl::desc("combine Advances whose inputs are mutual exclusive into the fewest number of advances possible (expensive)."),
100    cl::cat(cPabloOptimizationsOptions));
101#endif
102
103static int firstInputFile = 1;  // Normal case when first positional arg is a regex.
104
105re::RE * get_icgrep_RE() {
106 
107    //std::vector<std::string> regexVector;
108    if (RegexFilename != "") {
109        std::ifstream regexFile(RegexFilename.c_str());
110        std::string r;
111        if (regexFile.is_open()) {
112            while (std::getline(regexFile, r)) {
113                regexVector.push_back(r);
114            }
115            regexFile.close();
116        }
117    }
118   
119    // if there are no regexes specified through -e or -f, the first positional argument
120    // must be a regex, not an input file.
121   
122    if (regexVector.size() == 0) {
123        regexVector.push_back(inputFiles[0]);
124        firstInputFile = 1;
125    }
126    else {
127        firstInputFile = 0;
128    }
129   
130    re::ModeFlagSet globalFlags = 0;
131    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
132
133 
134    std::vector<re::RE *> REs;
135    re::RE * re_ast = nullptr;
136    for (int i = 0; i < regexVector.size(); i++) {
137        try
138        {
139            re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
140        }
141        catch (ParseFailure failure)
142        {
143            std::cerr << "Regex parsing failure: " << failure.what() << std::endl;
144            std::cerr << regexVector[i] << std::endl;
145            exit(1);
146        }
147        catch (UCD::UnicodePropertyExpressionError e)
148        {
149            std::cerr << "Unicode error: " << e.what() << std::endl;
150            std::cerr << regexVector[i] << std::endl;
151            exit(1);
152        }
153        REs.push_back(re_ast);
154    }
155    if (REs.size() > 1) {
156        re_ast = re::makeAlt(REs.begin(), REs.end());
157    }
158   
159    if (PrintAllREs || PrintParsedREs) {
160        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
161    }
162    return re_ast;
163}
164
165re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
166    //Optimization passes to simplify the AST.
167    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
168    if (PrintAllREs || PrintStrippedREs) {
169        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
170    }
171    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
172    if (PrintAllREs || PrintStrippedREs) {
173        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
174    }
175   
176    cc::CC_NameMap nameMap;
177    re_ast = nameMap.process(re_ast, re::UnicodeClass);
178   
179    // std::cerr << "-----------------------------" << std::endl;
180   
181    if (PrintAllREs || PrintNamedREs) {
182        std::cerr << "Namer:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
183        std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
184    }
185   
186    //Add the UTF encoding.
187    if (encoding.getType() == Encoding::Type::UTF_8) {
188        re_ast = cc::UTF8_Encoder::toUTF8(nameMap, re_ast);
189        if (PrintAllREs || PrintUTF8REs) {
190            //Print to the terminal the AST that was generated by the utf8 encoder.
191            std::cerr << "UTF8-encoder:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
192            std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
193        }
194    }
195   
196    re_ast = re::RE_Simplifier::simplify(re_ast);
197    if (PrintAllREs || PrintSimplifiedREs) {
198        //Print to the terminal the AST that was generated by the simplifier.
199        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
200    }
201    return re_ast;
202}
203   
204pablo::PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
205   
206    pablo::PabloFunction * function = pablo::PabloFunction::Create("process_block", 8, 2);
207   
208    cc::CC_Compiler cc_compiler(*function, encoding);
209   
210    cc_compiler.compileByteClasses(re_ast);
211   
212    if (PrintCompiledCCcode) {
213        //Print to the terminal the AST that was generated by the character class compiler.
214        llvm::raw_os_ostream cerr(std::cerr);
215        cerr << "CC AST:" << "\n";
216        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
217    }
218   
219    re::RE_Compiler re_compiler(*function, cc_compiler);
220    re_compiler.initializeRequiredStreams();
221    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
222   
223    if (PrintCompiledREcode) {
224        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
225        llvm::raw_os_ostream cerr(std::cerr);
226        cerr << "Initial Pablo AST:\n";
227        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
228    }
229    return function;
230}
231
232void pablo_function_passes(pablo::PabloFunction * function) {
233    // Scan through the pablo code and perform DCE and CSE
234    if (!DisablePabloCSE) {
235        pablo::Simplifier::optimize(*function);
236    }
237    if (PabloSinkingPass) {
238        pablo::CodeSinking::optimize(*function);
239    }
240#ifdef ENABLE_MULTIPLEXING
241    if (EnableMultiplexing) {
242        pablo::AutoMultiplexing::optimize(*function);
243    }
244#endif
245    if (PrintOptimizedREcode) {
246        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
247        llvm::raw_os_ostream cerr(std::cerr);
248        cerr << "Final Pablo AST:\n";
249        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
250    }
251}
252
253
254
255ExecutionEngine * JIT_to_ExecutionEngine (llvm::Function * f) {
256
257    InitializeNativeTarget();
258    InitializeNativeTargetAsmPrinter();
259    InitializeNativeTargetAsmParser();
260
261    std::string errMessage;
262    EngineBuilder builder(std::move(std::unique_ptr<Module>(f->getParent())));
263    builder.setErrorStr(&errMessage);
264    builder.setMCPU(sys::getHostCPUName());
265    builder.setOptLevel(CodeGenOpt::Level::None);
266    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
267    ExecutionEngine * engine = builder.create();
268    if (engine == nullptr) {
269        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
270    }
271    //engine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
272    // engine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
273
274    return engine;
275}
276
277
278extern "C" {
279  void wrapped_print_register(char * regName, BitBlock bit_block) {
280      print_register<BitBlock>(regName, bit_block);
281  }
282}
283
284void icgrep_Linking(Module * m, ExecutionEngine * e) {
285    Module::FunctionListType & fns = m->getFunctionList();
286    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
287        std::string fnName = it->getName().str();
288        if (fnName == "process_block") continue;
289        if (fnName == "wrapped_print_register") {
290            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
291        }
292#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
293        else {
294            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
295            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
296        }
297#endif
298    }
299}
300
301
302int main(int argc, char *argv[]) {
303    StringMap<cl::Option*> Map;
304    cl::getRegisteredOptions(Map);
305    Map["time-passes"]->setHiddenFlag(cl::Hidden);
306    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
307    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
308    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
309    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
310    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
311    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
312    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
313    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
314    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
315    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
316    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
317    Map["regalloc"]->setHiddenFlag(cl::Hidden);
318    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
319    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
320    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
321    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
322    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
323    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
324    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
325    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
326    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
327    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
328
329    cl::ParseCommandLineOptions(argc, argv);
330   
331    Encoding encoding(Encoding::Type::UTF_8, 8);
332
333    llvm::Function * icgrep_IR = nullptr;
334   
335    if (IRFileName == "") {       
336        re::RE * re_ast = get_icgrep_RE();
337        re_ast = regular_expression_passes(encoding, re_ast);
338       
339        pablo::PabloFunction * function = re2pablo_compiler(encoding, re_ast);
340
341        pablo_function_passes(function);
342        pablo::PabloCompiler pablo_compiler;
343        try {
344            icgrep_IR = pablo_compiler.compile(function);
345            releaseSlabAllocatorMemory();
346        }
347        catch (std::runtime_error e) {
348            releaseSlabAllocatorMemory();
349            std::cerr << "Runtime error: " << e.what() << std::endl;
350            exit(1);
351        }
352    }
353    else {
354        firstInputFile = 0;  // No regexp arguments; first positional argument is a file to process.
355        SMDiagnostic ParseErr;
356        Module * M = parseIRFile(IRFileName, ParseErr, getGlobalContext()).release();
357        if (!M) {
358            throw std::runtime_error("Error in Parsing IR File " + IRFileName);
359        }
360        icgrep_IR = M->getFunction("process_block");
361    }
362   
363    llvm::ExecutionEngine * engine = JIT_to_ExecutionEngine(icgrep_IR);
364   
365    icgrep_Linking(icgrep_IR->getParent(), engine);
366   
367    // Ensure everything is ready to go.
368    engine->finalizeObject();
369   
370    void * icgrep_MCptr = engine->getPointerToFunction(icgrep_IR);
371   
372    if (icgrep_MCptr) {
373        GrepExecutor grepEngine = GrepExecutor(icgrep_MCptr);
374        grepEngine.setCountOnlyOption(CountOnly);
375        grepEngine.setNormalizeLineBreaksOption(NormalizeLineBreaks);
376        grepEngine.setShowLineNumberOption(ShowLineNumbers);
377            if (inputFiles.size() > (firstInputFile + 1) || ShowFileNames) {
378            grepEngine.setShowFileNameOption();
379        }
380        for (unsigned i = firstInputFile; i != inputFiles.size(); ++i) {
381            grepEngine.doGrep(inputFiles[i].c_str());
382        }
383    }
384   
385    //engine->freeMachineCodeForFunction(icgrep_IR); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
386    delete engine;
387
388    return 0;
389}
390
Note: See TracBrowser for help on using the repository browser.