blob: 3bbd1a13da029c2e7b6752ed248797c53114865a [file] [log] [blame]
Justin Holewinski21fdcb02013-03-30 14:29:25 +00001//===- NVVMReflect.cpp - NVVM Emulate conditional compilation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass replaces occurences of __nvvm_reflect("string") with an
11// integer based on -nvvm-reflect-list string=<int> option given to this pass.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/StringMap.h"
16#include "llvm/Pass.h"
17#include "llvm/IR/Function.h"
18#include "llvm/IR/Module.h"
19#include "llvm/IR/Type.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_os_ostream.h"
26#include "llvm/Transforms/Scalar.h"
27#include <map>
28#include <sstream>
29#include <string>
30#include <vector>
31
32#define NVVM_REFLECT_FUNCTION "__nvvm_reflect"
33
34using namespace llvm;
35
36namespace llvm { void initializeNVVMReflectPass(PassRegistry &); }
37
38namespace {
39class LLVM_LIBRARY_VISIBILITY NVVMReflect : public ModulePass {
40private:
41 //std::map<std::string, int> VarMap;
42 StringMap<int> VarMap;
43 typedef std::map<std::string, int>::iterator VarMapIter;
44 Function *reflectFunction;
45
46public:
47 static char ID;
48 NVVMReflect() : ModulePass(ID) {
49 VarMap.clear();
50 reflectFunction = 0;
51 }
52
53 void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); }
54 virtual bool runOnModule(Module &);
55
56 void setVarMap();
57};
58}
59
60static cl::opt<bool>
61NVVMReflectEnabled("nvvm-reflect-enable", cl::init(true),
62 cl::desc("NVVM reflection, enabled by default"));
63
64char NVVMReflect::ID = 0;
65INITIALIZE_PASS(NVVMReflect, "nvvm-reflect",
66 "Replace occurences of __nvvm_reflect() calls with 0/1", false,
67 false)
68
69static cl::list<std::string>
70ReflectList("nvvm-reflect-list", cl::value_desc("name=0/1"),
71 cl::desc("A list of string=num assignments, where num=0 or 1"),
72 cl::ValueRequired);
73
74/// This function does the same operation as perl's split.
75/// For example, calling this with ("a=1,b=2,c=0", ",") will
76/// return ["a=1", "b=2", "c=0"] in the return std::vector.
77static std::vector<std::string>
78Tokenize(const std::string &str, const std::string &delim) {
79 std::vector<std::string> tokens;
80
81 size_t p0 = 0, p1 = std::string::npos;
82 while (p0 != std::string::npos) {
83 p1 = str.find_first_of(delim, p0);
84 if (p1 != p0) {
85 std::string token = str.substr(p0, p1 - p0);
86 tokens.push_back(token);
87 }
88 p0 = str.find_first_not_of(delim, p1);
89 }
90
91 return tokens;
92}
93
94/// The command line can look as follows :
95/// -R a=1,b=2 -R c=3,d=0 -R e=2
96/// The strings "a=1,b=2", "c=3,d=0", "e=2" are available in the
97/// ReflectList vector. First, each of ReflectList[i] is 'split'
98/// using "," as the delimiter. Then each of this part is split
99/// using "=" as the delimiter.
100void NVVMReflect::setVarMap() {
101 for (unsigned i = 0, e = ReflectList.size(); i != e; ++i) {
102 // DEBUG(dbgs() << "Option : " << ReflectList[i] << std::endl);
103 std::vector<std::string> nameValList = Tokenize(ReflectList[i], ",");
104 for (unsigned j = 0, ej = nameValList.size(); j != ej; ++j) {
105 std::vector<std::string> nameValPair = Tokenize(nameValList[j], "=");
106 assert(nameValPair.size() == 2 && "name=val expected");
107 std::stringstream valstream(nameValPair[1]);
108 int val;
109 valstream >> val;
110 assert((!(valstream.fail())) && "integer value expected");
111 VarMap[nameValPair[0]] = val;
112 }
113 }
114}
115
116bool NVVMReflect::runOnModule(Module &M) {
117 if (!NVVMReflectEnabled)
118 return false;
119
120 setVarMap();
121
122 reflectFunction = M.getFunction(NVVM_REFLECT_FUNCTION);
123
124 // If reflect function is not used, then there will be
125 // no entry in the module.
126 if (reflectFunction == 0) {
127 return false;
128 }
129
130 // Validate _reflect function
131 assert(reflectFunction->isDeclaration() &&
132 "_reflect function should not have a body");
133 assert(reflectFunction->getReturnType()->isIntegerTy() &&
134 "_reflect's return type should be integer");
135
136 std::vector<Instruction *> toRemove;
137
138 // Go through the uses of reflectFunction in this Function.
139 // Each of them should a CallInst with a ConstantArray argument.
140 // First validate that. If the c-string corresponding to the
141 // ConstantArray can be found successfully, see if it can be
142 // found in VarMap. If so, replace the uses of CallInst with the
143 // value found in VarMap. If not, replace the use with value 0.
144 for (Value::use_iterator iter = reflectFunction->use_begin(),
145 iterEnd = reflectFunction->use_end();
146 iter != iterEnd; ++iter) {
147 assert(isa<CallInst>(*iter) && "Only a call instruction can use _reflect");
148 CallInst *reflect = cast<CallInst>(*iter);
149
150 assert((reflect->getNumOperands() == 2) &&
151 "Only one operand expect for _reflect function");
152 // In cuda, we will have an extra constant-to-generic conversion of
153 // the string.
154 const Value *conv = reflect->getArgOperand(0);
155 assert(isa<CallInst>(conv) && "Expected a const-to-gen conversion");
156 const CallInst *convcall = cast<CallInst>(conv);
157 const Value *str = convcall->getArgOperand(0);
158 assert(isa<ConstantExpr>(str) &&
159 "Format of _reflect function not recognized");
160 const ConstantExpr *gep = cast<ConstantExpr>(str);
161
162 const Value *sym = gep->getOperand(0);
163 assert(isa<Constant>(sym) && "Format of _reflect function not recognized");
164
165 const Constant *symstr = cast<Constant>(sym);
166
167 assert(isa<ConstantDataSequential>(symstr->getOperand(0)) &&
168 "Format of _reflect function not recognized");
169
170 assert(cast<ConstantDataSequential>(symstr->getOperand(0))->isCString() &&
171 "Format of _reflect function not recognized");
172
173 std::string reflectArg =
174 cast<ConstantDataSequential>(symstr->getOperand(0))->getAsString();
175
176 reflectArg = reflectArg.substr(0, reflectArg.size() - 1);
177 // DEBUG(dbgs() << "Arg of _reflect : " << reflectArg << std::endl);
178
179 int reflectVal = 0; // The default value is 0
180 if (VarMap.find(reflectArg) != VarMap.end()) {
181 reflectVal = VarMap[reflectArg];
182 }
183 reflect->replaceAllUsesWith(
184 ConstantInt::get(reflect->getType(), reflectVal));
185 toRemove.push_back(reflect);
186 }
187 if (toRemove.size() == 0)
188 return false;
189
190 for (unsigned i = 0, e = toRemove.size(); i != e; ++i)
191 toRemove[i]->eraseFromParent();
192 return true;
193}