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 "MCTargetDesc/NVPTXBaseInfo.h" 92 #include "NVPTX.h" 93 #include "NVPTXTargetMachine.h" 94 #include "NVPTXUtilities.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 #include <numeric> 102 #include <queue> 103 104 #define DEBUG_TYPE "nvptx-lower-args" 105 106 using namespace llvm; 107 108 namespace llvm { 109 void initializeNVPTXLowerArgsPass(PassRegistry &); 110 } 111 112 namespace { 113 class NVPTXLowerArgs : public FunctionPass { 114 bool runOnFunction(Function &F) override; 115 116 bool runOnKernelFunction(Function &F); 117 bool runOnDeviceFunction(Function &F); 118 119 // handle byval parameters 120 void handleByValParam(Argument *Arg); 121 // Knowing Ptr must point to the global address space, this function 122 // addrspacecasts Ptr to global and then back to generic. This allows 123 // NVPTXInferAddressSpaces to fold the global-to-generic cast into 124 // loads/stores that appear later. 125 void markPointerAsGlobal(Value *Ptr); 126 127 public: 128 static char ID; // Pass identification, replacement for typeid 129 NVPTXLowerArgs(const NVPTXTargetMachine *TM = nullptr) 130 : FunctionPass(ID), TM(TM) {} 131 StringRef getPassName() const override { 132 return "Lower pointer arguments of CUDA kernels"; 133 } 134 135 private: 136 const NVPTXTargetMachine *TM; 137 }; 138 } // namespace 139 140 char NVPTXLowerArgs::ID = 1; 141 142 INITIALIZE_PASS(NVPTXLowerArgs, "nvptx-lower-args", 143 "Lower arguments (NVPTX)", false, false) 144 145 // ============================================================================= 146 // If the function had a byval struct ptr arg, say foo(%struct.x* byval %d), 147 // and we can't guarantee that the only accesses are loads, 148 // then add the following instructions to the first basic block: 149 // 150 // %temp = alloca %struct.x, align 8 151 // %tempd = addrspacecast %struct.x* %d to %struct.x addrspace(101)* 152 // %tv = load %struct.x addrspace(101)* %tempd 153 // store %struct.x %tv, %struct.x* %temp, align 8 154 // 155 // The above code allocates some space in the stack and copies the incoming 156 // struct from param space to local space. 157 // Then replace all occurrences of %d by %temp. 158 // 159 // In case we know that all users are GEPs or Loads, replace them with the same 160 // ones in parameter AS, so we can access them using ld.param. 161 // ============================================================================= 162 163 // Replaces the \p OldUser instruction with the same in parameter AS. 164 // Only Load and GEP are supported. 165 static void convertToParamAS(Value *OldUser, Value *Param) { 166 Instruction *I = dyn_cast<Instruction>(OldUser); 167 assert(I && "OldUser must be an instruction"); 168 struct IP { 169 Instruction *OldInstruction; 170 Value *NewParam; 171 }; 172 SmallVector<IP> ItemsToConvert = {{I, Param}}; 173 SmallVector<Instruction *> InstructionsToDelete; 174 175 auto CloneInstInParamAS = [](const IP &I) -> Value * { 176 if (auto *LI = dyn_cast<LoadInst>(I.OldInstruction)) { 177 LI->setOperand(0, I.NewParam); 178 return LI; 179 } 180 if (auto *GEP = dyn_cast<GetElementPtrInst>(I.OldInstruction)) { 181 SmallVector<Value *, 4> Indices(GEP->indices()); 182 auto *NewGEP = GetElementPtrInst::Create(GEP->getSourceElementType(), 183 I.NewParam, Indices, 184 GEP->getName(), GEP); 185 NewGEP->setIsInBounds(GEP->isInBounds()); 186 return NewGEP; 187 } 188 if (auto *BC = dyn_cast<BitCastInst>(I.OldInstruction)) { 189 auto *NewBCType = PointerType::getWithSamePointeeType( 190 cast<PointerType>(BC->getType()), ADDRESS_SPACE_PARAM); 191 return BitCastInst::Create(BC->getOpcode(), I.NewParam, NewBCType, 192 BC->getName(), BC); 193 } 194 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I.OldInstruction)) { 195 assert(ASC->getDestAddressSpace() == ADDRESS_SPACE_PARAM); 196 (void)ASC; 197 // Just pass through the argument, the old ASC is no longer needed. 198 return I.NewParam; 199 } 200 llvm_unreachable("Unsupported instruction"); 201 }; 202 203 while (!ItemsToConvert.empty()) { 204 IP I = ItemsToConvert.pop_back_val(); 205 Value *NewInst = CloneInstInParamAS(I); 206 207 if (NewInst && NewInst != I.OldInstruction) { 208 // We've created a new instruction. Queue users of the old instruction to 209 // be converted and the instruction itself to be deleted. We can't delete 210 // the old instruction yet, because it's still in use by a load somewhere. 211 for (Value *V : I.OldInstruction->users()) 212 ItemsToConvert.push_back({cast<Instruction>(V), NewInst}); 213 214 InstructionsToDelete.push_back(I.OldInstruction); 215 } 216 } 217 218 // Now we know that all argument loads are using addresses in parameter space 219 // and we can finally remove the old instructions in generic AS. Instructions 220 // scheduled for removal should be processed in reverse order so the ones 221 // closest to the load are deleted first. Otherwise they may still be in use. 222 // E.g if we have Value = Load(BitCast(GEP(arg))), InstructionsToDelete will 223 // have {GEP,BitCast}. GEP can't be deleted first, because it's still used by 224 // the BitCast. 225 for (Instruction *I : llvm::reverse(InstructionsToDelete)) 226 I->eraseFromParent(); 227 } 228 229 // Adjust alignment of arguments passed byval in .param address space. We can 230 // increase alignment of such arguments in a way that ensures that we can 231 // effectively vectorize their loads. We should also traverse all loads from 232 // byval pointer and adjust their alignment, if those were using known offset. 233 // Such alignment changes must be conformed with parameter store and load in 234 // NVPTXTargetLowering::LowerCall. 235 static void adjustByValArgAlignment(Argument *Arg, Value *ArgInParamAS, 236 const NVPTXTargetLowering *TLI) { 237 Function *Func = Arg->getParent(); 238 Type *StructType = Arg->getParamByValType(); 239 const DataLayout DL(Func->getParent()); 240 241 uint64_t NewArgAlign = 242 TLI->getFunctionParamOptimizedAlign(Func, StructType, DL).value(); 243 uint64_t CurArgAlign = 244 Arg->getAttribute(Attribute::Alignment).getValueAsInt(); 245 246 if (CurArgAlign >= NewArgAlign) 247 return; 248 249 LLVM_DEBUG(dbgs() << "Try to use alignment " << NewArgAlign << " instead of " 250 << CurArgAlign << " for " << *Arg << '\n'); 251 252 auto NewAlignAttr = 253 Attribute::get(Func->getContext(), Attribute::Alignment, NewArgAlign); 254 Arg->removeAttr(Attribute::Alignment); 255 Arg->addAttr(NewAlignAttr); 256 257 struct Load { 258 LoadInst *Inst; 259 uint64_t Offset; 260 }; 261 262 struct LoadContext { 263 Value *InitialVal; 264 uint64_t Offset; 265 }; 266 267 SmallVector<Load> Loads; 268 std::queue<LoadContext> Worklist; 269 Worklist.push({ArgInParamAS, 0}); 270 271 while (!Worklist.empty()) { 272 LoadContext Ctx = Worklist.front(); 273 Worklist.pop(); 274 275 for (User *CurUser : Ctx.InitialVal->users()) { 276 if (auto *I = dyn_cast<LoadInst>(CurUser)) { 277 Loads.push_back({I, Ctx.Offset}); 278 continue; 279 } 280 281 if (auto *I = dyn_cast<BitCastInst>(CurUser)) { 282 Worklist.push({I, Ctx.Offset}); 283 continue; 284 } 285 286 if (auto *I = dyn_cast<GetElementPtrInst>(CurUser)) { 287 APInt OffsetAccumulated = 288 APInt::getZero(DL.getIndexSizeInBits(ADDRESS_SPACE_PARAM)); 289 290 if (!I->accumulateConstantOffset(DL, OffsetAccumulated)) 291 continue; 292 293 uint64_t OffsetLimit = -1; 294 uint64_t Offset = OffsetAccumulated.getLimitedValue(OffsetLimit); 295 assert(Offset != OffsetLimit && "Expect Offset less than UINT64_MAX"); 296 297 Worklist.push({I, Ctx.Offset + Offset}); 298 continue; 299 } 300 301 llvm_unreachable("All users must be one of: load, " 302 "bitcast, getelementptr."); 303 } 304 } 305 306 for (Load &CurLoad : Loads) { 307 Align NewLoadAlign(std::gcd(NewArgAlign, CurLoad.Offset)); 308 Align CurLoadAlign(CurLoad.Inst->getAlign()); 309 CurLoad.Inst->setAlignment(std::max(NewLoadAlign, CurLoadAlign)); 310 } 311 } 312 313 void NVPTXLowerArgs::handleByValParam(Argument *Arg) { 314 Function *Func = Arg->getParent(); 315 Instruction *FirstInst = &(Func->getEntryBlock().front()); 316 Type *StructType = Arg->getParamByValType(); 317 assert(StructType && "Missing byval type"); 318 319 auto IsALoadChain = [&](Value *Start) { 320 SmallVector<Value *, 16> ValuesToCheck = {Start}; 321 auto IsALoadChainInstr = [](Value *V) -> bool { 322 if (isa<GetElementPtrInst>(V) || isa<BitCastInst>(V) || isa<LoadInst>(V)) 323 return true; 324 // ASC to param space are OK, too -- we'll just strip them. 325 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(V)) { 326 if (ASC->getDestAddressSpace() == ADDRESS_SPACE_PARAM) 327 return true; 328 } 329 return false; 330 }; 331 332 while (!ValuesToCheck.empty()) { 333 Value *V = ValuesToCheck.pop_back_val(); 334 if (!IsALoadChainInstr(V)) { 335 LLVM_DEBUG(dbgs() << "Need a copy of " << *Arg << " because of " << *V 336 << "\n"); 337 (void)Arg; 338 return false; 339 } 340 if (!isa<LoadInst>(V)) 341 llvm::append_range(ValuesToCheck, V->users()); 342 } 343 return true; 344 }; 345 346 if (llvm::all_of(Arg->users(), IsALoadChain)) { 347 // Convert all loads and intermediate operations to use parameter AS and 348 // skip creation of a local copy of the argument. 349 SmallVector<User *, 16> UsersToUpdate(Arg->users()); 350 Value *ArgInParamAS = new AddrSpaceCastInst( 351 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 352 FirstInst); 353 for (Value *V : UsersToUpdate) 354 convertToParamAS(V, ArgInParamAS); 355 LLVM_DEBUG(dbgs() << "No need to copy " << *Arg << "\n"); 356 357 // Further optimizations require target lowering info. 358 if (!TM) 359 return; 360 361 const auto *TLI = 362 cast<NVPTXTargetLowering>(TM->getSubtargetImpl()->getTargetLowering()); 363 364 adjustByValArgAlignment(Arg, ArgInParamAS, TLI); 365 366 return; 367 } 368 369 // Otherwise we have to create a temporary copy. 370 const DataLayout &DL = Func->getParent()->getDataLayout(); 371 unsigned AS = DL.getAllocaAddrSpace(); 372 AllocaInst *AllocA = new AllocaInst(StructType, AS, Arg->getName(), FirstInst); 373 // Set the alignment to alignment of the byval parameter. This is because, 374 // later load/stores assume that alignment, and we are going to replace 375 // the use of the byval parameter with this alloca instruction. 376 AllocA->setAlignment(Func->getParamAlign(Arg->getArgNo()) 377 .value_or(DL.getPrefTypeAlign(StructType))); 378 Arg->replaceAllUsesWith(AllocA); 379 380 Value *ArgInParam = new AddrSpaceCastInst( 381 Arg, PointerType::get(StructType, ADDRESS_SPACE_PARAM), Arg->getName(), 382 FirstInst); 383 // Be sure to propagate alignment to this load; LLVM doesn't know that NVPTX 384 // addrspacecast preserves alignment. Since params are constant, this load is 385 // definitely not volatile. 386 LoadInst *LI = 387 new LoadInst(StructType, ArgInParam, Arg->getName(), 388 /*isVolatile=*/false, AllocA->getAlign(), FirstInst); 389 new StoreInst(LI, AllocA, FirstInst); 390 } 391 392 void NVPTXLowerArgs::markPointerAsGlobal(Value *Ptr) { 393 if (Ptr->getType()->getPointerAddressSpace() == ADDRESS_SPACE_GLOBAL) 394 return; 395 396 // Deciding where to emit the addrspacecast pair. 397 BasicBlock::iterator InsertPt; 398 if (Argument *Arg = dyn_cast<Argument>(Ptr)) { 399 // Insert at the functon entry if Ptr is an argument. 400 InsertPt = Arg->getParent()->getEntryBlock().begin(); 401 } else { 402 // Insert right after Ptr if Ptr is an instruction. 403 InsertPt = ++cast<Instruction>(Ptr)->getIterator(); 404 assert(InsertPt != InsertPt->getParent()->end() && 405 "We don't call this function with Ptr being a terminator."); 406 } 407 408 Instruction *PtrInGlobal = new AddrSpaceCastInst( 409 Ptr, 410 PointerType::getWithSamePointeeType(cast<PointerType>(Ptr->getType()), 411 ADDRESS_SPACE_GLOBAL), 412 Ptr->getName(), &*InsertPt); 413 Value *PtrInGeneric = new AddrSpaceCastInst(PtrInGlobal, Ptr->getType(), 414 Ptr->getName(), &*InsertPt); 415 // Replace with PtrInGeneric all uses of Ptr except PtrInGlobal. 416 Ptr->replaceAllUsesWith(PtrInGeneric); 417 PtrInGlobal->setOperand(0, Ptr); 418 } 419 420 // ============================================================================= 421 // Main function for this pass. 422 // ============================================================================= 423 bool NVPTXLowerArgs::runOnKernelFunction(Function &F) { 424 if (TM && TM->getDrvInterface() == NVPTX::CUDA) { 425 // Mark pointers in byval structs as global. 426 for (auto &B : F) { 427 for (auto &I : B) { 428 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 429 if (LI->getType()->isPointerTy()) { 430 Value *UO = getUnderlyingObject(LI->getPointerOperand()); 431 if (Argument *Arg = dyn_cast<Argument>(UO)) { 432 if (Arg->hasByValAttr()) { 433 // LI is a load from a pointer within a byval kernel parameter. 434 markPointerAsGlobal(LI); 435 } 436 } 437 } 438 } 439 } 440 } 441 } 442 443 LLVM_DEBUG(dbgs() << "Lowering kernel args of " << F.getName() << "\n"); 444 for (Argument &Arg : F.args()) { 445 if (Arg.getType()->isPointerTy()) { 446 if (Arg.hasByValAttr()) 447 handleByValParam(&Arg); 448 else if (TM && TM->getDrvInterface() == NVPTX::CUDA) 449 markPointerAsGlobal(&Arg); 450 } 451 } 452 return true; 453 } 454 455 // Device functions only need to copy byval args into local memory. 456 bool NVPTXLowerArgs::runOnDeviceFunction(Function &F) { 457 LLVM_DEBUG(dbgs() << "Lowering function args of " << F.getName() << "\n"); 458 for (Argument &Arg : F.args()) 459 if (Arg.getType()->isPointerTy() && Arg.hasByValAttr()) 460 handleByValParam(&Arg); 461 return true; 462 } 463 464 bool NVPTXLowerArgs::runOnFunction(Function &F) { 465 return isKernelFunction(F) ? runOnKernelFunction(F) : runOnDeviceFunction(F); 466 } 467 468 FunctionPass * 469 llvm::createNVPTXLowerArgsPass(const NVPTXTargetMachine *TM) { 470 return new NVPTXLowerArgs(TM); 471 } 472