LLVM API Documentation

NVPTXGenericToNVVM.cpp
Go to the documentation of this file.
00001 //===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Convert generic global variables into either .global or .const access based
00011 // on the variable's "constant" qualifier.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "NVPTX.h"
00016 #include "MCTargetDesc/NVPTXBaseInfo.h"
00017 #include "NVPTXUtilities.h"
00018 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
00019 #include "llvm/CodeGen/ValueTypes.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/IRBuilder.h"
00023 #include "llvm/IR/Instructions.h"
00024 #include "llvm/IR/Intrinsics.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/IR/Operator.h"
00027 #include "llvm/IR/ValueMap.h"
00028 #include "llvm/PassManager.h"
00029 
00030 using namespace llvm;
00031 
00032 namespace llvm {
00033 void initializeGenericToNVVMPass(PassRegistry &);
00034 }
00035 
00036 namespace {
00037 class GenericToNVVM : public ModulePass {
00038 public:
00039   static char ID;
00040 
00041   GenericToNVVM() : ModulePass(ID) {}
00042 
00043   bool runOnModule(Module &M) override;
00044 
00045   void getAnalysisUsage(AnalysisUsage &AU) const override {}
00046 
00047 private:
00048   Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
00049                          IRBuilder<> &Builder);
00050   Value *remapConstant(Module *M, Function *F, Constant *C,
00051                        IRBuilder<> &Builder);
00052   Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
00053                                                 Constant *C,
00054                                                 IRBuilder<> &Builder);
00055   Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
00056                            IRBuilder<> &Builder);
00057   void remapNamedMDNode(Module *M, NamedMDNode *N);
00058   MDNode *remapMDNode(Module *M, MDNode *N);
00059 
00060   typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
00061   typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
00062   GVMapTy GVMap;
00063   ConstantToValueMapTy ConstantToValueMap;
00064 };
00065 } // end namespace
00066 
00067 char GenericToNVVM::ID = 0;
00068 
00069 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
00070 
00071 INITIALIZE_PASS(
00072     GenericToNVVM, "generic-to-nvvm",
00073     "Ensure that the global variables are in the global address space", false,
00074     false)
00075 
00076 bool GenericToNVVM::runOnModule(Module &M) {
00077   // Create a clone of each global variable that has the default address space.
00078   // The clone is created with the global address space  specifier, and the pair
00079   // of original global variable and its clone is placed in the GVMap for later
00080   // use.
00081 
00082   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00083        I != E;) {
00084     GlobalVariable *GV = I++;
00085     if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
00086         !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
00087         !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
00088       GlobalVariable *NewGV = new GlobalVariable(
00089           M, GV->getType()->getElementType(), GV->isConstant(),
00090           GV->getLinkage(),
00091           GV->hasInitializer() ? GV->getInitializer() : nullptr,
00092           "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
00093       NewGV->copyAttributesFrom(GV);
00094       GVMap[GV] = NewGV;
00095     }
00096   }
00097 
00098   // Return immediately, if every global variable has a specific address space
00099   // specifier.
00100   if (GVMap.empty()) {
00101     return false;
00102   }
00103 
00104   // Walk through the instructions in function defitinions, and replace any use
00105   // of original global variables in GVMap with a use of the corresponding
00106   // copies in GVMap.  If necessary, promote constants to instructions.
00107   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00108     if (I->isDeclaration()) {
00109       continue;
00110     }
00111     IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
00112     for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
00113          ++BBI) {
00114       for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
00115            ++II) {
00116         for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
00117           Value *Operand = II->getOperand(i);
00118           if (isa<Constant>(Operand)) {
00119             II->setOperand(
00120                 i, remapConstant(&M, I, cast<Constant>(Operand), Builder));
00121           }
00122         }
00123       }
00124     }
00125     ConstantToValueMap.clear();
00126   }
00127 
00128   // Walk through the metadata section and update the debug information
00129   // associated with the global variables in the default address space.
00130   for (Module::named_metadata_iterator I = M.named_metadata_begin(),
00131                                        E = M.named_metadata_end();
00132        I != E; I++) {
00133     remapNamedMDNode(&M, I);
00134   }
00135 
00136   // Walk through the global variable  initializers, and replace any use of
00137   // original global variables in GVMap with a use of the corresponding copies
00138   // in GVMap.  The copies need to be bitcast to the original global variable
00139   // types, as we cannot use cvta in global variable initializers.
00140   for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
00141     GlobalVariable *GV = I->first;
00142     GlobalVariable *NewGV = I->second;
00143 
00144     // Remove GV from the map so that it can be RAUWed.  Note that
00145     // DenseMap::erase() won't invalidate any iterators but this one.
00146     auto Next = std::next(I);
00147     GVMap.erase(I);
00148     I = Next;
00149 
00150     Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
00151     // At this point, the remaining uses of GV should be found only in global
00152     // variable initializers, as other uses have been already been removed
00153     // while walking through the instructions in function definitions.
00154     GV->replaceAllUsesWith(BitCastNewGV);
00155     std::string Name = GV->getName();
00156     GV->eraseFromParent();
00157     NewGV->setName(Name);
00158   }
00159   assert(GVMap.empty() && "Expected it to be empty by now");
00160 
00161   return true;
00162 }
00163 
00164 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
00165                                       GlobalVariable *GV,
00166                                       IRBuilder<> &Builder) {
00167   PointerType *GVType = GV->getType();
00168   Value *CVTA = nullptr;
00169 
00170   // See if the address space conversion requires the operand to be bitcast
00171   // to i8 addrspace(n)* first.
00172   EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
00173   if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
00174     // A bitcast to i8 addrspace(n)* on the operand is needed.
00175     LLVMContext &Context = M->getContext();
00176     unsigned int AddrSpace = GVType->getAddressSpace();
00177     Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
00178     CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
00179     // Insert the address space conversion.
00180     Type *ResultType =
00181         PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
00182     SmallVector<Type *, 2> ParamTypes;
00183     ParamTypes.push_back(ResultType);
00184     ParamTypes.push_back(DestTy);
00185     Function *CVTAFunction = Intrinsic::getDeclaration(
00186         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
00187     CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
00188     // Another bitcast from i8 * to <the element type of GVType> * is
00189     // required.
00190     DestTy =
00191         PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
00192     CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
00193   } else {
00194     // A simple CVTA is enough.
00195     SmallVector<Type *, 2> ParamTypes;
00196     ParamTypes.push_back(PointerType::get(GVType->getElementType(),
00197                                           llvm::ADDRESS_SPACE_GENERIC));
00198     ParamTypes.push_back(GVType);
00199     Function *CVTAFunction = Intrinsic::getDeclaration(
00200         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
00201     CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
00202   }
00203 
00204   return CVTA;
00205 }
00206 
00207 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
00208                                     IRBuilder<> &Builder) {
00209   // If the constant C has been converted already in the given function  F, just
00210   // return the converted value.
00211   ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
00212   if (CTII != ConstantToValueMap.end()) {
00213     return CTII->second;
00214   }
00215 
00216   Value *NewValue = C;
00217   if (isa<GlobalVariable>(C)) {
00218     // If the constant C is a global variable and is found in  GVMap, generate a
00219     // set set of instructions that convert the clone of C with the global
00220     // address space specifier to a generic pointer.
00221     // The constant C cannot be used here, as it will be erased from the
00222     // module eventually.  And the clone of C with the global address space
00223     // specifier cannot be used here either, as it will affect the types of
00224     // other instructions in the function.  Hence, this address space conversion
00225     // is required.
00226     GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
00227     if (I != GVMap.end()) {
00228       NewValue = getOrInsertCVTA(M, F, I->second, Builder);
00229     }
00230   } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
00231              isa<ConstantStruct>(C)) {
00232     // If any element in the constant vector or aggregate C is or uses a global
00233     // variable in GVMap, the constant C needs to be reconstructed, using a set
00234     // of instructions.
00235     NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
00236   } else if (isa<ConstantExpr>(C)) {
00237     // If any operand in the constant expression C is or uses a global variable
00238     // in GVMap, the constant expression C needs to be reconstructed, using a
00239     // set of instructions.
00240     NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
00241   }
00242 
00243   ConstantToValueMap[C] = NewValue;
00244   return NewValue;
00245 }
00246 
00247 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
00248     Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
00249   bool OperandChanged = false;
00250   SmallVector<Value *, 4> NewOperands;
00251   unsigned NumOperands = C->getNumOperands();
00252 
00253   // Check if any element is or uses a global variable in  GVMap, and thus
00254   // converted to another value.
00255   for (unsigned i = 0; i < NumOperands; ++i) {
00256     Value *Operand = C->getOperand(i);
00257     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
00258     OperandChanged |= Operand != NewOperand;
00259     NewOperands.push_back(NewOperand);
00260   }
00261 
00262   // If none of the elements has been modified, return C as it is.
00263   if (!OperandChanged) {
00264     return C;
00265   }
00266 
00267   // If any of the elements has been  modified, construct the equivalent
00268   // vector or aggregate value with a set instructions and the converted
00269   // elements.
00270   Value *NewValue = UndefValue::get(C->getType());
00271   if (isa<ConstantVector>(C)) {
00272     for (unsigned i = 0; i < NumOperands; ++i) {
00273       Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
00274       NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
00275     }
00276   } else {
00277     for (unsigned i = 0; i < NumOperands; ++i) {
00278       NewValue =
00279           Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
00280     }
00281   }
00282 
00283   return NewValue;
00284 }
00285 
00286 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
00287                                         IRBuilder<> &Builder) {
00288   bool OperandChanged = false;
00289   SmallVector<Value *, 4> NewOperands;
00290   unsigned NumOperands = C->getNumOperands();
00291 
00292   // Check if any operand is or uses a global variable in  GVMap, and thus
00293   // converted to another value.
00294   for (unsigned i = 0; i < NumOperands; ++i) {
00295     Value *Operand = C->getOperand(i);
00296     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
00297     OperandChanged |= Operand != NewOperand;
00298     NewOperands.push_back(NewOperand);
00299   }
00300 
00301   // If none of the operands has been modified, return C as it is.
00302   if (!OperandChanged) {
00303     return C;
00304   }
00305 
00306   // If any of the operands has been modified, construct the instruction with
00307   // the converted operands.
00308   unsigned Opcode = C->getOpcode();
00309   switch (Opcode) {
00310   case Instruction::ICmp:
00311     // CompareConstantExpr (icmp)
00312     return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
00313                               NewOperands[0], NewOperands[1]);
00314   case Instruction::FCmp:
00315     // CompareConstantExpr (fcmp)
00316     assert(false && "Address space conversion should have no effect "
00317                     "on float point CompareConstantExpr (fcmp)!");
00318     return C;
00319   case Instruction::ExtractElement:
00320     // ExtractElementConstantExpr
00321     return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
00322   case Instruction::InsertElement:
00323     // InsertElementConstantExpr
00324     return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
00325                                        NewOperands[2]);
00326   case Instruction::ShuffleVector:
00327     // ShuffleVector
00328     return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
00329                                        NewOperands[2]);
00330   case Instruction::ExtractValue:
00331     // ExtractValueConstantExpr
00332     return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
00333   case Instruction::InsertValue:
00334     // InsertValueConstantExpr
00335     return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
00336                                      C->getIndices());
00337   case Instruction::GetElementPtr:
00338     // GetElementPtrConstantExpr
00339     return cast<GEPOperator>(C)->isInBounds()
00340                ? Builder.CreateGEP(
00341                      NewOperands[0],
00342                      makeArrayRef(&NewOperands[1], NumOperands - 1))
00343                : Builder.CreateInBoundsGEP(
00344                      NewOperands[0],
00345                      makeArrayRef(&NewOperands[1], NumOperands - 1));
00346   case Instruction::Select:
00347     // SelectConstantExpr
00348     return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
00349   default:
00350     // BinaryConstantExpr
00351     if (Instruction::isBinaryOp(Opcode)) {
00352       return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
00353                                  NewOperands[0], NewOperands[1]);
00354     }
00355     // UnaryConstantExpr
00356     if (Instruction::isCast(Opcode)) {
00357       return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
00358                                 NewOperands[0], C->getType());
00359     }
00360     assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
00361     return C;
00362   }
00363 }
00364 
00365 void GenericToNVVM::remapNamedMDNode(Module *M, NamedMDNode *N) {
00366 
00367   bool OperandChanged = false;
00368   SmallVector<MDNode *, 16> NewOperands;
00369   unsigned NumOperands = N->getNumOperands();
00370 
00371   // Check if any operand is or contains a global variable in  GVMap, and thus
00372   // converted to another value.
00373   for (unsigned i = 0; i < NumOperands; ++i) {
00374     MDNode *Operand = N->getOperand(i);
00375     MDNode *NewOperand = remapMDNode(M, Operand);
00376     OperandChanged |= Operand != NewOperand;
00377     NewOperands.push_back(NewOperand);
00378   }
00379 
00380   // If none of the operands has been modified, return immediately.
00381   if (!OperandChanged) {
00382     return;
00383   }
00384 
00385   // Replace the old operands with the new operands.
00386   N->dropAllReferences();
00387   for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
00388                                            E = NewOperands.end();
00389        I != E; ++I) {
00390     N->addOperand(*I);
00391   }
00392 }
00393 
00394 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
00395 
00396   bool OperandChanged = false;
00397   SmallVector<Value *, 8> NewOperands;
00398   unsigned NumOperands = N->getNumOperands();
00399 
00400   // Check if any operand is or contains a global variable in  GVMap, and thus
00401   // converted to another value.
00402   for (unsigned i = 0; i < NumOperands; ++i) {
00403     Value *Operand = N->getOperand(i);
00404     Value *NewOperand = Operand;
00405     if (Operand) {
00406       if (isa<GlobalVariable>(Operand)) {
00407         GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
00408         if (I != GVMap.end()) {
00409           NewOperand = I->second;
00410           if (++i < NumOperands) {
00411             NewOperands.push_back(NewOperand);
00412             // Address space of the global variable follows the global variable
00413             // in the global variable debug info (see createGlobalVariable in
00414             // lib/Analysis/DIBuilder.cpp).
00415             NewOperand =
00416                 ConstantInt::get(Type::getInt32Ty(M->getContext()),
00417                                  I->second->getType()->getAddressSpace());
00418           }
00419         }
00420       } else if (isa<MDNode>(Operand)) {
00421         NewOperand = remapMDNode(M, cast<MDNode>(Operand));
00422       }
00423     }
00424     OperandChanged |= Operand != NewOperand;
00425     NewOperands.push_back(NewOperand);
00426   }
00427 
00428   // If none of the operands has been modified, return N as it is.
00429   if (!OperandChanged) {
00430     return N;
00431   }
00432 
00433   // If any of the operands has been modified, create a new MDNode with the new
00434   // operands.
00435   return MDNode::get(M->getContext(), makeArrayRef(NewOperands));
00436 }