source: icGREP/icgrep-devel/icgrep/toolchain.cpp @ 4890

Last change on this file since 4890 was 4890, checked in by nmedfort, 3 years ago

Continued work on multiplexing pass.

File size: 10.8 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 "basis_bits.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/CommandLine.h>
20#include <llvm/CodeGen/CommandFlags.h>
21#include <llvm/Support/SourceMgr.h>
22#include <llvm/Support/TargetSelect.h>
23#include <llvm/Support/Host.h>
24
25#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
26#include <UCD/precompiled_properties.h>
27#endif
28#include <re/re_cc.h>
29#include <re/re_nullable.h>
30#include <re/re_simplifier.h>
31#include <re/re_alt.h>
32#include <re/parsefailure.h>
33#include <re/re_parser.h>
34#include <re/re_compiler.h>
35#include <utf8_encoder.h>
36#include <cc/cc_compiler.h>
37#include <pablo/pablo_compiler.h>
38#include <pablo/optimizers/pablo_simplifier.hpp>
39#include <pablo/optimizers/codemotionpass.h>
40#include <pablo/passes/flattenassociativedfg.h>
41#include <pablo/passes/factorizedfg.h>
42#ifdef ENABLE_MULTIPLEXING
43#include <pablo/optimizers/pablo_automultiplexing.hpp>
44#include <pablo/optimizers/pablo_bddminimization.h>
45#include <pablo/optimizers/distributivepass.h>
46#endif
47#include <pablo/function.h>
48#include <pablo/analysis/pabloverifier.hpp>
49#include <re/printer_re.h>
50#include <pablo/printer_pablos.h>
51
52#include "do_grep.h"
53
54using namespace pablo;
55
56static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
57                                              "These options control printing of intermediate regular expression structures.");
58static cl::opt<bool> PrintAllREs("print-REs", cl::init(false), cl::desc("print regular expression passes"), cl::cat(cRegexOutputOptions));
59static cl::opt<bool> PrintParsedREs("print-parsed-REs", cl::init(false), cl::desc("print out parsed regular expressions"), cl::cat(cRegexOutputOptions));
60static cl::opt<bool> PrintStrippedREs("print-stripped-REs", cl::init(false), cl::desc("print out REs with nullable prefixes/suffixes removed"), cl::cat(cRegexOutputOptions));
61static cl::opt<bool> PrintNamedREs("print-named-REs", cl::init(false), cl::desc("print out named REs"), cl::cat(cRegexOutputOptions));
62static cl::opt<bool> PrintUTF8REs("print-utf8-REs", cl::init(false), cl::desc("print out UTF-8 REs"), cl::cat(cRegexOutputOptions));
63static cl::opt<bool> PrintSimplifiedREs("print-simplified-REs", cl::init(false), cl::desc("print out final simplified REs"), cl::cat(cRegexOutputOptions));
64static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options",
65                                            "These options control printing of intermediate Pablo code.");
66
67static cl::opt<bool> PrintOptimizedREcode("print-pablo", cl::init(false), cl::desc("print final optimized Pablo code"), cl::cat(dPabloDumpOptions));
68static cl::opt<bool> PrintCompiledCCcode("print-CC-pablo", cl::init(false), cl::desc("print Pablo output from character class compiler"), cl::cat(dPabloDumpOptions));
69static cl::opt<bool> PrintCompiledREcode("print-RE-pablo", cl::init(false), cl::desc("print Pablo output from the regular expression compiler"), cl::cat(dPabloDumpOptions));
70
71static cl::OptionCategory cPabloOptimizationsOptions("Pablo Optimizations", "These options control Pablo optimization passes.");
72
73static cl::opt<bool> DisablePabloCSE("disable-CSE", cl::init(false),
74                                     cl::desc("Disable Pablo common subexpression elimination/dead code elimination"),
75                                     cl::cat(cPabloOptimizationsOptions));
76static cl::opt<bool> PabloSinkingPass("sinking", cl::init(false),
77                                      cl::desc("Moves all instructions into the innermost legal If-scope so that they are only executed when needed."),
78                                      cl::cat(cPabloOptimizationsOptions));
79
80#ifdef ENABLE_MULTIPLEXING
81static cl::opt<bool> EnableMultiplexing("multiplexing", cl::init(false),
82                                        cl::desc("combine Advances whose inputs are mutual exclusive into the fewest number of advances possible (expensive)."),
83                                        cl::cat(cPabloOptimizationsOptions));
84
85static cl::opt<unsigned> MultiplexingSetLimit("multiplexing-set-limit", cl::init(std::numeric_limits<unsigned>::max()),
86                                        cl::desc("maximum size of any candidate multiplexing set."),
87                                        cl::cat(cPabloOptimizationsOptions));
88static cl::opt<unsigned> MultiplexingSelectionLimit("multiplexing-selection-limit", cl::init(100),
89                                        cl::desc("maximum number of selections from any partial candidate multiplexing set."),
90                                        cl::cat(cPabloOptimizationsOptions));
91static cl::opt<unsigned> MultiplexingWindowSize("multiplexing-window-size", cl::init(1),
92                                        cl::desc("maximum depth difference for computing mutual exclusion of Advance nodes."),
93                                        cl::cat(cPabloOptimizationsOptions));
94
95static cl::opt<bool> EnableLowering("lowering", cl::init(false),
96                                         cl::desc("coalesce associative functions prior to optimization passes."),
97                                         cl::cat(cPabloOptimizationsOptions));
98static cl::opt<bool> EnableDistribution("dist", cl::init(false),
99                                         cl::desc("apply distribution law optimization."),
100                                         cl::cat(cPabloOptimizationsOptions));
101#endif
102
103static cl::opt<bool> DisableAVX2("disable-AVX2", cl::init(false), cl::desc("disable AVX2 instruction set."), cl::cat(cPabloOptimizationsOptions));
104
105re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
106    if (PrintAllREs || PrintParsedREs) {
107        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
108    }
109
110    //Optimization passes to simplify the AST.
111    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
112    if (PrintAllREs || PrintStrippedREs) {
113        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
114    }
115    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
116    if (PrintAllREs || PrintStrippedREs) {
117        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
118    }
119
120    re_ast = re::RE_Simplifier::simplify(re_ast);
121    if (PrintAllREs || PrintSimplifiedREs) {
122        //Print to the terminal the AST that was generated by the simplifier.
123        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
124    }
125    return re_ast;
126}
127   
128PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
129    PabloFunction * function = PabloFunction::Create("process_block", 8, 2);
130    cc::CC_Compiler cc_compiler(*function, encoding);
131    re::RE_Compiler re_compiler(*function, cc_compiler);
132    re_compiler.initializeRequiredStreams();
133    re_compiler.compileUnicodeNames(re_ast);
134    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
135
136    if (PrintCompiledREcode) {
137        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
138        llvm::raw_os_ostream cerr(std::cerr);
139        cerr << "Initial Pablo AST:\n";
140        PabloPrinter::print(*function, cerr);
141    }
142    #ifndef NDEBUG
143    PabloVerifier::verify(*function, "creation");
144    #endif
145    return function;
146}
147
148void pablo_function_passes(PabloFunction * function) {
149    // Scan through the pablo code and perform DCE and CSE
150    if (!DisablePabloCSE) {
151        Simplifier::optimize(*function);
152    }
153#ifdef ENABLE_MULTIPLEXING
154    if (EnableLowering || EnableDistribution || EnableMultiplexing) {
155        FlattenAssociativeDFG::transform(*function);
156    }
157#endif
158    if (PabloSinkingPass) {
159        CodeMotionPass::optimize(*function);
160    }
161#ifdef ENABLE_MULTIPLEXING   
162    if (EnableDistribution) {
163        DistributivePass::optimize(*function);
164    }
165    if (EnableMultiplexing) {
166        MultiplexingPass::optimize(*function, MultiplexingSetLimit, MultiplexingSelectionLimit, MultiplexingWindowSize);
167    }
168    if (EnableLowering || EnableDistribution || EnableMultiplexing) {
169        FactorizeDFG::transform(*function);
170    }
171#endif
172    if (PrintOptimizedREcode) {
173        PabloVerifier::verify(*function, "post-optimization");
174        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
175        llvm::raw_os_ostream cerr(std::cerr);
176        cerr << "Final Pablo AST:\n";
177        PabloPrinter::print(*function, cerr);
178    }
179}
180
181// Dynamic AVX2 confirmation
182#if (BLOCK_SIZE == 256)
183#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
184#include "ispc.cpp"
185#endif
186
187
188ExecutionEngine * JIT_to_ExecutionEngine (llvm::Function * f) {
189
190    InitializeNativeTarget();
191    InitializeNativeTargetAsmPrinter();
192    InitializeNativeTargetAsmParser();
193
194    std::string errMessage;
195    EngineBuilder builder(std::move(std::unique_ptr<Module>(f->getParent())));
196    builder.setErrorStr(&errMessage);
197    builder.setMCPU(sys::getHostCPUName());
198    builder.setOptLevel(CodeGenOpt::Level::None);
199
200#if (BLOCK_SIZE == 256)
201    if (!DisableAVX2 && (strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
202            std::vector<std::string> attrs;
203            attrs.push_back("avx2");
204            builder.setMAttrs(attrs);
205    //std::cerr << "+avx2 set" << std::endl;
206    }
207#endif
208    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
209    ExecutionEngine * engine = builder.create();
210    if (engine == nullptr) {
211        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
212    }
213    //engine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
214    // engine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
215
216    return engine;
217}
218
219
220extern "C" {
221  void wrapped_print_register(char * regName, BitBlock bit_block) {
222      print_register<BitBlock>(regName, bit_block);
223  }
224}
225
226void icgrep_Linking(Module * m, ExecutionEngine * e) {
227    Module::FunctionListType & fns = m->getFunctionList();
228    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
229        std::string fnName = it->getName().str();
230        if (fnName == "process_block") continue;
231        if (fnName == "process_block_initialize_carries") continue;
232        if (fnName == "wrapped_print_register") {
233            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
234        }
235#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
236        else {
237            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
238            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
239        }
240#endif
241    }
242}
243
Note: See TracBrowser for help on using the repository browser.