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

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

Work on coalescing algorithm + minor changes.

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