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

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

Symbol table work and untested kernel instatiate method for multiple input streams

File size: 9.5 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#include <sstream>
11
12#include <llvm/IR/Function.h>
13#include <llvm/IR/Module.h>
14#include <llvm/ExecutionEngine/ExecutionEngine.h>
15#include <llvm/ExecutionEngine/MCJIT.h>
16#include <llvm/IRReader/IRReader.h>
17#include <llvm/Support/CommandLine.h>
18#include <llvm/CodeGen/CommandFlags.h>
19#include <llvm/Support/SourceMgr.h>
20#include <llvm/Support/TargetSelect.h>
21#include <llvm/Support/Host.h>
22#include <llvm/Support/raw_ostream.h>
23
24// Dynamic processor detection
25#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
26#include <util/ispc.cpp>
27
28#include <re/re_cc.h>
29#include <object_cache.h>
30
31static cl::OptionCategory bGrepOutputOptions("Output Options",
32                                      "These options control the output.");
33
34static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
35static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
36static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
37
38static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
39static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
40
41static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
42static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
43
44static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
45static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
46static cl::opt<std::string> IROutputFilename("dump-generated-IR-output", cl::init(""), cl::desc("output IR filename"), cl::cat(eIRDumpOptions));
47
48
49static cl::OptionCategory cMachineCodeOptimization("Machine Code Optimizations", "These options control back-end compilier optimization levels.");
50
51
52static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O1')"),
53                              cl::cat(cMachineCodeOptimization), cl::Prefix, cl::ZeroOrMore, cl::init('1'));
54
55
56static cl::OptionCategory cObjectCache("Object Caching", "These options control back-end object caching behaviours.");
57
58static cl::opt<bool> EnableObjectCache("enable-object-cache", cl::init(false), cl::desc("Enable object caching"), cl::cat(cObjectCache));
59
60static cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::init(""), cl::desc("Path to the object cache diretory"), cl::cat(cObjectCache));
61
62
63
64ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
65
66    InitializeNativeTarget();
67    InitializeNativeTargetAsmPrinter();
68    InitializeNativeTargetAsmParser();
69
70    PassRegistry * Registry = PassRegistry::getPassRegistry();
71    initializeCore(*Registry);
72    initializeCodeGen(*Registry);
73    initializeLowerIntrinsicsPass(*Registry);
74
75    std::string errMessage;
76    EngineBuilder builder(std::move(std::unique_ptr<Module>(m)));
77    builder.setErrorStr(&errMessage);
78    builder.setMCPU(sys::getHostCPUName());
79    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
80    switch (OptLevel) {
81        case '0': optLevel = CodeGenOpt::None; break;
82        case '1': optLevel = CodeGenOpt::Less; break;
83        case '2': optLevel = CodeGenOpt::Default; break;
84        case '3': optLevel = CodeGenOpt::Aggressive; break;
85        default: errs() << OptLevel << " is an invalid optimization level.\n";
86    }
87    builder.setOptLevel(optLevel);
88
89    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
90        std::vector<std::string> attrs;
91        attrs.push_back("avx2");
92        builder.setMAttrs(attrs);
93    }
94    // builder.selectTarget();
95
96    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
97        if (IROutputFilename.empty()) {
98            m->dump();
99        } else {
100            std::error_code error;
101            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
102            m->print(out, nullptr);
103        }
104    }
105
106    ExecutionEngine * engine = builder.create();
107    ICGrepObjectCache * cache = nullptr;
108    if (engine == nullptr) {
109        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
110    }
111    if (EnableObjectCache) {
112        if (ObjectCacheDir.empty())
113            // Default is $HOME/.cache/icgrep
114            cache = new ICGrepObjectCache();
115        else
116            cache = new ICGrepObjectCache(ObjectCacheDir);
117        engine->setObjectCache(cache);
118    }
119    return engine;
120}
121
122
123
124static int * total_count;
125static std::stringstream * resultStrs = nullptr;
126static std::vector<std::string> inputFiles;
127
128void initResult(std::vector<std::string> filenames, const int firstName, const int n){
129    if (n - firstName > 1) {
130        ShowFileNames = true;
131    }
132    inputFiles = filenames;
133    resultStrs = new std::stringstream[n];
134    total_count = new int[n];
135    for (int i=1; i<inputFiles.size(); i++){
136        total_count[i-1] = 0;
137    }
138
139}
140
141extern "C" {
142    void wrapped_report_match(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer, uint64_t filesize, char * filename) {
143
144        int idx = 0;
145        for (int i=1; i<inputFiles.size(); i++){
146            if (inputFiles[i] == filename){
147                idx = i-1;
148                break;
149            }
150        }
151
152        if(CountOnly){
153            total_count[idx]++;
154            return;
155        }
156
157        if (ShowFileNames) {
158            resultStrs[idx] << filename << ':';
159        }
160        if (ShowLineNumbers) {
161            resultStrs[idx] << lineNum << ":";
162        }
163
164        if ((buffer[line_start] == 0xA) && (line_start != line_end)) {
165            // The line "starts" on the LF of a CRLF.  Really the end of the last line.
166            line_start++;
167        }
168        if (line_end == filesize) {
169            // The match position is at end-of-file.   We have a final unterminated line.
170            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
171            if (NormalizeLineBreaks) {
172                resultStrs[idx] << '\n';  // terminate it
173            }
174            return;
175        }
176        unsigned char end_byte = (unsigned char)buffer[line_end]; 
177        if (NormalizeLineBreaks) {
178            if (end_byte == 0x85) {
179                // Line terminated with NEL, on the second byte.  Back up 1.
180                line_end--;
181            } else if (end_byte > 0xD) {
182                // Line terminated with PS or LS, on the third byte.  Back up 2.
183                line_end -= 2;
184            }
185            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
186            resultStrs[idx] << '\n';
187        }
188        else{   
189            if (end_byte == 0x0D) {
190                // Check for line_end on first byte of CRLF;  note that we don't
191                // want to access past the end of buffer.
192                if ((line_end + 1 < filesize) && (buffer[line_end + 1] == 0x0A)) {
193                    // Found CRLF; preserve both bytes.
194                    line_end++;
195                }
196            }
197            resultStrs[idx].write(&buffer[line_start], line_end - line_start + 1);
198        }
199    }
200}
201
202void PrintResult(){
203    if(CountOnly){
204        for (int i=1; i<inputFiles.size(); i++){
205            std::cout << total_count[i-1] << std::endl;
206        }
207        return;
208    }
209
210    std::string out;
211    for (int i=1; i<inputFiles.size(); i++){
212        std::cout << resultStrs[i-1].str();
213    }
214}
215
216re::CC * parsedCodePointSet;
217
218extern "C" {
219    void insert_codepoints(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer) {
220       re::codepoint_t c = 0;
221        ssize_t line_pos = line_start;
222        while (isxdigit(buffer[line_pos])) {
223            if (isdigit(buffer[line_pos])) {
224                c = (c << 4) | (buffer[line_pos] - '0');
225            }
226            else {
227                c = (c << 4) | (tolower(buffer[line_pos]) - 'a' + 10);
228            }
229            line_pos++;
230        }
231        assert(((line_pos - line_start) >= 4) && ((line_pos - line_start) <= 6)); // UCD format 4 to 6 hex digits.       
232        parsedCodePointSet->insert(c);
233    }
234}
235
236void setParsedCodePointSet(){
237    parsedCodePointSet = re::makeCC();
238}
239
240re::CC * getParsedCodePointSet(){
241    return parsedCodePointSet;
242}
243
244void icgrep_Linking(Module * m, ExecutionEngine * e) {
245    Module::FunctionListType & fns = m->getFunctionList();
246    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
247        std::string fnName = it->getName().str();
248        if (fnName == "s2p_block") continue;
249        if (fnName == "process_block") continue;
250        if (fnName == "process_block_initialize_carries") continue;
251       
252        if (fnName == "wrapped_report_match") {
253            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_report_match);
254        }
255        if (fnName == "insert_codepoints") {
256            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&insert_codepoints);
257        }
258#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
259        else {
260            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
261            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
262        }
263#endif
264    }
265}
Note: See TracBrowser for help on using the repository browser.