NVPTXGenericToNVVM.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. //===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Convert generic global variables into either .global or .const access based
  10. // on the variable's "constant" qualifier.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "MCTargetDesc/NVPTXBaseInfo.h"
  14. #include "NVPTX.h"
  15. #include "NVPTXUtilities.h"
  16. #include "llvm/CodeGen/ValueTypes.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/Intrinsics.h"
  22. #include "llvm/IR/LegacyPassManager.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/Operator.h"
  25. #include "llvm/IR/ValueMap.h"
  26. #include "llvm/Transforms/Utils/ValueMapper.h"
  27. using namespace llvm;
  28. namespace llvm {
  29. void initializeGenericToNVVMPass(PassRegistry &);
  30. }
  31. namespace {
  32. class GenericToNVVM : public ModulePass {
  33. public:
  34. static char ID;
  35. GenericToNVVM() : ModulePass(ID) {}
  36. bool runOnModule(Module &M) override;
  37. void getAnalysisUsage(AnalysisUsage &AU) const override {}
  38. private:
  39. Value *remapConstant(Module *M, Function *F, Constant *C,
  40. IRBuilder<> &Builder);
  41. Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
  42. Constant *C,
  43. IRBuilder<> &Builder);
  44. Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
  45. IRBuilder<> &Builder);
  46. typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
  47. typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
  48. GVMapTy GVMap;
  49. ConstantToValueMapTy ConstantToValueMap;
  50. };
  51. } // end namespace
  52. char GenericToNVVM::ID = 0;
  53. ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
  54. INITIALIZE_PASS(
  55. GenericToNVVM, "generic-to-nvvm",
  56. "Ensure that the global variables are in the global address space", false,
  57. false)
  58. bool GenericToNVVM::runOnModule(Module &M) {
  59. // Create a clone of each global variable that has the default address space.
  60. // The clone is created with the global address space specifier, and the pair
  61. // of original global variable and its clone is placed in the GVMap for later
  62. // use.
  63. for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
  64. if (GV.getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
  65. !llvm::isTexture(GV) && !llvm::isSurface(GV) && !llvm::isSampler(GV) &&
  66. !GV.getName().startswith("llvm.")) {
  67. GlobalVariable *NewGV = new GlobalVariable(
  68. M, GV.getValueType(), GV.isConstant(), GV.getLinkage(),
  69. GV.hasInitializer() ? GV.getInitializer() : nullptr, "", &GV,
  70. GV.getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
  71. NewGV->copyAttributesFrom(&GV);
  72. GVMap[&GV] = NewGV;
  73. }
  74. }
  75. // Return immediately, if every global variable has a specific address space
  76. // specifier.
  77. if (GVMap.empty()) {
  78. return false;
  79. }
  80. // Walk through the instructions in function defitinions, and replace any use
  81. // of original global variables in GVMap with a use of the corresponding
  82. // copies in GVMap. If necessary, promote constants to instructions.
  83. for (Function &F : M) {
  84. if (F.isDeclaration()) {
  85. continue;
  86. }
  87. IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
  88. for (BasicBlock &BB : F) {
  89. for (Instruction &II : BB) {
  90. for (unsigned i = 0, e = II.getNumOperands(); i < e; ++i) {
  91. Value *Operand = II.getOperand(i);
  92. if (isa<Constant>(Operand)) {
  93. II.setOperand(
  94. i, remapConstant(&M, &F, cast<Constant>(Operand), Builder));
  95. }
  96. }
  97. }
  98. }
  99. ConstantToValueMap.clear();
  100. }
  101. // Copy GVMap over to a standard value map.
  102. ValueToValueMapTy VM;
  103. for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
  104. VM[I->first] = I->second;
  105. // Walk through the global variable initializers, and replace any use of
  106. // original global variables in GVMap with a use of the corresponding copies
  107. // in GVMap. The copies need to be bitcast to the original global variable
  108. // types, as we cannot use cvta in global variable initializers.
  109. for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
  110. GlobalVariable *GV = I->first;
  111. GlobalVariable *NewGV = I->second;
  112. // Remove GV from the map so that it can be RAUWed. Note that
  113. // DenseMap::erase() won't invalidate any iterators but this one.
  114. auto Next = std::next(I);
  115. GVMap.erase(I);
  116. I = Next;
  117. Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
  118. // At this point, the remaining uses of GV should be found only in global
  119. // variable initializers, as other uses have been already been removed
  120. // while walking through the instructions in function definitions.
  121. GV->replaceAllUsesWith(BitCastNewGV);
  122. std::string Name = std::string(GV->getName());
  123. GV->eraseFromParent();
  124. NewGV->setName(Name);
  125. }
  126. assert(GVMap.empty() && "Expected it to be empty by now");
  127. return true;
  128. }
  129. Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
  130. IRBuilder<> &Builder) {
  131. // If the constant C has been converted already in the given function F, just
  132. // return the converted value.
  133. ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
  134. if (CTII != ConstantToValueMap.end()) {
  135. return CTII->second;
  136. }
  137. Value *NewValue = C;
  138. if (isa<GlobalVariable>(C)) {
  139. // If the constant C is a global variable and is found in GVMap, substitute
  140. //
  141. // addrspacecast GVMap[C] to addrspace(0)
  142. //
  143. // for our use of C.
  144. GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
  145. if (I != GVMap.end()) {
  146. GlobalVariable *GV = I->second;
  147. NewValue = Builder.CreateAddrSpaceCast(
  148. GV,
  149. PointerType::get(GV->getValueType(), llvm::ADDRESS_SPACE_GENERIC));
  150. }
  151. } else if (isa<ConstantAggregate>(C)) {
  152. // If any element in the constant vector or aggregate C is or uses a global
  153. // variable in GVMap, the constant C needs to be reconstructed, using a set
  154. // of instructions.
  155. NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
  156. } else if (isa<ConstantExpr>(C)) {
  157. // If any operand in the constant expression C is or uses a global variable
  158. // in GVMap, the constant expression C needs to be reconstructed, using a
  159. // set of instructions.
  160. NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
  161. }
  162. ConstantToValueMap[C] = NewValue;
  163. return NewValue;
  164. }
  165. Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
  166. Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
  167. bool OperandChanged = false;
  168. SmallVector<Value *, 4> NewOperands;
  169. unsigned NumOperands = C->getNumOperands();
  170. // Check if any element is or uses a global variable in GVMap, and thus
  171. // converted to another value.
  172. for (unsigned i = 0; i < NumOperands; ++i) {
  173. Value *Operand = C->getOperand(i);
  174. Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
  175. OperandChanged |= Operand != NewOperand;
  176. NewOperands.push_back(NewOperand);
  177. }
  178. // If none of the elements has been modified, return C as it is.
  179. if (!OperandChanged) {
  180. return C;
  181. }
  182. // If any of the elements has been modified, construct the equivalent
  183. // vector or aggregate value with a set instructions and the converted
  184. // elements.
  185. Value *NewValue = PoisonValue::get(C->getType());
  186. if (isa<ConstantVector>(C)) {
  187. for (unsigned i = 0; i < NumOperands; ++i) {
  188. Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
  189. NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
  190. }
  191. } else {
  192. for (unsigned i = 0; i < NumOperands; ++i) {
  193. NewValue =
  194. Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
  195. }
  196. }
  197. return NewValue;
  198. }
  199. Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
  200. IRBuilder<> &Builder) {
  201. bool OperandChanged = false;
  202. SmallVector<Value *, 4> NewOperands;
  203. unsigned NumOperands = C->getNumOperands();
  204. // Check if any operand is or uses a global variable in GVMap, and thus
  205. // converted to another value.
  206. for (unsigned i = 0; i < NumOperands; ++i) {
  207. Value *Operand = C->getOperand(i);
  208. Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
  209. OperandChanged |= Operand != NewOperand;
  210. NewOperands.push_back(NewOperand);
  211. }
  212. // If none of the operands has been modified, return C as it is.
  213. if (!OperandChanged) {
  214. return C;
  215. }
  216. // If any of the operands has been modified, construct the instruction with
  217. // the converted operands.
  218. unsigned Opcode = C->getOpcode();
  219. switch (Opcode) {
  220. case Instruction::ICmp:
  221. // CompareConstantExpr (icmp)
  222. return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
  223. NewOperands[0], NewOperands[1]);
  224. case Instruction::FCmp:
  225. // CompareConstantExpr (fcmp)
  226. llvm_unreachable("Address space conversion should have no effect "
  227. "on float point CompareConstantExpr (fcmp)!");
  228. case Instruction::ExtractElement:
  229. // ExtractElementConstantExpr
  230. return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
  231. case Instruction::InsertElement:
  232. // InsertElementConstantExpr
  233. return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
  234. NewOperands[2]);
  235. case Instruction::ShuffleVector:
  236. // ShuffleVector
  237. return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
  238. NewOperands[2]);
  239. case Instruction::ExtractValue:
  240. // ExtractValueConstantExpr
  241. return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
  242. case Instruction::InsertValue:
  243. // InsertValueConstantExpr
  244. return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
  245. C->getIndices());
  246. case Instruction::GetElementPtr:
  247. // GetElementPtrConstantExpr
  248. return cast<GEPOperator>(C)->isInBounds()
  249. ? Builder.CreateGEP(
  250. cast<GEPOperator>(C)->getSourceElementType(),
  251. NewOperands[0],
  252. makeArrayRef(&NewOperands[1], NumOperands - 1))
  253. : Builder.CreateInBoundsGEP(
  254. cast<GEPOperator>(C)->getSourceElementType(),
  255. NewOperands[0],
  256. makeArrayRef(&NewOperands[1], NumOperands - 1));
  257. case Instruction::Select:
  258. // SelectConstantExpr
  259. return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
  260. default:
  261. // BinaryConstantExpr
  262. if (Instruction::isBinaryOp(Opcode)) {
  263. return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
  264. NewOperands[0], NewOperands[1]);
  265. }
  266. // UnaryConstantExpr
  267. if (Instruction::isCast(Opcode)) {
  268. return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
  269. NewOperands[0], C->getType());
  270. }
  271. llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
  272. }
  273. }