test commit: add minor comment
[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/ADT/ValueMap.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.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(), GV->hasInitializer() ? GV->getInitializer() : NULL,
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   // Walk through the metadata section and update the debug information
129   // associated with the global variables in the default address space.
130   for (Module::named_metadata_iterator I = M.named_metadata_begin(),
131                                        E = M.named_metadata_end();
132        I != E; I++) {
133     remapNamedMDNode(&M, I);
134   }
135
136   // Walk through the global variable  initializers, and replace any use of
137   // original global variables in GVMap with a use of the corresponding copies
138   // in GVMap.  The copies need to be bitcast to the original global variable
139   // types, as we cannot use cvta in global variable initializers.
140   for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
141     GlobalVariable *GV = I->first;
142     GlobalVariable *NewGV = I->second;
143     ++I;
144     Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
145     // At this point, the remaining uses of GV should be found only in global
146     // variable initializers, as other uses have been already been removed
147     // while walking through the instructions in function definitions.
148     for (Value::use_iterator UI = GV->use_begin(), UE = GV->use_end();
149          UI != UE;) {
150       Use &U = (UI++).getUse();
151       U.set(BitCastNewGV);
152     }
153     std::string Name = GV->getName();
154     GV->removeDeadConstantUsers();
155     GV->eraseFromParent();
156     NewGV->setName(Name);
157   }
158   GVMap.clear();
159
160   return true;
161 }
162
163 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
164                                       GlobalVariable *GV,
165                                       IRBuilder<> &Builder) {
166   PointerType *GVType = GV->getType();
167   Value *CVTA = NULL;
168
169   // See if the address space conversion requires the operand to be bitcast
170   // to i8 addrspace(n)* first.
171   EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
172   if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
173     // A bitcast to i8 addrspace(n)* on the operand is needed.
174     LLVMContext &Context = M->getContext();
175     unsigned int AddrSpace = GVType->getAddressSpace();
176     Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
177     CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
178     // Insert the address space conversion.
179     Type *ResultType =
180         PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
181     SmallVector<Type *, 2> ParamTypes;
182     ParamTypes.push_back(ResultType);
183     ParamTypes.push_back(DestTy);
184     Function *CVTAFunction = Intrinsic::getDeclaration(
185         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
186     CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
187     // Another bitcast from i8 * to <the element type of GVType> * is
188     // required.
189     DestTy =
190         PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
191     CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
192   } else {
193     // A simple CVTA is enough.
194     SmallVector<Type *, 2> ParamTypes;
195     ParamTypes.push_back(PointerType::get(GVType->getElementType(),
196                                           llvm::ADDRESS_SPACE_GENERIC));
197     ParamTypes.push_back(GVType);
198     Function *CVTAFunction = Intrinsic::getDeclaration(
199         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
200     CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
201   }
202
203   return CVTA;
204 }
205
206 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
207                                     IRBuilder<> &Builder) {
208   // If the constant C has been converted already in the given function  F, just
209   // return the converted value.
210   ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
211   if (CTII != ConstantToValueMap.end()) {
212     return CTII->second;
213   }
214
215   Value *NewValue = C;
216   if (isa<GlobalVariable>(C)) {
217     // If the constant C is a global variable and is found in  GVMap, generate a
218     // set set of instructions that convert the clone of C with the global
219     // address space specifier to a generic pointer.
220     // The constant C cannot be used here, as it will be erased from the
221     // module eventually.  And the clone of C with the global address space
222     // specifier cannot be used here either, as it will affect the types of
223     // other instructions in the function.  Hence, this address space conversion
224     // is required.
225     GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
226     if (I != GVMap.end()) {
227       NewValue = getOrInsertCVTA(M, F, I->second, Builder);
228     }
229   } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
230              isa<ConstantStruct>(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
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
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     assert(false && "Address space conversion should have no effect "
316                     "on float point CompareConstantExpr (fcmp)!");
317     return C;
318   case Instruction::ExtractElement:
319     // ExtractElementConstantExpr
320     return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
321   case Instruction::InsertElement:
322     // InsertElementConstantExpr
323     return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
324                                        NewOperands[2]);
325   case Instruction::ShuffleVector:
326     // ShuffleVector
327     return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
328                                        NewOperands[2]);
329   case Instruction::ExtractValue:
330     // ExtractValueConstantExpr
331     return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
332   case Instruction::InsertValue:
333     // InsertValueConstantExpr
334     return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
335                                      C->getIndices());
336   case Instruction::GetElementPtr:
337     // GetElementPtrConstantExpr
338     return cast<GEPOperator>(C)->isInBounds()
339                ? Builder.CreateGEP(
340                      NewOperands[0],
341                      makeArrayRef(&NewOperands[1], NumOperands - 1))
342                : Builder.CreateInBoundsGEP(
343                      NewOperands[0],
344                      makeArrayRef(&NewOperands[1], NumOperands - 1));
345   case Instruction::Select:
346     // SelectConstantExpr
347     return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
348   default:
349     // BinaryConstantExpr
350     if (Instruction::isBinaryOp(Opcode)) {
351       return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
352                                  NewOperands[0], NewOperands[1]);
353     }
354     // UnaryConstantExpr
355     if (Instruction::isCast(Opcode)) {
356       return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
357                                 NewOperands[0], C->getType());
358     }
359     assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
360     return C;
361   }
362 }
363
364 void GenericToNVVM::remapNamedMDNode(Module *M, 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 = remapMDNode(M, Operand);
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
393 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
394
395   bool OperandChanged = false;
396   SmallVector<Value *, 8> NewOperands;
397   unsigned NumOperands = N->getNumOperands();
398
399   // Check if any operand is or contains a global variable in  GVMap, and thus
400   // converted to another value.
401   for (unsigned i = 0; i < NumOperands; ++i) {
402     Value *Operand = N->getOperand(i);
403     Value *NewOperand = Operand;
404     if (Operand) {
405       if (isa<GlobalVariable>(Operand)) {
406         GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
407         if (I != GVMap.end()) {
408           NewOperand = I->second;
409           if (++i < NumOperands) {
410             NewOperands.push_back(NewOperand);
411             // Address space of the global variable follows the global variable
412             // in the global variable debug info (see createGlobalVariable in
413             // lib/Analysis/DIBuilder.cpp).
414             NewOperand =
415                 ConstantInt::get(Type::getInt32Ty(M->getContext()),
416                                  I->second->getType()->getAddressSpace());
417           }
418         }
419       } else if (isa<MDNode>(Operand)) {
420         NewOperand = remapMDNode(M, cast<MDNode>(Operand));
421       }
422     }
423     OperandChanged |= Operand != NewOperand;
424     NewOperands.push_back(NewOperand);
425   }
426
427   // If none of the operands has been modified, return N as it is.
428   if (!OperandChanged) {
429     return N;
430   }
431
432   // If any of the operands has been modified, create a new MDNode with the new
433   // operands.
434   return MDNode::get(M->getContext(), makeArrayRef(NewOperands));
435 }