1 //===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
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 // Convert generic global variables into either .global or .const access based
11 // on the variable's "constant" qualifier.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "NVPTX.h"
16 #include "MCTargetDesc/NVPTXBaseInfo.h"
17 #include "NVPTXUtilities.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/ValueMap.h"
29 #include "llvm/Transforms/Utils/ValueMapper.h"
30
31 using namespace llvm;
32
33 namespace llvm {
34 void initializeGenericToNVVMPass(PassRegistry &);
35 }
36
37 namespace {
38 class GenericToNVVM : public ModulePass {
39 public:
40 static char ID;
41
GenericToNVVM()42 GenericToNVVM() : ModulePass(ID) {}
43
44 bool runOnModule(Module &M) override;
45
getAnalysisUsage(AnalysisUsage & AU) const46 void getAnalysisUsage(AnalysisUsage &AU) const override {}
47
48 private:
49 Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
50 IRBuilder<> &Builder);
51 Value *remapConstant(Module *M, Function *F, Constant *C,
52 IRBuilder<> &Builder);
53 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
54 Constant *C,
55 IRBuilder<> &Builder);
56 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
57 IRBuilder<> &Builder);
58 void remapNamedMDNode(ValueToValueMapTy &VM, NamedMDNode *N);
59
60 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
61 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
62 GVMapTy GVMap;
63 ConstantToValueMapTy ConstantToValueMap;
64 };
65 } // end namespace
66
67 char GenericToNVVM::ID = 0;
68
createGenericToNVVMPass()69 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
70
71 INITIALIZE_PASS(
72 GenericToNVVM, "generic-to-nvvm",
73 "Ensure that the global variables are in the global address space", false,
74 false)
75
runOnModule(Module & M)76 bool GenericToNVVM::runOnModule(Module &M) {
77 // Create a clone of each global variable that has the default address space.
78 // The clone is created with the global address space specifier, and the pair
79 // of original global variable and its clone is placed in the GVMap for later
80 // use.
81
82 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
83 I != E;) {
84 GlobalVariable *GV = &*I++;
85 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
86 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
87 !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
88 GlobalVariable *NewGV = new GlobalVariable(
89 M, GV->getValueType(), GV->isConstant(),
90 GV->getLinkage(),
91 GV->hasInitializer() ? GV->getInitializer() : nullptr,
92 "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
93 NewGV->copyAttributesFrom(GV);
94 GVMap[GV] = NewGV;
95 }
96 }
97
98 // Return immediately, if every global variable has a specific address space
99 // specifier.
100 if (GVMap.empty()) {
101 return false;
102 }
103
104 // Walk through the instructions in function defitinions, and replace any use
105 // of original global variables in GVMap with a use of the corresponding
106 // copies in GVMap. If necessary, promote constants to instructions.
107 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
108 if (I->isDeclaration()) {
109 continue;
110 }
111 IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
112 for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
113 ++BBI) {
114 for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
115 ++II) {
116 for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
117 Value *Operand = II->getOperand(i);
118 if (isa<Constant>(Operand)) {
119 II->setOperand(
120 i, remapConstant(&M, &*I, cast<Constant>(Operand), Builder));
121 }
122 }
123 }
124 }
125 ConstantToValueMap.clear();
126 }
127
128 // Copy GVMap over to a standard value map.
129 ValueToValueMapTy VM;
130 for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
131 VM[I->first] = I->second;
132
133 // Walk through the metadata section and update the debug information
134 // associated with the global variables in the default address space.
135 for (NamedMDNode &I : M.named_metadata()) {
136 remapNamedMDNode(VM, &I);
137 }
138
139 // Walk through the global variable initializers, and replace any use of
140 // original global variables in GVMap with a use of the corresponding copies
141 // in GVMap. The copies need to be bitcast to the original global variable
142 // types, as we cannot use cvta in global variable initializers.
143 for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
144 GlobalVariable *GV = I->first;
145 GlobalVariable *NewGV = I->second;
146
147 // Remove GV from the map so that it can be RAUWed. Note that
148 // DenseMap::erase() won't invalidate any iterators but this one.
149 auto Next = std::next(I);
150 GVMap.erase(I);
151 I = Next;
152
153 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
154 // At this point, the remaining uses of GV should be found only in global
155 // variable initializers, as other uses have been already been removed
156 // while walking through the instructions in function definitions.
157 GV->replaceAllUsesWith(BitCastNewGV);
158 std::string Name = GV->getName();
159 GV->eraseFromParent();
160 NewGV->setName(Name);
161 }
162 assert(GVMap.empty() && "Expected it to be empty by now");
163
164 return true;
165 }
166
getOrInsertCVTA(Module * M,Function * F,GlobalVariable * GV,IRBuilder<> & Builder)167 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
168 GlobalVariable *GV,
169 IRBuilder<> &Builder) {
170 PointerType *GVType = GV->getType();
171 Value *CVTA = nullptr;
172
173 // See if the address space conversion requires the operand to be bitcast
174 // to i8 addrspace(n)* first.
175 EVT ExtendedGVType = EVT::getEVT(GV->getValueType(), true);
176 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
177 // A bitcast to i8 addrspace(n)* on the operand is needed.
178 LLVMContext &Context = M->getContext();
179 unsigned int AddrSpace = GVType->getAddressSpace();
180 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
181 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
182 // Insert the address space conversion.
183 Type *ResultType =
184 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
185 Function *CVTAFunction = Intrinsic::getDeclaration(
186 M, Intrinsic::nvvm_ptr_global_to_gen, {ResultType, DestTy});
187 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
188 // Another bitcast from i8 * to <the element type of GVType> * is
189 // required.
190 DestTy =
191 PointerType::get(GV->getValueType(), llvm::ADDRESS_SPACE_GENERIC);
192 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
193 } else {
194 // A simple CVTA is enough.
195 SmallVector<Type *, 2> ParamTypes;
196 ParamTypes.push_back(PointerType::get(GV->getValueType(),
197 llvm::ADDRESS_SPACE_GENERIC));
198 ParamTypes.push_back(GVType);
199 Function *CVTAFunction = Intrinsic::getDeclaration(
200 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
201 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
202 }
203
204 return CVTA;
205 }
206
remapConstant(Module * M,Function * F,Constant * C,IRBuilder<> & Builder)207 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
208 IRBuilder<> &Builder) {
209 // If the constant C has been converted already in the given function F, just
210 // return the converted value.
211 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
212 if (CTII != ConstantToValueMap.end()) {
213 return CTII->second;
214 }
215
216 Value *NewValue = C;
217 if (isa<GlobalVariable>(C)) {
218 // If the constant C is a global variable and is found in GVMap, generate a
219 // set set of instructions that convert the clone of C with the global
220 // address space specifier to a generic pointer.
221 // The constant C cannot be used here, as it will be erased from the
222 // module eventually. And the clone of C with the global address space
223 // specifier cannot be used here either, as it will affect the types of
224 // other instructions in the function. Hence, this address space conversion
225 // is required.
226 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
227 if (I != GVMap.end()) {
228 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
229 }
230 } else if (isa<ConstantAggregate>(C)) {
231 // If any element in the constant vector or aggregate C is or uses a global
232 // variable in GVMap, the constant C needs to be reconstructed, using a set
233 // of instructions.
234 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
235 } else if (isa<ConstantExpr>(C)) {
236 // If any operand in the constant expression C is or uses a global variable
237 // in GVMap, the constant expression C needs to be reconstructed, using a
238 // set of instructions.
239 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
240 }
241
242 ConstantToValueMap[C] = NewValue;
243 return NewValue;
244 }
245
remapConstantVectorOrConstantAggregate(Module * M,Function * F,Constant * C,IRBuilder<> & Builder)246 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
247 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
248 bool OperandChanged = false;
249 SmallVector<Value *, 4> NewOperands;
250 unsigned NumOperands = C->getNumOperands();
251
252 // Check if any element is or uses a global variable in GVMap, and thus
253 // converted to another value.
254 for (unsigned i = 0; i < NumOperands; ++i) {
255 Value *Operand = C->getOperand(i);
256 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
257 OperandChanged |= Operand != NewOperand;
258 NewOperands.push_back(NewOperand);
259 }
260
261 // If none of the elements has been modified, return C as it is.
262 if (!OperandChanged) {
263 return C;
264 }
265
266 // If any of the elements has been modified, construct the equivalent
267 // vector or aggregate value with a set instructions and the converted
268 // elements.
269 Value *NewValue = UndefValue::get(C->getType());
270 if (isa<ConstantVector>(C)) {
271 for (unsigned i = 0; i < NumOperands; ++i) {
272 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
273 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
274 }
275 } else {
276 for (unsigned i = 0; i < NumOperands; ++i) {
277 NewValue =
278 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
279 }
280 }
281
282 return NewValue;
283 }
284
remapConstantExpr(Module * M,Function * F,ConstantExpr * C,IRBuilder<> & Builder)285 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
286 IRBuilder<> &Builder) {
287 bool OperandChanged = false;
288 SmallVector<Value *, 4> NewOperands;
289 unsigned NumOperands = C->getNumOperands();
290
291 // Check if any operand is or uses a global variable in GVMap, and thus
292 // converted to another value.
293 for (unsigned i = 0; i < NumOperands; ++i) {
294 Value *Operand = C->getOperand(i);
295 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
296 OperandChanged |= Operand != NewOperand;
297 NewOperands.push_back(NewOperand);
298 }
299
300 // If none of the operands has been modified, return C as it is.
301 if (!OperandChanged) {
302 return C;
303 }
304
305 // If any of the operands has been modified, construct the instruction with
306 // the converted operands.
307 unsigned Opcode = C->getOpcode();
308 switch (Opcode) {
309 case Instruction::ICmp:
310 // CompareConstantExpr (icmp)
311 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
312 NewOperands[0], NewOperands[1]);
313 case Instruction::FCmp:
314 // CompareConstantExpr (fcmp)
315 llvm_unreachable("Address space conversion should have no effect "
316 "on float point CompareConstantExpr (fcmp)!");
317 case Instruction::ExtractElement:
318 // ExtractElementConstantExpr
319 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
320 case Instruction::InsertElement:
321 // InsertElementConstantExpr
322 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
323 NewOperands[2]);
324 case Instruction::ShuffleVector:
325 // ShuffleVector
326 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
327 NewOperands[2]);
328 case Instruction::ExtractValue:
329 // ExtractValueConstantExpr
330 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
331 case Instruction::InsertValue:
332 // InsertValueConstantExpr
333 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
334 C->getIndices());
335 case Instruction::GetElementPtr:
336 // GetElementPtrConstantExpr
337 return cast<GEPOperator>(C)->isInBounds()
338 ? Builder.CreateGEP(
339 cast<GEPOperator>(C)->getSourceElementType(),
340 NewOperands[0],
341 makeArrayRef(&NewOperands[1], NumOperands - 1))
342 : Builder.CreateInBoundsGEP(
343 cast<GEPOperator>(C)->getSourceElementType(),
344 NewOperands[0],
345 makeArrayRef(&NewOperands[1], NumOperands - 1));
346 case Instruction::Select:
347 // SelectConstantExpr
348 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
349 default:
350 // BinaryConstantExpr
351 if (Instruction::isBinaryOp(Opcode)) {
352 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
353 NewOperands[0], NewOperands[1]);
354 }
355 // UnaryConstantExpr
356 if (Instruction::isCast(Opcode)) {
357 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
358 NewOperands[0], C->getType());
359 }
360 llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
361 }
362 }
363
remapNamedMDNode(ValueToValueMapTy & VM,NamedMDNode * N)364 void GenericToNVVM::remapNamedMDNode(ValueToValueMapTy &VM, NamedMDNode *N) {
365
366 bool OperandChanged = false;
367 SmallVector<MDNode *, 16> NewOperands;
368 unsigned NumOperands = N->getNumOperands();
369
370 // Check if any operand is or contains a global variable in GVMap, and thus
371 // converted to another value.
372 for (unsigned i = 0; i < NumOperands; ++i) {
373 MDNode *Operand = N->getOperand(i);
374 MDNode *NewOperand = MapMetadata(Operand, VM);
375 OperandChanged |= Operand != NewOperand;
376 NewOperands.push_back(NewOperand);
377 }
378
379 // If none of the operands has been modified, return immediately.
380 if (!OperandChanged) {
381 return;
382 }
383
384 // Replace the old operands with the new operands.
385 N->dropAllReferences();
386 for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
387 E = NewOperands.end();
388 I != E; ++I) {
389 N->addOperand(*I);
390 }
391 }
392