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

Last change on this file since 4755 was 4755, checked in by lindanl, 4 years ago

Add an option to use AVX2 instructions.

File size: 16.5 KB
RevLine 
[3850]1/*
[4544]2 *  Copyright (c) 2015 International Characters.
[3850]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
[4327]7#include <string>
[4328]8#include <iostream>
9#include <fstream>
[4327]10
[3965]11#include "icgrep.h"
[3850]12#include "utf_encoding.h"
[4324]13#include "pablo/pablo_compiler.h"
[4730]14#include <llvm/IR/Function.h>
[4732]15#include <llvm/IR/Module.h>
[4730]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>
[4734]23
[4732]24#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
25#include <UCD/precompiled_properties.h>
26#endif
[4734]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>
[4730]46
[4324]47#include "do_grep.h"
[3850]48
[4544]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));
[4734]70static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""), cl::cat(aRegexSourceOptions));
[4544]71
[4734]72static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
73                                      "These options control printing of intermediate regular expression structures.");
[4544]74
[4734]75static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options",
76                                      "These options control printing of intermediate Pablo code.");
[4730]77
[4734]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
[4755]103static cl::opt<bool> UseAVX2("use-AVX2", cl::init(false), cl::desc("execute with AVX2 instruction set."), cl::cat(cRegexOutputOptions));
104
[4750]105static unsigned firstInputFile = 1;  // Normal case when first positional arg is a regex.
[4734]106
107re::RE * get_icgrep_RE() {
108 
109    //std::vector<std::string> regexVector;
110    if (RegexFilename != "") {
111        std::ifstream regexFile(RegexFilename.c_str());
112        std::string r;
113        if (regexFile.is_open()) {
114            while (std::getline(regexFile, r)) {
115                regexVector.push_back(r);
116            }
117            regexFile.close();
118        }
119    }
120   
121    // if there are no regexes specified through -e or -f, the first positional argument
122    // must be a regex, not an input file.
123   
124    if (regexVector.size() == 0) {
125        regexVector.push_back(inputFiles[0]);
126        firstInputFile = 1;
127    }
128    else {
129        firstInputFile = 0;
130    }
131   
132    re::ModeFlagSet globalFlags = 0;
133    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
134
135 
136    std::vector<re::RE *> REs;
137    re::RE * re_ast = nullptr;
[4750]138    for (unsigned i = 0; i < regexVector.size(); i++) {
[4734]139        try
140        {
141            re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
142        }
143        catch (ParseFailure failure)
144        {
145            std::cerr << "Regex parsing failure: " << failure.what() << std::endl;
146            std::cerr << regexVector[i] << std::endl;
147            exit(1);
148        }
[4737]149        catch (UCD::UnicodePropertyExpressionError e)
150        {
151            std::cerr << "Unicode error: " << e.what() << std::endl;
152            std::cerr << regexVector[i] << std::endl;
153            exit(1);
154        }
[4734]155        REs.push_back(re_ast);
156    }
157    if (REs.size() > 1) {
158        re_ast = re::makeAlt(REs.begin(), REs.end());
159    }
160   
161    if (PrintAllREs || PrintParsedREs) {
162        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
163    }
164    return re_ast;
165}
166
167re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
168    //Optimization passes to simplify the AST.
169    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
170    if (PrintAllREs || PrintStrippedREs) {
171        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
172    }
173    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
174    if (PrintAllREs || PrintStrippedREs) {
175        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
176    }
177   
178    cc::CC_NameMap nameMap;
179    re_ast = nameMap.process(re_ast, re::UnicodeClass);
180   
181    // std::cerr << "-----------------------------" << std::endl;
182   
183    if (PrintAllREs || PrintNamedREs) {
184        std::cerr << "Namer:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
185        std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
186    }
187   
188    //Add the UTF encoding.
189    if (encoding.getType() == Encoding::Type::UTF_8) {
190        re_ast = cc::UTF8_Encoder::toUTF8(nameMap, re_ast);
191        if (PrintAllREs || PrintUTF8REs) {
192            //Print to the terminal the AST that was generated by the utf8 encoder.
193            std::cerr << "UTF8-encoder:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
194            std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
195        }
196    }
197   
198    re_ast = re::RE_Simplifier::simplify(re_ast);
199    if (PrintAllREs || PrintSimplifiedREs) {
200        //Print to the terminal the AST that was generated by the simplifier.
201        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
202    }
203    return re_ast;
204}
205   
206pablo::PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
207   
208    pablo::PabloFunction * function = pablo::PabloFunction::Create("process_block", 8, 2);
209   
210    cc::CC_Compiler cc_compiler(*function, encoding);
211   
212    cc_compiler.compileByteClasses(re_ast);
213   
214    if (PrintCompiledCCcode) {
215        //Print to the terminal the AST that was generated by the character class compiler.
216        llvm::raw_os_ostream cerr(std::cerr);
217        cerr << "CC AST:" << "\n";
218        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
219    }
220   
221    re::RE_Compiler re_compiler(*function, cc_compiler);
222    re_compiler.initializeRequiredStreams();
223    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
224   
225    if (PrintCompiledREcode) {
226        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
227        llvm::raw_os_ostream cerr(std::cerr);
228        cerr << "Initial Pablo AST:\n";
229        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
230    }
231    return function;
232}
233
234void pablo_function_passes(pablo::PabloFunction * function) {
235    // Scan through the pablo code and perform DCE and CSE
236    if (!DisablePabloCSE) {
237        pablo::Simplifier::optimize(*function);
238    }
239    if (PabloSinkingPass) {
240        pablo::CodeSinking::optimize(*function);
241    }
242#ifdef ENABLE_MULTIPLEXING
243    if (EnableMultiplexing) {
244        pablo::AutoMultiplexing::optimize(*function);
245    }
246#endif
247    if (PrintOptimizedREcode) {
248        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
249        llvm::raw_os_ostream cerr(std::cerr);
250        cerr << "Final Pablo AST:\n";
251        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
252    }
253}
254
255
256
[4730]257ExecutionEngine * JIT_to_ExecutionEngine (llvm::Function * f) {
258
259    InitializeNativeTarget();
260    InitializeNativeTargetAsmPrinter();
261    InitializeNativeTargetAsmParser();
262
263    std::string errMessage;
264    EngineBuilder builder(std::move(std::unique_ptr<Module>(f->getParent())));
265    builder.setErrorStr(&errMessage);
266    builder.setMCPU(sys::getHostCPUName());
[4731]267    builder.setOptLevel(CodeGenOpt::Level::None);
[4755]268#if (BLOCK_SIZE == 256)
269    if(UseAVX2){
270            std::vector<std::string> attrs;
271            attrs.push_back("avx2");
272            builder.setMAttrs(attrs);
273    }
274#endif
[4730]275    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
276    ExecutionEngine * engine = builder.create();
277    if (engine == nullptr) {
278        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
279    }
280    //engine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
281    // engine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
282
283    return engine;
284}
285
286
[4731]287extern "C" {
288  void wrapped_print_register(char * regName, BitBlock bit_block) {
289      print_register<BitBlock>(regName, bit_block);
290  }
291}
292
293void icgrep_Linking(Module * m, ExecutionEngine * e) {
[4732]294    Module::FunctionListType & fns = m->getFunctionList();
295    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
296        std::string fnName = it->getName().str();
297        if (fnName == "process_block") continue;
298        if (fnName == "wrapped_print_register") {
299            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
300        }
301#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
302        else {
303            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
304            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
305        }
306#endif
[4731]307    }
308}
309
310
[4325]311int main(int argc, char *argv[]) {
[4353]312    StringMap<cl::Option*> Map;
313    cl::getRegisteredOptions(Map);
314    Map["time-passes"]->setHiddenFlag(cl::Hidden);
315    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
316    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
317    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
318    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
319    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
320    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
321    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
322    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
323    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
324    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
325    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
326    Map["regalloc"]->setHiddenFlag(cl::Hidden);
327    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
328    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
329    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
330    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
331    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
332    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
333    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
334    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
[4572]335    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
336    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
337
[4544]338    cl::ParseCommandLineOptions(argc, argv);
[4353]339   
[4325]340    Encoding encoding(Encoding::Type::UTF_8, 8);
[3914]341
[4734]342    llvm::Function * icgrep_IR = nullptr;
[4328]343   
[4734]344    if (IRFileName == "") {       
345        re::RE * re_ast = get_icgrep_RE();
346        re_ast = regular_expression_passes(encoding, re_ast);
347       
348        pablo::PabloFunction * function = re2pablo_compiler(encoding, re_ast);
349
350        pablo_function_passes(function);
351        pablo::PabloCompiler pablo_compiler;
352        try {
353            icgrep_IR = pablo_compiler.compile(function);
354            releaseSlabAllocatorMemory();
[4328]355        }
[4734]356        catch (std::runtime_error e) {
357            releaseSlabAllocatorMemory();
358            std::cerr << "Runtime error: " << e.what() << std::endl;
359            exit(1);
360        }
[4328]361    }
362    else {
[4734]363        firstInputFile = 0;  // No regexp arguments; first positional argument is a file to process.
364        SMDiagnostic ParseErr;
365        Module * M = parseIRFile(IRFileName, ParseErr, getGlobalContext()).release();
366        if (!M) {
367            throw std::runtime_error("Error in Parsing IR File " + IRFileName);
368        }
369        icgrep_IR = M->getFunction("process_block");
[4328]370    }
371   
[4731]372    llvm::ExecutionEngine * engine = JIT_to_ExecutionEngine(icgrep_IR);
[4730]373   
[4731]374    icgrep_Linking(icgrep_IR->getParent(), engine);
[4730]375   
[4731]376    // Ensure everything is ready to go.
377    engine->finalizeObject();
[4730]378   
[4731]379    void * icgrep_MCptr = engine->getPointerToFunction(icgrep_IR);
380   
381    if (icgrep_MCptr) {
382        GrepExecutor grepEngine = GrepExecutor(icgrep_MCptr);
[4325]383        grepEngine.setCountOnlyOption(CountOnly);
[4460]384        grepEngine.setNormalizeLineBreaksOption(NormalizeLineBreaks);
[4327]385        grepEngine.setShowLineNumberOption(ShowLineNumbers);
[4328]386            if (inputFiles.size() > (firstInputFile + 1) || ShowFileNames) {
387            grepEngine.setShowFileNameOption();
388        }
389        for (unsigned i = firstInputFile; i != inputFiles.size(); ++i) {
[4325]390            grepEngine.doGrep(inputFiles[i].c_str());
391        }
[3850]392    }
[4327]393   
[4731]394    //engine->freeMachineCodeForFunction(icgrep_IR); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
[4730]395    delete engine;
396
[3850]397    return 0;
398}
399
Note: See TracBrowser for help on using the repository browser.