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

Last change on this file since 4788 was 4788, checked in by nmedfort, 4 years ago

Misc changes + potential SIGBUS fix for issue reported by Hongpu.

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