[C++] Use 'nullptr'. Target edition.
[oota-llvm.git] / lib / Target / NVPTX / NVPTXGenericToNVVM.cpp
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/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueMap.h"
28 #include "llvm/PassManager.h"
29
30 using namespace llvm;
31
32 namespace llvm {
33 void initializeGenericToNVVMPass(PassRegistry &);
34 }
35
36 namespace {
37 class GenericToNVVM : public ModulePass {
38 public:
39   static char ID;
40
41   GenericToNVVM() : ModulePass(ID) {}
42
43   virtual bool runOnModule(Module &M);
44
45   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46   }
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(Module *M, NamedMDNode *N);
59   MDNode *remapMDNode(Module *M, MDNode *N);
60
61   typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
62   typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
63   GVMapTy GVMap;
64   ConstantToValueMapTy ConstantToValueMap;
65 };
66 } // end namespace
67
68 char GenericToNVVM::ID = 0;
69
70 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
71
72 INITIALIZE_PASS(
73     GenericToNVVM, "generic-to-nvvm",
74     "Ensure that the global variables are in the global address space", false,
75     false)
76
77 bool GenericToNVVM::runOnModule(Module &M) {
78   // Create a clone of each global variable that has the default address space.
79   // The clone is created with the global address space  specifier, and the pair
80   // of original global variable and its clone is placed in the GVMap for later
81   // use.
82
83   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
84        I != E;) {
85     GlobalVariable *GV = I++;
86     if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
87         !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
88         !GV->getName().startswith("llvm.")) {
89       GlobalVariable *NewGV = new GlobalVariable(
90           M, GV->getType()->getElementType(), GV->isConstant(),
91           GV->getLinkage(),
92           GV->hasInitializer() ? GV->getInitializer() : nullptr,
93           "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
94       NewGV->copyAttributesFrom(GV);
95       GVMap[GV] = NewGV;
96     }
97   }
98
99   // Return immediately, if every global variable has a specific address space
100   // specifier.
101   if (GVMap.empty()) {
102     return false;
103   }
104
105   // Walk through the instructions in function defitinions, and replace any use
106   // of original global variables in GVMap with a use of the corresponding
107   // copies in GVMap.  If necessary, promote constants to instructions.
108   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
109     if (I->isDeclaration()) {
110       continue;
111     }
112     IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
113     for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
114          ++BBI) {
115       for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
116            ++II) {
117         for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
118           Value *Operand = II->getOperand(i);
119           if (isa<Constant>(Operand)) {
120             II->setOperand(
121                 i, remapConstant(&M, I, cast<Constant>(Operand), Builder));
122           }
123         }
124       }
125     }
126     ConstantToValueMap.clear();
127   }
128
129   // Walk through the metadata section and update the debug information
130   // associated with the global variables in the default address space.
131   for (Module::named_metadata_iterator I = M.named_metadata_begin(),
132                                        E = M.named_metadata_end();
133        I != E; I++) {
134     remapNamedMDNode(&M, I);
135   }
136
137   // Walk through the global variable  initializers, and replace any use of
138   // original global variables in GVMap with a use of the corresponding copies
139   // in GVMap.  The copies need to be bitcast to the original global variable
140   // types, as we cannot use cvta in global variable initializers.
141   for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
142     GlobalVariable *GV = I->first;
143     GlobalVariable *NewGV = I->second;
144     ++I;
145     Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
146     // At this point, the remaining uses of GV should be found only in global
147     // variable initializers, as other uses have been already been removed
148     // while walking through the instructions in function definitions.
149     for (Value::use_iterator UI = GV->use_begin(), UE = GV->use_end();
150          UI != UE;)
151       (UI++)->set(BitCastNewGV);
152     std::string Name = GV->getName();
153     GV->removeDeadConstantUsers();
154     GV->eraseFromParent();
155     NewGV->setName(Name);
156   }
157   GVMap.clear();
158
159   return true;
160 }
161
162 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
163                                       GlobalVariable *GV,
164                                       IRBuilder<> &Builder) {
165   PointerType *GVType = GV->getType();
166   Value *CVTA = nullptr;
167
168   // See if the address space conversion requires the operand to be bitcast
169   // to i8 addrspace(n)* first.
170   EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
171   if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
172     // A bitcast to i8 addrspace(n)* on the operand is needed.
173     LLVMContext &Context = M->getContext();
174     unsigned int AddrSpace = GVType->getAddressSpace();
175     Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
176     CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
177     // Insert the address space conversion.
178     Type *ResultType =
179         PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
180     SmallVector<Type *, 2> ParamTypes;
181     ParamTypes.push_back(ResultType);
182     ParamTypes.push_back(DestTy);
183     Function *CVTAFunction = Intrinsic::getDeclaration(
184         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
185     CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
186     // Another bitcast from i8 * to <the element type of GVType> * is
187     // required.
188     DestTy =
189         PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
190     CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
191   } else {
192     // A simple CVTA is enough.
193     SmallVector<Type *, 2> ParamTypes;
194     ParamTypes.push_back(PointerType::get(GVType->getElementType(),
195                                           llvm::ADDRESS_SPACE_GENERIC));
196     ParamTypes.push_back(GVType);
197     Function *CVTAFunction = Intrinsic::getDeclaration(
198         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
199     CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
200   }
201
202   return CVTA;
203 }
204
205 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
206                                     IRBuilder<> &Builder) {
207   // If the constant C has been converted already in the given function  F, just
208   // return the converted value.
209   ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
210   if (CTII != ConstantToValueMap.end()) {
211     return CTII->second;
212   }
213
214   Value *NewValue = C;
215   if (isa<GlobalVariable>(C)) {
216     // If the constant C is a global variable and is found in  GVMap, generate a
217     // set set of instructions that convert the clone of C with the global
218     // address space specifier to a generic pointer.
219     // The constant C cannot be used here, as it will be erased from the
220     // module eventually.  And the clone of C with the global address space
221     // specifier cannot be used here either, as it will affect the types of
222     // other instructions in the function.  Hence, this address space conversion
223     // is required.
224     GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
225     if (I != GVMap.end()) {
226       NewValue = getOrInsertCVTA(M, F, I->second, Builder);
227     }
228   } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
229              isa<ConstantStruct>(C)) {
230     // If any element in the constant vector or aggregate C is or uses a global
231     // variable in GVMap, the constant C needs to be reconstructed, using a set
232     // of instructions.
233     NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
234   } else if (isa<ConstantExpr>(C)) {
235     // If any operand in the constant expression C is or uses a global variable
236     // in GVMap, the constant expression C needs to be reconstructed, using a
237     // set of instructions.
238     NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
239   }
240
241   ConstantToValueMap[C] = NewValue;
242   return NewValue;
243 }
244
245 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
246     Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
247   bool OperandChanged = false;
248   SmallVector<Value *, 4> NewOperands;
249   unsigned NumOperands = C->getNumOperands();
250
251   // Check if any element is or uses a global variable in  GVMap, and thus
252   // converted to another value.
253   for (unsigned i = 0; i < NumOperands; ++i) {
254     Value *Operand = C->getOperand(i);
255     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
256     OperandChanged |= Operand != NewOperand;
257     NewOperands.push_back(NewOperand);
258   }
259
260   // If none of the elements has been modified, return C as it is.
261   if (!OperandChanged) {
262     return C;
263   }
264
265   // If any of the elements has been  modified, construct the equivalent
266   // vector or aggregate value with a set instructions and the converted
267   // elements.
268   Value *NewValue = UndefValue::get(C->getType());
269   if (isa<ConstantVector>(C)) {
270     for (unsigned i = 0; i < NumOperands; ++i) {
271       Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
272       NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
273     }
274   } else {
275     for (unsigned i = 0; i < NumOperands; ++i) {
276       NewValue =
277           Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
278     }
279   }
280
281   return NewValue;
282 }
283
284 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
285                                         IRBuilder<> &Builder) {
286   bool OperandChanged = false;
287   SmallVector<Value *, 4> NewOperands;
288   unsigned NumOperands = C->getNumOperands();
289
290   // Check if any operand is or uses a global variable in  GVMap, and thus
291   // converted to another value.
292   for (unsigned i = 0; i < NumOperands; ++i) {
293     Value *Operand = C->getOperand(i);
294     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
295     OperandChanged |= Operand != NewOperand;
296     NewOperands.push_back(NewOperand);
297   }
298
299   // If none of the operands has been modified, return C as it is.
300   if (!OperandChanged) {
301     return C;
302   }
303
304   // If any of the operands has been modified, construct the instruction with
305   // the converted operands.
306   unsigned Opcode = C->getOpcode();
307   switch (Opcode) {
308   case Instruction::ICmp:
309     // CompareConstantExpr (icmp)
310     return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
311                               NewOperands[0], NewOperands[1]);
312   case Instruction::FCmp:
313     // CompareConstantExpr (fcmp)
314     assert(false && "Address space conversion should have no effect "
315                     "on float point CompareConstantExpr (fcmp)!");
316     return C;
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                      NewOperands[0],
340                      makeArrayRef(&NewOperands[1], NumOperands - 1))
341                : Builder.CreateInBoundsGEP(
342                      NewOperands[0],
343                      makeArrayRef(&NewOperands[1], NumOperands - 1));
344   case Instruction::Select:
345     // SelectConstantExpr
346     return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
347   default:
348     // BinaryConstantExpr
349     if (Instruction::isBinaryOp(Opcode)) {
350       return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
351                                  NewOperands[0], NewOperands[1]);
352     }
353     // UnaryConstantExpr
354     if (Instruction::isCast(Opcode)) {
355       return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
356                                 NewOperands[0], C->getType());
357     }
358     assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
359     return C;
360   }
361 }
362
363 void GenericToNVVM::remapNamedMDNode(Module *M, NamedMDNode *N) {
364
365   bool OperandChanged = false;
366   SmallVector<MDNode *, 16> NewOperands;
367   unsigned NumOperands = N->getNumOperands();
368
369   // Check if any operand is or contains a global variable in  GVMap, and thus
370   // converted to another value.
371   for (unsigned i = 0; i < NumOperands; ++i) {
372     MDNode *Operand = N->getOperand(i);
373     MDNode *NewOperand = remapMDNode(M, Operand);
374     OperandChanged |= Operand != NewOperand;
375     NewOperands.push_back(NewOperand);
376   }
377
378   // If none of the operands has been modified, return immediately.
379   if (!OperandChanged) {
380     return;
381   }
382
383   // Replace the old operands with the new operands.
384   N->dropAllReferences();
385   for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
386                                            E = NewOperands.end();
387        I != E; ++I) {
388     N->addOperand(*I);
389   }
390 }
391
392 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
393
394   bool OperandChanged = false;
395   SmallVector<Value *, 8> NewOperands;
396   unsigned NumOperands = N->getNumOperands();
397
398   // Check if any operand is or contains a global variable in  GVMap, and thus
399   // converted to another value.
400   for (unsigned i = 0; i < NumOperands; ++i) {
401     Value *Operand = N->getOperand(i);
402     Value *NewOperand = Operand;
403     if (Operand) {
404       if (isa<GlobalVariable>(Operand)) {
405         GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
406         if (I != GVMap.end()) {
407           NewOperand = I->second;
408           if (++i < NumOperands) {
409             NewOperands.push_back(NewOperand);
410             // Address space of the global variable follows the global variable
411             // in the global variable debug info (see createGlobalVariable in
412             // lib/Analysis/DIBuilder.cpp).
413             NewOperand =
414                 ConstantInt::get(Type::getInt32Ty(M->getContext()),
415                                  I->second->getType()->getAddressSpace());
416           }
417         }
418       } else if (isa<MDNode>(Operand)) {
419         NewOperand = remapMDNode(M, cast<MDNode>(Operand));
420       }
421     }
422     OperandChanged |= Operand != NewOperand;
423     NewOperands.push_back(NewOperand);
424   }
425
426   // If none of the operands has been modified, return N as it is.
427   if (!OperandChanged) {
428     return N;
429   }
430
431   // If any of the operands has been modified, create a new MDNode with the new
432   // operands.
433   return MDNode::get(M->getContext(), makeArrayRef(NewOperands));
434 }