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

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

Code clean-up. Removed Pablo Call, SetIthBit? and Prototype.

File size: 7.9 KB
Line 
1/*
2 *  Copyright (c) 2016 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 "toolchain.h"
8#include <llvm/CodeGen/CommandFlags.h>             // for InitTargetOptionsF...
9#include <llvm/ExecutionEngine/ExecutionEngine.h>  // for EngineBuilder
10#include <llvm/Support/CommandLine.h>              // for OptionCategory
11#include <llvm/Support/TargetSelect.h>             // for InitializeNativeTa...
12#include <llvm/Support/raw_ostream.h>              // for errs, raw_ostream
13#include <llvm/ADT/SmallString.h>                  // for SmallString
14#include <llvm/IR/LegacyPassManager.h>             // for PassManager
15#include <llvm/InitializePasses.h>                 // for initializeCodeGen
16#include <llvm/PassRegistry.h>                     // for PassRegistry
17#include <llvm/Support/CodeGen.h>                  // for Level, Level::None
18#include <llvm/Support/Compiler.h>                 // for LLVM_UNLIKELY
19#include <llvm/Target/TargetMachine.h>             // for TargetMachine, Tar...
20#include <llvm/Target/TargetOptions.h>             // for TargetOptions
21#include <object_cache.h>
22namespace llvm { class Module; }
23#ifdef CUDA_ENABLED
24#include <IR_Gen/llvm2ptx.h>
25#endif
26 
27using namespace llvm;
28
29namespace codegen {
30
31static cl::OptionCategory CodeGenOptions("Code Generation Options", "These options control code generation.");
32
33
34static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(CodeGenOptions));
35static cl::opt<std::string> IROutputFilename("dump-generated-IR-output", cl::init(""), cl::desc("output IR filename"), cl::cat(CodeGenOptions));
36#if LLVM_VERSION_MINOR > 6
37static cl::opt<bool> DumpASM("DumpASM", cl::init(false), cl::desc("Print Assembly Code."), cl::cat(CodeGenOptions));
38#endif
39static cl::opt<std::string> ASMOutputFilename("asm-output", cl::init(""), cl::desc("output ASM filename"), cl::cat(CodeGenOptions));
40static cl::opt<bool> AsmVerbose("asm-verbose",
41                                cl::desc("Add comments to directives."),
42                                cl::init(true), cl::cat(CodeGenOptions));
43
44char OptLevel;
45static cl::opt<char, true> OptLevelOption("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O1')"), cl::location(OptLevel),
46                              cl::cat(CodeGenOptions), cl::Prefix, cl::ZeroOrMore, cl::init('1'));
47
48
49static cl::opt<bool> EnableObjectCache("enable-object-cache", cl::init(false), cl::desc("Enable object caching"), cl::cat(CodeGenOptions));
50
51static cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::init(""), cl::desc("Path to the object cache diretory"), cl::cat(CodeGenOptions));
52
53
54int BlockSize;
55int SegmentSize;
56int BufferSegments;
57int ThreadNum;
58
59static cl::opt<int, true> BlockSizeOption("BlockSize", cl::location(BlockSize), cl::init(0), cl::desc("specify a block size (defaults to widest SIMD register width in bits)."), cl::cat(CodeGenOptions));
60static cl::opt<int, true> SegmentSizeOption("segment-size", cl::location(SegmentSize), cl::desc("Segment Size"), cl::value_desc("positive integer"), cl::init(1));
61static cl::opt<int, true> BufferSegmentsOption("buffer-segments", cl::location(BufferSegments), cl::desc("Buffer Segments"), cl::value_desc("positive integer"), cl::init(1));
62static cl::opt<int, true> ThreadNumOption("thread-num", cl::location(ThreadNum), cl::desc("Number of threads used for segment pipeline parallel"), cl::value_desc("positive integer"), cl::init(2));
63
64const cl::OptionCategory * codegen_flags() {return &CodeGenOptions;}
65
66#ifdef CUDA_ENABLED
67bool NVPTX;
68static cl::opt<bool> USENVPTX("NVPTX", cl::desc("Run on GPU only."), cl::init(false));
69#endif
70
71}
72
73
74#ifdef CUDA_ENABLED
75void setNVPTXOption(){
76    codegen::NVPTX = codegen::USENVPTX;
77}
78
79void Compile2PTX (Module * m, std::string IRFilename, std::string PTXFilename) {
80    InitializeAllTargets();
81    InitializeAllTargetMCs();
82    InitializeAllAsmPrinters();
83    InitializeAllAsmParsers();
84
85    PassRegistry *Registry = PassRegistry::getPassRegistry();
86    initializeCore(*Registry);
87    initializeCodeGen(*Registry);
88    initializeLoopStrengthReducePass(*Registry);
89    initializeLowerIntrinsicsPass(*Registry);
90    initializeUnreachableBlockElimPass(*Registry);
91
92    std::error_code error;
93    llvm::raw_fd_ostream out(IRFilename, error, sys::fs::OpenFlags::F_None);
94    m->print(out, nullptr);
95
96    if (LLVM_UNLIKELY(codegen::DumpGeneratedIR))
97            m->dump();
98
99    llvm2ptx(IRFilename, PTXFilename);
100}
101#endif
102
103
104void setAllFeatures(EngineBuilder &builder) {
105    llvm::StringMap<bool> HostCPUFeatures;
106    if (llvm::sys::getHostCPUFeatures(HostCPUFeatures)) {
107        std::vector<std::string> attrs;
108        for (auto &flag : HostCPUFeatures) {
109            auto enabled = flag.second ? "+" : "-";
110            attrs.push_back(enabled + flag.first().str());
111        }
112        builder.setMAttrs(attrs);
113    }
114}
115
116bool AVX2_available() {
117    llvm::StringMap<bool> HostCPUFeatures;
118    if (llvm::sys::getHostCPUFeatures(HostCPUFeatures)) {
119        auto f = HostCPUFeatures.find("avx2");
120        return ((f != HostCPUFeatures.end()) && f->second);
121    }
122    return false;
123}
124
125#ifndef USE_LLVM_3_6
126void WriteAssembly (llvm::TargetMachine *TM, Module * m) {
127    llvm::legacy::PassManager PM;
128
129    llvm::SmallString<128> Str;
130    llvm::raw_svector_ostream dest(Str);
131
132    if (TM->addPassesToEmitFile(PM, dest, llvm::TargetMachine::CGFT_AssemblyFile ) ) {
133        throw std::runtime_error("LLVM error: addPassesToEmitFile failed.");
134    }
135    PM.run(*m);
136
137    if (codegen::ASMOutputFilename.empty()) {
138        errs() << Str;
139    } else {
140        std::error_code error;
141        llvm::raw_fd_ostream out(codegen::ASMOutputFilename, error, sys::fs::OpenFlags::F_None);
142        out << Str;
143    }
144}
145#endif
146
147ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
148
149    InitializeNativeTarget();
150    InitializeNativeTargetAsmPrinter();
151    InitializeNativeTargetAsmParser();
152
153    PassRegistry * Registry = PassRegistry::getPassRegistry();
154    initializeCore(*Registry);
155    initializeCodeGen(*Registry);
156    initializeLowerIntrinsicsPass(*Registry);
157
158    std::string errMessage;
159    EngineBuilder builder{std::unique_ptr<Module>(m)};
160    builder.setErrorStr(&errMessage);
161    TargetOptions opts = InitTargetOptionsFromCodeGenFlags();
162    opts.MCOptions.AsmVerbose = codegen::AsmVerbose;
163
164    builder.setTargetOptions(opts);
165    builder.setVerifyModules(true);
166    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
167    switch (codegen::OptLevel) {
168        case '0': optLevel = CodeGenOpt::None; break;
169        case '1': optLevel = CodeGenOpt::Less; break;
170        case '2': optLevel = CodeGenOpt::Default; break;
171        case '3': optLevel = CodeGenOpt::Aggressive; break;
172        default: errs() << codegen::OptLevel << " is an invalid optimization level.\n";
173    }
174    builder.setOptLevel(optLevel);
175
176    setAllFeatures(builder);
177
178    if (LLVM_UNLIKELY(codegen::DumpGeneratedIR)) {
179        if (codegen::IROutputFilename.empty()) {
180            m->dump();
181        } else {
182            std::error_code error;
183            llvm::raw_fd_ostream out(codegen::IROutputFilename, error, sys::fs::OpenFlags::F_None);
184            m->print(out, nullptr);
185        }
186    }
187#if LLVM_VERSION_MINOR > 6
188    if (codegen::DumpASM) {
189      WriteAssembly(builder.selectTarget(), m);
190    }
191#endif
192    ExecutionEngine * engine = builder.create();
193    if (engine == nullptr) {
194        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
195    }   
196    return engine;
197}
198
199void ApplyObjectCache(ExecutionEngine * e) {
200    ICGrepObjectCache * cache = nullptr;
201    if (codegen::EnableObjectCache) {
202        if (codegen::ObjectCacheDir.empty())
203            // Default is $HOME/.cache/icgrep
204            cache = new ICGrepObjectCache();
205        else
206            cache = new ICGrepObjectCache(codegen::ObjectCacheDir);
207        e->setObjectCache(cache);
208    }   
209}
210
211
Note: See TracBrowser for help on using the repository browser.