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

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

Progress on multi-target UCD compiler.

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