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 #define DEBUG_TYPE "nvptx-lower-args" 103 104 using namespace llvm; 105 106 namespace llvm { 107 void initializeNVPTXLowerArgsPass(PassRegistry &); 108 } 109 110 namespace { 111 class NVPTXLowerArgs : public FunctionPass { 112 bool runOnFunction(Function &F) override; 113 114 bool runOnKernelFunction(Function &F); 115 bool runOnDeviceFunction(Function &F); 116 117 // handle byval parameters 118 void handleByValParam(Argument *Arg); 119 // Knowing Ptr must point to the global address space, this function 120 // addrspacecasts Ptr to global and then back to generic. This allows 121 // NVPTXInferAddressSpaces to fold the global-to-generic cast into 122 // loads/stores that appear later. 123 void markPointerAsGlobal(Value *Ptr); 124 125 public: 126 static char ID; // Pass identification, replacement for typeid 127 NVPTXLowerArgs(const NVPTXTargetMachine *TM = nullptr) 128 : FunctionPass(ID), TM(TM) {} 129 StringRef getPassName() const override { 130 return "Lower pointer arguments of CUDA kernels"; 131 } 132 133 private: 134 const NVPTXTargetMachine *TM; 135 }; 136 } // namespace 137 138 char NVPTXLowerArgs::ID = 1; 139 140 INITIALIZE_PASS(NVPTXLowerArgs, "nvptx-lower-args", 141 "Lower arguments (NVPTX)", false, false) 142 143 // ============================================================================= 144 // If the function had a byval struct ptr arg, say foo(%struct.x* byval %d), 145 // and we can't guarantee that the only accesses are loads, 146 // then add the following instructions to the first basic block: 147 // 148 // %temp = alloca %struct.x, align 8 149 // %tempd = addrspacecast %struct.x* %d to %struct.x addrspace(101)* 150 // %tv = load %struct.x addrspace(101)* %tempd 151 // store %struct.x %tv, %struct.x* %temp, align 8 152 // 153 // The above code allocates some space in the stack and copies the incoming 154 // struct from param space to local space. 155 // Then replace all occurrences of %d by %temp. 156 // 157 // In case we know that all users are GEPs or Loads, replace them with the same 158 // ones in parameter AS, so we can access them using ld.param. 159 // ============================================================================= 160 161 // Replaces the \p OldUser instruction with the same in parameter AS. 162 // Only Load and GEP are supported. 163 static void convertToParamAS(Value *OldUser, Value *Param) { 164 Instruction *I = dyn_cast<Instruction>(OldUser); 165 assert(I && "OldUser must be an instruction"); 166 struct IP { 167 Instruction *OldInstruction; 168 Value *NewParam; 169 }; 170 SmallVector<IP> ItemsToConvert = {{I, Param}}; 171 SmallVector<Instruction *> InstructionsToDelete; 172 173 auto CloneInstInParamAS = [](const IP &I) -> Value * { 174 if (auto *LI = dyn_cast<LoadInst>(I.OldInstruction)) { 175 LI->setOperand(0, I.NewParam); 176 return LI; 177 } 178 if (auto *GEP = dyn_cast<GetElementPtrInst>(I.OldInstruction)) { 179 SmallVector<Value *, 4> Indices(GEP->indices()); 180 auto *NewGEP = GetElementPtrInst::Create(nullptr, I.NewParam, Indices, 181 GEP->getName(), GEP); 182 NewGEP->setIsInBounds(GEP->isInBounds()); 183 return NewGEP; 184 } 185 if (auto *BC = dyn_cast<BitCastInst>(I.OldInstruction)) { 186 auto *NewBCType = BC->getType()->getPointerElementType()->getPointerTo( 187 ADDRESS_SPACE_PARAM); 188 return BitCastInst::Create(BC->getOpcode(), I.NewParam, NewBCType, 189 BC->getName(), BC); 190 } 191 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I.OldInstruction)) { 192 assert(ASC->getDestAddressSpace() == ADDRESS_SPACE_PARAM); 193 // Just pass through the argument, the old ASC is no longer needed. 194 return I.NewParam; 195 } 196 llvm_unreachable("Unsupported instruction"); 197 }; 198 199 while (!ItemsToConvert.empty()) { 200 IP I = ItemsToConvert.pop_back_val(); 201 Value *NewInst = CloneInstInParamAS(I); 202 203 if (NewInst && NewInst != I.OldInstruction) { 204 // We've created a new instruction. Queue users of the old instruction to 205 // be converted and the instruction itself to be deleted. We can't delete 206 // the old instruction yet, because it's still in use by a load somewhere. 207 llvm::for_each( 208 I.OldInstruction->users(), [NewInst, &ItemsToConvert](Value *V) { 209 ItemsToConvert.push_back({cast<Instruction>(V), NewInst}); 210 }); 211 212 InstructionsToDelete.push_back(I.OldInstruction); 213 } 214 } 215 216 // Now we know that all argument loads are using addresses in parameter space 217 // and we can finally remove the old instructions in generic AS. Instructions 218 // scheduled for removal should be processed in reverse order so the ones 219 // closest to the load are deleted first. Otherwise they may still be in use. 220 // E.g if we have Value = Load(BitCast(GEP(arg))), InstructionsToDelete will 221 // have {GEP,BitCast}. GEP can't be deleted first, because it's still used by 222 // the BitCast. 223 llvm::for_each(reverse(InstructionsToDelete), 224 [](Instruction *I) { I->eraseFromParent(); }); 225 } 226 227 void NVPTXLowerArgs::handleByValParam(Argument *Arg) { 228 Function *Func = Arg->getParent(); 229 Instruction *FirstInst = &(Func->getEntryBlock().front()); 230 PointerType *PType = dyn_cast<PointerType>(Arg->getType()); 231 232 assert(PType && "Expecting pointer type in handleByValParam"); 233 234 Type *StructType = PType->getElementType(); 235 236 auto IsALoadChain = [&](Value *Start) { 237 SmallVector<Value *, 16> ValuesToCheck = {Start}; 238 auto IsALoadChainInstr = [](Value *V) -> bool { 239 if (isa<GetElementPtrInst>(V) || isa<BitCastInst>(V) || isa<LoadInst>(V)) 240 return true; 241 // ASC to param space are OK, too -- we'll just strip them. 242 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(V)) { 243 if (ASC->getDestAddressSpace() == ADDRESS_SPACE_PARAM) 244 return true; 245 } 246 return false; 247 }; 248 249 while (!ValuesToCheck.empty()) { 250 Value *V = ValuesToCheck.pop_back_val(); 251 if (!IsALoadChainInstr(V)) { 252 LLVM_DEBUG(dbgs() << "Need a copy of " << *Arg << " because of " << *V 253 << "\n"); 254 (void)Arg; 255 return false; 256 } 257 if (!isa<LoadInst>(V)) 258 llvm::append_range(ValuesToCheck, V->users()); 259 } 260 return true; 261 }; 262 263 if (llvm::all_of(Arg->users(), IsALoadChain)) { 264 // Convert all loads and intermediate operations to use parameter AS and 265 // skip creation of a local copy of the argument. 266 SmallVector<User *, 16> UsersToUpdate(Arg->users()); 267 Value *ArgInParamAS = new AddrSpaceCastInst( 268 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 269 FirstInst); 270 llvm::for_each(UsersToUpdate, [ArgInParamAS](Value *V) { 271 convertToParamAS(V, ArgInParamAS); 272 }); 273 LLVM_DEBUG(dbgs() << "No need to copy " << *Arg << "\n"); 274 return; 275 } 276 277 // Otherwise we have to create a temporary copy. 278 const DataLayout &DL = Func->getParent()->getDataLayout(); 279 unsigned AS = DL.getAllocaAddrSpace(); 280 AllocaInst *AllocA = new AllocaInst(StructType, AS, Arg->getName(), FirstInst); 281 // Set the alignment to alignment of the byval parameter. This is because, 282 // later load/stores assume that alignment, and we are going to replace 283 // the use of the byval parameter with this alloca instruction. 284 AllocA->setAlignment(Func->getParamAlign(Arg->getArgNo()) 285 .getValueOr(DL.getPrefTypeAlign(StructType))); 286 Arg->replaceAllUsesWith(AllocA); 287 288 Value *ArgInParam = new AddrSpaceCastInst( 289 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 290 FirstInst); 291 // Be sure to propagate alignment to this load; LLVM doesn't know that NVPTX 292 // addrspacecast preserves alignment. Since params are constant, this load is 293 // definitely not volatile. 294 LoadInst *LI = 295 new LoadInst(StructType, ArgInParam, Arg->getName(), 296 /*isVolatile=*/false, AllocA->getAlign(), FirstInst); 297 new StoreInst(LI, AllocA, FirstInst); 298 } 299 300 void NVPTXLowerArgs::markPointerAsGlobal(Value *Ptr) { 301 if (Ptr->getType()->getPointerAddressSpace() == ADDRESS_SPACE_GLOBAL) 302 return; 303 304 // Deciding where to emit the addrspacecast pair. 305 BasicBlock::iterator InsertPt; 306 if (Argument *Arg = dyn_cast<Argument>(Ptr)) { 307 // Insert at the functon entry if Ptr is an argument. 308 InsertPt = Arg->getParent()->getEntryBlock().begin(); 309 } else { 310 // Insert right after Ptr if Ptr is an instruction. 311 InsertPt = ++cast<Instruction>(Ptr)->getIterator(); 312 assert(InsertPt != InsertPt->getParent()->end() && 313 "We don't call this function with Ptr being a terminator."); 314 } 315 316 Instruction *PtrInGlobal = new AddrSpaceCastInst( 317 Ptr, PointerType::get(Ptr->getType()->getPointerElementType(), 318 ADDRESS_SPACE_GLOBAL), 319 Ptr->getName(), &*InsertPt); 320 Value *PtrInGeneric = new AddrSpaceCastInst(PtrInGlobal, Ptr->getType(), 321 Ptr->getName(), &*InsertPt); 322 // Replace with PtrInGeneric all uses of Ptr except PtrInGlobal. 323 Ptr->replaceAllUsesWith(PtrInGeneric); 324 PtrInGlobal->setOperand(0, Ptr); 325 } 326 327 // ============================================================================= 328 // Main function for this pass. 329 // ============================================================================= 330 bool NVPTXLowerArgs::runOnKernelFunction(Function &F) { 331 if (TM && TM->getDrvInterface() == NVPTX::CUDA) { 332 // Mark pointers in byval structs as global. 333 for (auto &B : F) { 334 for (auto &I : B) { 335 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 336 if (LI->getType()->isPointerTy()) { 337 Value *UO = getUnderlyingObject(LI->getPointerOperand()); 338 if (Argument *Arg = dyn_cast<Argument>(UO)) { 339 if (Arg->hasByValAttr()) { 340 // LI is a load from a pointer within a byval kernel parameter. 341 markPointerAsGlobal(LI); 342 } 343 } 344 } 345 } 346 } 347 } 348 } 349 350 LLVM_DEBUG(dbgs() << "Lowering kernel args of " << F.getName() << "\n"); 351 for (Argument &Arg : F.args()) { 352 if (Arg.getType()->isPointerTy()) { 353 if (Arg.hasByValAttr()) 354 handleByValParam(&Arg); 355 else if (TM && TM->getDrvInterface() == NVPTX::CUDA) 356 markPointerAsGlobal(&Arg); 357 } 358 } 359 return true; 360 } 361 362 // Device functions only need to copy byval args into local memory. 363 bool NVPTXLowerArgs::runOnDeviceFunction(Function &F) { 364 LLVM_DEBUG(dbgs() << "Lowering function args of " << F.getName() << "\n"); 365 for (Argument &Arg : F.args()) 366 if (Arg.getType()->isPointerTy() && Arg.hasByValAttr()) 367 handleByValParam(&Arg); 368 return true; 369 } 370 371 bool NVPTXLowerArgs::runOnFunction(Function &F) { 372 return isKernelFunction(F) ? runOnKernelFunction(F) : runOnDeviceFunction(F); 373 } 374 375 FunctionPass * 376 llvm::createNVPTXLowerArgsPass(const NVPTXTargetMachine *TM) { 377 return new NVPTXLowerArgs(TM); 378 } 379