NVVMReflect.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. //===- NVVMReflect.cpp - NVVM Emulate conditional compilation -------------===//
  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. // This pass replaces occurrences of __nvvm_reflect("foo") and llvm.nvvm.reflect
  10. // with an integer.
  11. //
  12. // We choose the value we use by looking at metadata in the module itself. Note
  13. // that we intentionally only have one way to choose these values, because other
  14. // parts of LLVM (particularly, InstCombineCall) rely on being able to predict
  15. // the values chosen by this pass.
  16. //
  17. // If we see an unknown string, we replace its call with 0.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "NVPTX.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/InstIterator.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/Intrinsics.h"
  29. #include "llvm/IR/IntrinsicsNVPTX.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/PassManager.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/raw_os_ostream.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/Scalar.h"
  39. #include <sstream>
  40. #include <string>
  41. #define NVVM_REFLECT_FUNCTION "__nvvm_reflect"
  42. using namespace llvm;
  43. #define DEBUG_TYPE "nvptx-reflect"
  44. namespace llvm { void initializeNVVMReflectPass(PassRegistry &); }
  45. namespace {
  46. class NVVMReflect : public FunctionPass {
  47. public:
  48. static char ID;
  49. unsigned int SmVersion;
  50. NVVMReflect() : NVVMReflect(0) {}
  51. explicit NVVMReflect(unsigned int Sm) : FunctionPass(ID), SmVersion(Sm) {
  52. initializeNVVMReflectPass(*PassRegistry::getPassRegistry());
  53. }
  54. bool runOnFunction(Function &) override;
  55. };
  56. }
  57. FunctionPass *llvm::createNVVMReflectPass(unsigned int SmVersion) {
  58. return new NVVMReflect(SmVersion);
  59. }
  60. static cl::opt<bool>
  61. NVVMReflectEnabled("nvvm-reflect-enable", cl::init(true), cl::Hidden,
  62. cl::desc("NVVM reflection, enabled by default"));
  63. char NVVMReflect::ID = 0;
  64. INITIALIZE_PASS(NVVMReflect, "nvvm-reflect",
  65. "Replace occurrences of __nvvm_reflect() calls with 0/1", false,
  66. false)
  67. static bool runNVVMReflect(Function &F, unsigned SmVersion) {
  68. if (!NVVMReflectEnabled)
  69. return false;
  70. if (F.getName() == NVVM_REFLECT_FUNCTION) {
  71. assert(F.isDeclaration() && "_reflect function should not have a body");
  72. assert(F.getReturnType()->isIntegerTy() &&
  73. "_reflect's return type should be integer");
  74. return false;
  75. }
  76. SmallVector<Instruction *, 4> ToRemove;
  77. // Go through the calls in this function. Each call to __nvvm_reflect or
  78. // llvm.nvvm.reflect should be a CallInst with a ConstantArray argument.
  79. // First validate that. If the c-string corresponding to the ConstantArray can
  80. // be found successfully, see if it can be found in VarMap. If so, replace the
  81. // uses of CallInst with the value found in VarMap. If not, replace the use
  82. // with value 0.
  83. // The IR for __nvvm_reflect calls differs between CUDA versions.
  84. //
  85. // CUDA 6.5 and earlier uses this sequence:
  86. // %ptr = tail call i8* @llvm.nvvm.ptr.constant.to.gen.p0i8.p4i8
  87. // (i8 addrspace(4)* getelementptr inbounds
  88. // ([8 x i8], [8 x i8] addrspace(4)* @str, i32 0, i32 0))
  89. // %reflect = tail call i32 @__nvvm_reflect(i8* %ptr)
  90. //
  91. // The value returned by Sym->getOperand(0) is a Constant with a
  92. // ConstantDataSequential operand which can be converted to string and used
  93. // for lookup.
  94. //
  95. // CUDA 7.0 does it slightly differently:
  96. // %reflect = call i32 @__nvvm_reflect(i8* addrspacecast
  97. // (i8 addrspace(1)* getelementptr inbounds
  98. // ([8 x i8], [8 x i8] addrspace(1)* @str, i32 0, i32 0) to i8*))
  99. //
  100. // In this case, we get a Constant with a GlobalVariable operand and we need
  101. // to dig deeper to find its initializer with the string we'll use for lookup.
  102. for (Instruction &I : instructions(F)) {
  103. CallInst *Call = dyn_cast<CallInst>(&I);
  104. if (!Call)
  105. continue;
  106. Function *Callee = Call->getCalledFunction();
  107. if (!Callee || (Callee->getName() != NVVM_REFLECT_FUNCTION &&
  108. Callee->getIntrinsicID() != Intrinsic::nvvm_reflect))
  109. continue;
  110. // FIXME: Improve error handling here and elsewhere in this pass.
  111. assert(Call->getNumOperands() == 2 &&
  112. "Wrong number of operands to __nvvm_reflect function");
  113. // In cuda 6.5 and earlier, we will have an extra constant-to-generic
  114. // conversion of the string.
  115. const Value *Str = Call->getArgOperand(0);
  116. if (const CallInst *ConvCall = dyn_cast<CallInst>(Str)) {
  117. // FIXME: Add assertions about ConvCall.
  118. Str = ConvCall->getArgOperand(0);
  119. }
  120. assert(isa<ConstantExpr>(Str) &&
  121. "Format of __nvvm__reflect function not recognized");
  122. const ConstantExpr *GEP = cast<ConstantExpr>(Str);
  123. const Value *Sym = GEP->getOperand(0);
  124. assert(isa<Constant>(Sym) &&
  125. "Format of __nvvm_reflect function not recognized");
  126. const Value *Operand = cast<Constant>(Sym)->getOperand(0);
  127. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand)) {
  128. // For CUDA-7.0 style __nvvm_reflect calls, we need to find the operand's
  129. // initializer.
  130. assert(GV->hasInitializer() &&
  131. "Format of _reflect function not recognized");
  132. const Constant *Initializer = GV->getInitializer();
  133. Operand = Initializer;
  134. }
  135. assert(isa<ConstantDataSequential>(Operand) &&
  136. "Format of _reflect function not recognized");
  137. assert(cast<ConstantDataSequential>(Operand)->isCString() &&
  138. "Format of _reflect function not recognized");
  139. StringRef ReflectArg = cast<ConstantDataSequential>(Operand)->getAsString();
  140. ReflectArg = ReflectArg.substr(0, ReflectArg.size() - 1);
  141. LLVM_DEBUG(dbgs() << "Arg of _reflect : " << ReflectArg << "\n");
  142. int ReflectVal = 0; // The default value is 0
  143. if (ReflectArg == "__CUDA_FTZ") {
  144. // Try to pull __CUDA_FTZ from the nvvm-reflect-ftz module flag. Our
  145. // choice here must be kept in sync with AutoUpgrade, which uses the same
  146. // technique to detect whether ftz is enabled.
  147. if (auto *Flag = mdconst::extract_or_null<ConstantInt>(
  148. F.getParent()->getModuleFlag("nvvm-reflect-ftz")))
  149. ReflectVal = Flag->getSExtValue();
  150. } else if (ReflectArg == "__CUDA_ARCH") {
  151. ReflectVal = SmVersion * 10;
  152. }
  153. Call->replaceAllUsesWith(ConstantInt::get(Call->getType(), ReflectVal));
  154. ToRemove.push_back(Call);
  155. }
  156. for (Instruction *I : ToRemove)
  157. I->eraseFromParent();
  158. return ToRemove.size() > 0;
  159. }
  160. bool NVVMReflect::runOnFunction(Function &F) {
  161. return runNVVMReflect(F, SmVersion);
  162. }
  163. NVVMReflectPass::NVVMReflectPass() : NVVMReflectPass(0) {}
  164. PreservedAnalyses NVVMReflectPass::run(Function &F,
  165. FunctionAnalysisManager &AM) {
  166. return runNVVMReflect(F, SmVersion) ? PreservedAnalyses::none()
  167. : PreservedAnalyses::all();
  168. }