1 //===-- NVPTXLowerArgs.cpp - Lower arguments ------------------------------===// 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 // 10 // Arguments to kernel and device functions are passed via param space, 11 // which imposes certain restrictions: 12 // http://docs.nvidia.com/cuda/parallel-thread-execution/#state-spaces 13 // 14 // Kernel parameters are read-only and accessible only via ld.param 15 // instruction, directly or via a pointer. Pointers to kernel 16 // arguments can't be converted to generic address space. 17 // 18 // Device function parameters are directly accessible via 19 // ld.param/st.param, but taking the address of one returns a pointer 20 // to a copy created in local space which *can't* be used with 21 // ld.param/st.param. 22 // 23 // Copying a byval struct into local memory in IR allows us to enforce 24 // the param space restrictions, gives the rest of IR a pointer w/o 25 // param space restrictions, and gives us an opportunity to eliminate 26 // the copy. 27 // 28 // Pointer arguments to kernel functions need more work to be lowered: 29 // 30 // 1. Convert non-byval pointer arguments of CUDA kernels to pointers in the 31 // global address space. This allows later optimizations to emit 32 // ld.global.*/st.global.* for accessing these pointer arguments. For 33 // example, 34 // 35 // define void @foo(float* %input) { 36 // %v = load float, float* %input, align 4 37 // ... 38 // } 39 // 40 // becomes 41 // 42 // define void @foo(float* %input) { 43 // %input2 = addrspacecast float* %input to float addrspace(1)* 44 // %input3 = addrspacecast float addrspace(1)* %input2 to float* 45 // %v = load float, float* %input3, align 4 46 // ... 47 // } 48 // 49 // Later, NVPTXInferAddressSpaces will optimize it to 50 // 51 // define void @foo(float* %input) { 52 // %input2 = addrspacecast float* %input to float addrspace(1)* 53 // %v = load float, float addrspace(1)* %input2, align 4 54 // ... 55 // } 56 // 57 // 2. Convert pointers in a byval kernel parameter to pointers in the global 58 // address space. As #2, it allows NVPTX to emit more ld/st.global. E.g., 59 // 60 // struct S { 61 // int *x; 62 // int *y; 63 // }; 64 // __global__ void foo(S s) { 65 // int *b = s.y; 66 // // use b 67 // } 68 // 69 // "b" points to the global address space. In the IR level, 70 // 71 // define void @foo({i32*, i32*}* byval %input) { 72 // %b_ptr = getelementptr {i32*, i32*}, {i32*, i32*}* %input, i64 0, i32 1 73 // %b = load i32*, i32** %b_ptr 74 // ; use %b 75 // } 76 // 77 // becomes 78 // 79 // define void @foo({i32*, i32*}* byval %input) { 80 // %b_ptr = getelementptr {i32*, i32*}, {i32*, i32*}* %input, i64 0, i32 1 81 // %b = load i32*, i32** %b_ptr 82 // %b_global = addrspacecast i32* %b to i32 addrspace(1)* 83 // %b_generic = addrspacecast i32 addrspace(1)* %b_global to i32* 84 // ; use %b_generic 85 // } 86 // 87 // TODO: merge this pass with NVPTXInferAddressSpaces so that other passes don't 88 // cancel the addrspacecast pair this pass emits. 89 //===----------------------------------------------------------------------===// 90 91 #include "NVPTX.h" 92 #include "NVPTXTargetMachine.h" 93 #include "NVPTXUtilities.h" 94 #include "MCTargetDesc/NVPTXBaseInfo.h" 95 #include "llvm/Analysis/ValueTracking.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/Instructions.h" 98 #include "llvm/IR/Module.h" 99 #include "llvm/IR/Type.h" 100 #include "llvm/Pass.h" 101 102 using namespace llvm; 103 104 namespace llvm { 105 void initializeNVPTXLowerArgsPass(PassRegistry &); 106 } 107 108 namespace { 109 class NVPTXLowerArgs : public FunctionPass { 110 bool runOnFunction(Function &F) override; 111 112 bool runOnKernelFunction(Function &F); 113 bool runOnDeviceFunction(Function &F); 114 115 // handle byval parameters 116 void handleByValParam(Argument *Arg); 117 // Knowing Ptr must point to the global address space, this function 118 // addrspacecasts Ptr to global and then back to generic. This allows 119 // NVPTXInferAddressSpaces to fold the global-to-generic cast into 120 // loads/stores that appear later. 121 void markPointerAsGlobal(Value *Ptr); 122 123 public: 124 static char ID; // Pass identification, replacement for typeid 125 NVPTXLowerArgs(const NVPTXTargetMachine *TM = nullptr) 126 : FunctionPass(ID), TM(TM) {} 127 StringRef getPassName() const override { 128 return "Lower pointer arguments of CUDA kernels"; 129 } 130 131 private: 132 const NVPTXTargetMachine *TM; 133 }; 134 } // namespace 135 136 char NVPTXLowerArgs::ID = 1; 137 138 INITIALIZE_PASS(NVPTXLowerArgs, "nvptx-lower-args", 139 "Lower arguments (NVPTX)", false, false) 140 141 // ============================================================================= 142 // If the function had a byval struct ptr arg, say foo(%struct.x* byval %d), 143 // and we can't guarantee that the only accesses are loads, 144 // then add the following instructions to the first basic block: 145 // 146 // %temp = alloca %struct.x, align 8 147 // %tempd = addrspacecast %struct.x* %d to %struct.x addrspace(101)* 148 // %tv = load %struct.x addrspace(101)* %tempd 149 // store %struct.x %tv, %struct.x* %temp, align 8 150 // 151 // The above code allocates some space in the stack and copies the incoming 152 // struct from param space to local space. 153 // Then replace all occurrences of %d by %temp. 154 // 155 // In case we know that all users are GEPs or Loads, replace them with the same 156 // ones in parameter AS, so we can access them using ld.param. 157 // ============================================================================= 158 159 // Replaces the \p OldUser instruction with the same in parameter AS. 160 // Only Load and GEP are supported. 161 static void convertToParamAS(Value *OldUser, Value *Param) { 162 Instruction *I = dyn_cast<Instruction>(OldUser); 163 assert(I && "OldUser must be an instruction"); 164 struct IP { 165 Instruction *OldInstruction; 166 Value *NewParam; 167 }; 168 SmallVector<IP> ItemsToConvert = {{I, Param}}; 169 SmallVector<GetElementPtrInst *> GEPsToDelete; 170 while (!ItemsToConvert.empty()) { 171 IP I = ItemsToConvert.pop_back_val(); 172 if (auto *LI = dyn_cast<LoadInst>(I.OldInstruction)) 173 LI->setOperand(0, I.NewParam); 174 else if (auto *GEP = dyn_cast<GetElementPtrInst>(I.OldInstruction)) { 175 SmallVector<Value *, 4> Indices(GEP->indices()); 176 auto *NewGEP = GetElementPtrInst::Create(nullptr, I.NewParam, Indices, 177 GEP->getName(), GEP); 178 NewGEP->setIsInBounds(GEP->isInBounds()); 179 llvm::for_each(GEP->users(), [NewGEP, &ItemsToConvert](Value *V) { 180 ItemsToConvert.push_back({cast<Instruction>(V), NewGEP}); 181 }); 182 GEPsToDelete.push_back(GEP); 183 } else 184 llvm_unreachable("Only Load and GEP can be converted to param AS."); 185 } 186 llvm::for_each(GEPsToDelete, 187 [](GetElementPtrInst *GEP) { GEP->eraseFromParent(); }); 188 } 189 190 static bool isALoadChain(Value *Start) { 191 SmallVector<Value *, 16> ValuesToCheck = {Start}; 192 while (!ValuesToCheck.empty()) { 193 Value *V = ValuesToCheck.pop_back_val(); 194 Instruction *I = dyn_cast<Instruction>(V); 195 if (!I) 196 return false; 197 if (isa<GetElementPtrInst>(I)) 198 ValuesToCheck.append(I->user_begin(), I->user_end()); 199 else if (!isa<LoadInst>(I)) 200 return false; 201 } 202 return true; 203 } 204 205 void NVPTXLowerArgs::handleByValParam(Argument *Arg) { 206 Function *Func = Arg->getParent(); 207 Instruction *FirstInst = &(Func->getEntryBlock().front()); 208 PointerType *PType = dyn_cast<PointerType>(Arg->getType()); 209 210 assert(PType && "Expecting pointer type in handleByValParam"); 211 212 Type *StructType = PType->getElementType(); 213 214 if (llvm::all_of(Arg->users(), isALoadChain)) { 215 // Replace all loads with the loads in param AS. This allows loading the Arg 216 // directly from parameter AS, without making a temporary copy. 217 SmallVector<User *, 16> UsersToUpdate(Arg->users()); 218 Value *ArgInParamAS = new AddrSpaceCastInst( 219 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 220 FirstInst); 221 llvm::for_each(UsersToUpdate, [ArgInParamAS](Value *V) { 222 convertToParamAS(V, ArgInParamAS); 223 }); 224 return; 225 } 226 227 // Otherwise we have to create a temporary copy. 228 const DataLayout &DL = Func->getParent()->getDataLayout(); 229 unsigned AS = DL.getAllocaAddrSpace(); 230 AllocaInst *AllocA = new AllocaInst(StructType, AS, Arg->getName(), FirstInst); 231 // Set the alignment to alignment of the byval parameter. This is because, 232 // later load/stores assume that alignment, and we are going to replace 233 // the use of the byval parameter with this alloca instruction. 234 AllocA->setAlignment(Func->getParamAlign(Arg->getArgNo()) 235 .getValueOr(DL.getPrefTypeAlign(StructType))); 236 Arg->replaceAllUsesWith(AllocA); 237 238 Value *ArgInParam = new AddrSpaceCastInst( 239 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 240 FirstInst); 241 // Be sure to propagate alignment to this load; LLVM doesn't know that NVPTX 242 // addrspacecast preserves alignment. Since params are constant, this load is 243 // definitely not volatile. 244 LoadInst *LI = 245 new LoadInst(StructType, ArgInParam, Arg->getName(), 246 /*isVolatile=*/false, AllocA->getAlign(), FirstInst); 247 new StoreInst(LI, AllocA, FirstInst); 248 } 249 250 void NVPTXLowerArgs::markPointerAsGlobal(Value *Ptr) { 251 if (Ptr->getType()->getPointerAddressSpace() == ADDRESS_SPACE_GLOBAL) 252 return; 253 254 // Deciding where to emit the addrspacecast pair. 255 BasicBlock::iterator InsertPt; 256 if (Argument *Arg = dyn_cast<Argument>(Ptr)) { 257 // Insert at the functon entry if Ptr is an argument. 258 InsertPt = Arg->getParent()->getEntryBlock().begin(); 259 } else { 260 // Insert right after Ptr if Ptr is an instruction. 261 InsertPt = ++cast<Instruction>(Ptr)->getIterator(); 262 assert(InsertPt != InsertPt->getParent()->end() && 263 "We don't call this function with Ptr being a terminator."); 264 } 265 266 Instruction *PtrInGlobal = new AddrSpaceCastInst( 267 Ptr, PointerType::get(Ptr->getType()->getPointerElementType(), 268 ADDRESS_SPACE_GLOBAL), 269 Ptr->getName(), &*InsertPt); 270 Value *PtrInGeneric = new AddrSpaceCastInst(PtrInGlobal, Ptr->getType(), 271 Ptr->getName(), &*InsertPt); 272 // Replace with PtrInGeneric all uses of Ptr except PtrInGlobal. 273 Ptr->replaceAllUsesWith(PtrInGeneric); 274 PtrInGlobal->setOperand(0, Ptr); 275 } 276 277 // ============================================================================= 278 // Main function for this pass. 279 // ============================================================================= 280 bool NVPTXLowerArgs::runOnKernelFunction(Function &F) { 281 if (TM && TM->getDrvInterface() == NVPTX::CUDA) { 282 // Mark pointers in byval structs as global. 283 for (auto &B : F) { 284 for (auto &I : B) { 285 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 286 if (LI->getType()->isPointerTy()) { 287 Value *UO = getUnderlyingObject(LI->getPointerOperand()); 288 if (Argument *Arg = dyn_cast<Argument>(UO)) { 289 if (Arg->hasByValAttr()) { 290 // LI is a load from a pointer within a byval kernel parameter. 291 markPointerAsGlobal(LI); 292 } 293 } 294 } 295 } 296 } 297 } 298 } 299 300 for (Argument &Arg : F.args()) { 301 if (Arg.getType()->isPointerTy()) { 302 if (Arg.hasByValAttr()) 303 handleByValParam(&Arg); 304 else if (TM && TM->getDrvInterface() == NVPTX::CUDA) 305 markPointerAsGlobal(&Arg); 306 } 307 } 308 return true; 309 } 310 311 // Device functions only need to copy byval args into local memory. 312 bool NVPTXLowerArgs::runOnDeviceFunction(Function &F) { 313 for (Argument &Arg : F.args()) 314 if (Arg.getType()->isPointerTy() && Arg.hasByValAttr()) 315 handleByValParam(&Arg); 316 return true; 317 } 318 319 bool NVPTXLowerArgs::runOnFunction(Function &F) { 320 return isKernelFunction(F) ? runOnKernelFunction(F) : runOnDeviceFunction(F); 321 } 322 323 FunctionPass * 324 llvm::createNVPTXLowerArgsPass(const NVPTXTargetMachine *TM) { 325 return new NVPTXLowerArgs(TM); 326 } 327