1 //===-- NVPTXInferAddressSpace.cpp - ---------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // CUDA C/C++ includes memory space designation as variable type qualifers (such 11 // as __global__ and __shared__). Knowing the space of a memory access allows 12 // CUDA compilers to emit faster PTX loads and stores. For example, a load from 13 // shared memory can be translated to `ld.shared` which is roughly 10% faster 14 // than a generic `ld` on an NVIDIA Tesla K40c. 15 // 16 // Unfortunately, type qualifiers only apply to variable declarations, so CUDA 17 // compilers must infer the memory space of an address expression from 18 // type-qualified variables. 19 // 20 // LLVM IR uses non-zero (so-called) specific address spaces to represent memory 21 // spaces (e.g. addrspace(3) means shared memory). The Clang frontend 22 // places only type-qualified variables in specific address spaces, and then 23 // conservatively `addrspacecast`s each type-qualified variable to addrspace(0) 24 // (so-called the generic address space) for other instructions to use. 25 // 26 // For example, the Clang translates the following CUDA code 27 // __shared__ float a[10]; 28 // float v = a[i]; 29 // to 30 // %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]* 31 // %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i 32 // %v = load float, float* %1 ; emits ld.f32 33 // @a is in addrspace(3) since it's type-qualified, but its use from %1 is 34 // redirected to %0 (the generic version of @a). 35 // 36 // The optimization implemented in this file propagates specific address spaces 37 // from type-qualified variable declarations to its users. For example, it 38 // optimizes the above IR to 39 // %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i 40 // %v = load float addrspace(3)* %1 ; emits ld.shared.f32 41 // propagating the addrspace(3) from @a to %1. As the result, the NVPTX 42 // codegen is able to emit ld.shared.f32 for %v. 43 // 44 // Address space inference works in two steps. First, it uses a data-flow 45 // analysis to infer as many generic pointers as possible to point to only one 46 // specific address space. In the above example, it can prove that %1 only 47 // points to addrspace(3). This algorithm was published in 48 // CUDA: Compiling and optimizing for a GPU platform 49 // Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang 50 // ICCS 2012 51 // 52 // Then, address space inference replaces all refinable generic pointers with 53 // equivalent specific pointers. 54 // 55 // The major challenge of implementing this optimization is handling PHINodes, 56 // which may create loops in the data flow graph. This brings two complications. 57 // 58 // First, the data flow analysis in Step 1 needs to be circular. For example, 59 // %generic.input = addrspacecast float addrspace(3)* %input to float* 60 // loop: 61 // %y = phi [ %generic.input, %y2 ] 62 // %y2 = getelementptr %y, 1 63 // %v = load %y2 64 // br ..., label %loop, ... 65 // proving %y specific requires proving both %generic.input and %y2 specific, 66 // but proving %y2 specific circles back to %y. To address this complication, 67 // the data flow analysis operates on a lattice: 68 // uninitialized > specific address spaces > generic. 69 // All address expressions (our implementation only considers phi, bitcast, 70 // addrspacecast, and getelementptr) start with the uninitialized address space. 71 // The monotone transfer function moves the address space of a pointer down a 72 // lattice path from uninitialized to specific and then to generic. A join 73 // operation of two different specific address spaces pushes the expression down 74 // to the generic address space. The analysis completes once it reaches a fixed 75 // point. 76 // 77 // Second, IR rewriting in Step 2 also needs to be circular. For example, 78 // converting %y to addrspace(3) requires the compiler to know the converted 79 // %y2, but converting %y2 needs the converted %y. To address this complication, 80 // we break these cycles using "undef" placeholders. When converting an 81 // instruction `I` to a new address space, if its operand `Op` is not converted 82 // yet, we let `I` temporarily use `undef` and fix all the uses of undef later. 83 // For instance, our algorithm first converts %y to 84 // %y' = phi float addrspace(3)* [ %input, undef ] 85 // Then, it converts %y2 to 86 // %y2' = getelementptr %y', 1 87 // Finally, it fixes the undef in %y' so that 88 // %y' = phi float addrspace(3)* [ %input, %y2' ] 89 // 90 //===----------------------------------------------------------------------===// 91 92 #include "llvm/Transforms/Scalar.h" 93 #include "llvm/ADT/DenseSet.h" 94 #include "llvm/ADT/Optional.h" 95 #include "llvm/ADT/SetVector.h" 96 #include "llvm/Analysis/TargetTransformInfo.h" 97 #include "llvm/IR/Function.h" 98 #include "llvm/IR/InstIterator.h" 99 #include "llvm/IR/Instructions.h" 100 #include "llvm/IR/Operator.h" 101 #include "llvm/Support/Debug.h" 102 #include "llvm/Support/raw_ostream.h" 103 #include "llvm/Transforms/Utils/Local.h" 104 #include "llvm/Transforms/Utils/ValueMapper.h" 105 106 #define DEBUG_TYPE "infer-address-spaces" 107 108 using namespace llvm; 109 110 namespace { 111 static const unsigned UninitializedAddressSpace = ~0u; 112 113 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>; 114 115 /// \brief InferAddressSpaces 116 class InferAddressSpaces: public FunctionPass { 117 /// Target specific address space which uses of should be replaced if 118 /// possible. 119 unsigned FlatAddrSpace; 120 121 public: 122 static char ID; 123 124 InferAddressSpaces() : FunctionPass(ID) {} 125 126 void getAnalysisUsage(AnalysisUsage &AU) const override { 127 AU.setPreservesCFG(); 128 AU.addRequired<TargetTransformInfoWrapperPass>(); 129 } 130 131 bool runOnFunction(Function &F) override; 132 133 private: 134 // Returns the new address space of V if updated; otherwise, returns None. 135 Optional<unsigned> 136 updateAddressSpace(const Value &V, 137 const ValueToAddrSpaceMapTy &InferredAddrSpace) const; 138 139 // Tries to infer the specific address space of each address expression in 140 // Postorder. 141 void inferAddressSpaces(const std::vector<Value *> &Postorder, 142 ValueToAddrSpaceMapTy *InferredAddrSpace) const; 143 144 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const; 145 146 // Changes the flat address expressions in function F to point to specific 147 // address spaces if InferredAddrSpace says so. Postorder is the postorder of 148 // all flat expressions in the use-def graph of function F. 149 bool 150 rewriteWithNewAddressSpaces(const std::vector<Value *> &Postorder, 151 const ValueToAddrSpaceMapTy &InferredAddrSpace, 152 Function *F) const; 153 154 void appendsFlatAddressExpressionToPostorderStack( 155 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack, 156 DenseSet<Value *> *Visited) const; 157 158 bool rewriteIntrinsicOperands(IntrinsicInst *II, 159 Value *OldV, Value *NewV) const; 160 void collectRewritableIntrinsicOperands( 161 IntrinsicInst *II, 162 std::vector<std::pair<Value *, bool>> *PostorderStack, 163 DenseSet<Value *> *Visited) const; 164 165 std::vector<Value *> collectFlatAddressExpressions(Function &F) const; 166 167 Value *cloneValueWithNewAddressSpace( 168 Value *V, unsigned NewAddrSpace, 169 const ValueToValueMapTy &ValueWithNewAddrSpace, 170 SmallVectorImpl<const Use *> *UndefUsesToFix) const; 171 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const; 172 }; 173 } // end anonymous namespace 174 175 char InferAddressSpaces::ID = 0; 176 177 namespace llvm { 178 void initializeInferAddressSpacesPass(PassRegistry &); 179 } 180 181 INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 182 false, false) 183 184 // Returns true if V is an address expression. 185 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and 186 // getelementptr operators. 187 static bool isAddressExpression(const Value &V) { 188 if (!isa<Operator>(V)) 189 return false; 190 191 switch (cast<Operator>(V).getOpcode()) { 192 case Instruction::PHI: 193 case Instruction::BitCast: 194 case Instruction::AddrSpaceCast: 195 case Instruction::GetElementPtr: 196 return true; 197 default: 198 return false; 199 } 200 } 201 202 // Returns the pointer operands of V. 203 // 204 // Precondition: V is an address expression. 205 static SmallVector<Value *, 2> getPointerOperands(const Value &V) { 206 assert(isAddressExpression(V)); 207 const Operator& Op = cast<Operator>(V); 208 switch (Op.getOpcode()) { 209 case Instruction::PHI: { 210 auto IncomingValues = cast<PHINode>(Op).incoming_values(); 211 return SmallVector<Value *, 2>(IncomingValues.begin(), 212 IncomingValues.end()); 213 } 214 case Instruction::BitCast: 215 case Instruction::AddrSpaceCast: 216 case Instruction::GetElementPtr: 217 return {Op.getOperand(0)}; 218 default: 219 llvm_unreachable("Unexpected instruction type."); 220 } 221 } 222 223 // TODO: Move logic to TTI? 224 bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II, 225 Value *OldV, 226 Value *NewV) const { 227 Module *M = II->getParent()->getParent()->getParent(); 228 229 switch (II->getIntrinsicID()) { 230 case Intrinsic::objectsize: 231 case Intrinsic::amdgcn_atomic_inc: 232 case Intrinsic::amdgcn_atomic_dec: { 233 Type *DestTy = II->getType(); 234 Type *SrcTy = NewV->getType(); 235 Function *NewDecl 236 = Intrinsic::getDeclaration(M, II->getIntrinsicID(), { DestTy, SrcTy }); 237 II->setArgOperand(0, NewV); 238 II->setCalledFunction(NewDecl); 239 return true; 240 } 241 default: 242 return false; 243 } 244 } 245 246 // TODO: Move logic to TTI? 247 void InferAddressSpaces::collectRewritableIntrinsicOperands( 248 IntrinsicInst *II, 249 std::vector<std::pair<Value *, bool>> *PostorderStack, 250 DenseSet<Value *> *Visited) const { 251 switch (II->getIntrinsicID()) { 252 case Intrinsic::objectsize: 253 case Intrinsic::amdgcn_atomic_inc: 254 case Intrinsic::amdgcn_atomic_dec: 255 appendsFlatAddressExpressionToPostorderStack( 256 II->getArgOperand(0), PostorderStack, Visited); 257 break; 258 default: 259 break; 260 } 261 } 262 263 // Returns all flat address expressions in function F. The elements are 264 // If V is an unvisited flat address expression, appends V to PostorderStack 265 // and marks it as visited. 266 void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack( 267 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack, 268 DenseSet<Value *> *Visited) const { 269 assert(V->getType()->isPointerTy()); 270 if (isAddressExpression(*V) && 271 V->getType()->getPointerAddressSpace() == FlatAddrSpace) { 272 if (Visited->insert(V).second) 273 PostorderStack->push_back(std::make_pair(V, false)); 274 } 275 } 276 277 // Returns all flat address expressions in function F. The elements are ordered 278 // ordered in postorder. 279 std::vector<Value *> 280 InferAddressSpaces::collectFlatAddressExpressions(Function &F) const { 281 // This function implements a non-recursive postorder traversal of a partial 282 // use-def graph of function F. 283 std::vector<std::pair<Value*, bool>> PostorderStack; 284 // The set of visited expressions. 285 DenseSet<Value*> Visited; 286 287 auto PushPtrOperand = [&](Value *Ptr) { 288 appendsFlatAddressExpressionToPostorderStack( 289 Ptr, &PostorderStack, &Visited); 290 }; 291 292 // We only explore address expressions that are reachable from loads and 293 // stores for now because we aim at generating faster loads and stores. 294 for (Instruction &I : instructions(F)) { 295 if (auto *LI = dyn_cast<LoadInst>(&I)) 296 PushPtrOperand(LI->getPointerOperand()); 297 else if (auto *SI = dyn_cast<StoreInst>(&I)) 298 PushPtrOperand(SI->getPointerOperand()); 299 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I)) 300 PushPtrOperand(RMW->getPointerOperand()); 301 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I)) 302 PushPtrOperand(CmpX->getPointerOperand()); 303 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) { 304 // For memset/memcpy/memmove, any pointer operand can be replaced. 305 PushPtrOperand(MI->getRawDest()); 306 307 // Handle 2nd operand for memcpy/memmove. 308 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) 309 PushPtrOperand(MTI->getRawSource()); 310 } else if (auto *II = dyn_cast<IntrinsicInst>(&I)) 311 collectRewritableIntrinsicOperands(II, &PostorderStack, &Visited); 312 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) { 313 // FIXME: Handle vectors of pointers 314 if (Cmp->getOperand(0)->getType()->isPointerTy()) { 315 PushPtrOperand(Cmp->getOperand(0)); 316 PushPtrOperand(Cmp->getOperand(1)); 317 } 318 } 319 } 320 321 std::vector<Value *> Postorder; // The resultant postorder. 322 while (!PostorderStack.empty()) { 323 // If the operands of the expression on the top are already explored, 324 // adds that expression to the resultant postorder. 325 if (PostorderStack.back().second) { 326 Postorder.push_back(PostorderStack.back().first); 327 PostorderStack.pop_back(); 328 continue; 329 } 330 // Otherwise, adds its operands to the stack and explores them. 331 PostorderStack.back().second = true; 332 for (Value *PtrOperand : getPointerOperands(*PostorderStack.back().first)) { 333 appendsFlatAddressExpressionToPostorderStack( 334 PtrOperand, &PostorderStack, &Visited); 335 } 336 } 337 return Postorder; 338 } 339 340 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone 341 // of OperandUse.get() in the new address space. If the clone is not ready yet, 342 // returns an undef in the new address space as a placeholder. 343 static Value *operandWithNewAddressSpaceOrCreateUndef( 344 const Use &OperandUse, unsigned NewAddrSpace, 345 const ValueToValueMapTy &ValueWithNewAddrSpace, 346 SmallVectorImpl<const Use *> *UndefUsesToFix) { 347 Value *Operand = OperandUse.get(); 348 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) 349 return NewOperand; 350 351 UndefUsesToFix->push_back(&OperandUse); 352 return UndefValue::get( 353 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace)); 354 } 355 356 // Returns a clone of `I` with its operands converted to those specified in 357 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an 358 // operand whose address space needs to be modified might not exist in 359 // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and 360 // adds that operand use to UndefUsesToFix so that caller can fix them later. 361 // 362 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast 363 // from a pointer whose type already matches. Therefore, this function returns a 364 // Value* instead of an Instruction*. 365 static Value *cloneInstructionWithNewAddressSpace( 366 Instruction *I, unsigned NewAddrSpace, 367 const ValueToValueMapTy &ValueWithNewAddrSpace, 368 SmallVectorImpl<const Use *> *UndefUsesToFix) { 369 Type *NewPtrType = 370 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace); 371 372 if (I->getOpcode() == Instruction::AddrSpaceCast) { 373 Value *Src = I->getOperand(0); 374 // Because `I` is flat, the source address space must be specific. 375 // Therefore, the inferred address space must be the source space, according 376 // to our algorithm. 377 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 378 if (Src->getType() != NewPtrType) 379 return new BitCastInst(Src, NewPtrType); 380 return Src; 381 } 382 383 // Computes the converted pointer operands. 384 SmallVector<Value *, 4> NewPointerOperands; 385 for (const Use &OperandUse : I->operands()) { 386 if (!OperandUse.get()->getType()->isPointerTy()) 387 NewPointerOperands.push_back(nullptr); 388 else 389 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef( 390 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix)); 391 } 392 393 switch (I->getOpcode()) { 394 case Instruction::BitCast: 395 return new BitCastInst(NewPointerOperands[0], NewPtrType); 396 case Instruction::PHI: { 397 assert(I->getType()->isPointerTy()); 398 PHINode *PHI = cast<PHINode>(I); 399 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues()); 400 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) { 401 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index); 402 NewPHI->addIncoming(NewPointerOperands[OperandNo], 403 PHI->getIncomingBlock(Index)); 404 } 405 return NewPHI; 406 } 407 case Instruction::GetElementPtr: { 408 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 409 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 410 GEP->getSourceElementType(), NewPointerOperands[0], 411 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end())); 412 NewGEP->setIsInBounds(GEP->isInBounds()); 413 return NewGEP; 414 } 415 default: 416 llvm_unreachable("Unexpected opcode"); 417 } 418 } 419 420 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the 421 // constant expression `CE` with its operands replaced as specified in 422 // ValueWithNewAddrSpace. 423 static Value *cloneConstantExprWithNewAddressSpace( 424 ConstantExpr *CE, unsigned NewAddrSpace, 425 const ValueToValueMapTy &ValueWithNewAddrSpace) { 426 Type *TargetType = 427 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace); 428 429 if (CE->getOpcode() == Instruction::AddrSpaceCast) { 430 // Because CE is flat, the source address space must be specific. 431 // Therefore, the inferred address space must be the source space according 432 // to our algorithm. 433 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() == 434 NewAddrSpace); 435 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType); 436 } 437 438 // Computes the operands of the new constant expression. 439 SmallVector<Constant *, 4> NewOperands; 440 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) { 441 Constant *Operand = CE->getOperand(Index); 442 // If the address space of `Operand` needs to be modified, the new operand 443 // with the new address space should already be in ValueWithNewAddrSpace 444 // because (1) the constant expressions we consider (i.e. addrspacecast, 445 // bitcast, and getelementptr) do not incur cycles in the data flow graph 446 // and (2) this function is called on constant expressions in postorder. 447 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) { 448 NewOperands.push_back(cast<Constant>(NewOperand)); 449 } else { 450 // Otherwise, reuses the old operand. 451 NewOperands.push_back(Operand); 452 } 453 } 454 455 if (CE->getOpcode() == Instruction::GetElementPtr) { 456 // Needs to specify the source type while constructing a getelementptr 457 // constant expression. 458 return CE->getWithOperands( 459 NewOperands, TargetType, /*OnlyIfReduced=*/false, 460 NewOperands[0]->getType()->getPointerElementType()); 461 } 462 463 return CE->getWithOperands(NewOperands, TargetType); 464 } 465 466 // Returns a clone of the value `V`, with its operands replaced as specified in 467 // ValueWithNewAddrSpace. This function is called on every flat address 468 // expression whose address space needs to be modified, in postorder. 469 // 470 // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix. 471 Value *InferAddressSpaces::cloneValueWithNewAddressSpace( 472 Value *V, unsigned NewAddrSpace, 473 const ValueToValueMapTy &ValueWithNewAddrSpace, 474 SmallVectorImpl<const Use *> *UndefUsesToFix) const { 475 // All values in Postorder are flat address expressions. 476 assert(isAddressExpression(*V) && 477 V->getType()->getPointerAddressSpace() == FlatAddrSpace); 478 479 if (Instruction *I = dyn_cast<Instruction>(V)) { 480 Value *NewV = cloneInstructionWithNewAddressSpace( 481 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix); 482 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) { 483 if (NewI->getParent() == nullptr) { 484 NewI->insertBefore(I); 485 NewI->takeName(I); 486 } 487 } 488 return NewV; 489 } 490 491 return cloneConstantExprWithNewAddressSpace( 492 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace); 493 } 494 495 // Defines the join operation on the address space lattice (see the file header 496 // comments). 497 unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1, 498 unsigned AS2) const { 499 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace) 500 return FlatAddrSpace; 501 502 if (AS1 == UninitializedAddressSpace) 503 return AS2; 504 if (AS2 == UninitializedAddressSpace) 505 return AS1; 506 507 // The join of two different specific address spaces is flat. 508 return (AS1 == AS2) ? AS1 : FlatAddrSpace; 509 } 510 511 bool InferAddressSpaces::runOnFunction(Function &F) { 512 if (skipFunction(F)) 513 return false; 514 515 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 516 FlatAddrSpace = TTI.getFlatAddressSpace(); 517 if (FlatAddrSpace == UninitializedAddressSpace) 518 return false; 519 520 // Collects all flat address expressions in postorder. 521 std::vector<Value *> Postorder = collectFlatAddressExpressions(F); 522 523 // Runs a data-flow analysis to refine the address spaces of every expression 524 // in Postorder. 525 ValueToAddrSpaceMapTy InferredAddrSpace; 526 inferAddressSpaces(Postorder, &InferredAddrSpace); 527 528 // Changes the address spaces of the flat address expressions who are inferred 529 // to point to a specific address space. 530 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, &F); 531 } 532 533 void InferAddressSpaces::inferAddressSpaces( 534 const std::vector<Value *> &Postorder, 535 ValueToAddrSpaceMapTy *InferredAddrSpace) const { 536 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end()); 537 // Initially, all expressions are in the uninitialized address space. 538 for (Value *V : Postorder) 539 (*InferredAddrSpace)[V] = UninitializedAddressSpace; 540 541 while (!Worklist.empty()) { 542 Value* V = Worklist.pop_back_val(); 543 544 // Tries to update the address space of the stack top according to the 545 // address spaces of its operands. 546 DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n'); 547 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace); 548 if (!NewAS.hasValue()) 549 continue; 550 // If any updates are made, grabs its users to the worklist because 551 // their address spaces can also be possibly updated. 552 DEBUG(dbgs() << " to " << NewAS.getValue() << '\n'); 553 (*InferredAddrSpace)[V] = NewAS.getValue(); 554 555 for (Value *User : V->users()) { 556 // Skip if User is already in the worklist. 557 if (Worklist.count(User)) 558 continue; 559 560 auto Pos = InferredAddrSpace->find(User); 561 // Our algorithm only updates the address spaces of flat address 562 // expressions, which are those in InferredAddrSpace. 563 if (Pos == InferredAddrSpace->end()) 564 continue; 565 566 // Function updateAddressSpace moves the address space down a lattice 567 // path. Therefore, nothing to do if User is already inferred as flat (the 568 // bottom element in the lattice). 569 if (Pos->second == FlatAddrSpace) 570 continue; 571 572 Worklist.insert(User); 573 } 574 } 575 } 576 577 Optional<unsigned> InferAddressSpaces::updateAddressSpace( 578 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const { 579 assert(InferredAddrSpace.count(&V)); 580 581 // The new inferred address space equals the join of the address spaces 582 // of all its pointer operands. 583 unsigned NewAS = UninitializedAddressSpace; 584 for (Value *PtrOperand : getPointerOperands(V)) { 585 auto I = InferredAddrSpace.find(PtrOperand); 586 unsigned OperandAS = I != InferredAddrSpace.end() ? 587 I->second : PtrOperand->getType()->getPointerAddressSpace(); 588 589 // join(flat, *) = flat. So we can break if NewAS is already flat. 590 NewAS = joinAddressSpaces(NewAS, OperandAS); 591 if (NewAS == FlatAddrSpace) 592 break; 593 } 594 595 unsigned OldAS = InferredAddrSpace.lookup(&V); 596 assert(OldAS != FlatAddrSpace); 597 if (OldAS == NewAS) 598 return None; 599 return NewAS; 600 } 601 602 /// \p returns true if \p U is the pointer operand of a memory instruction with 603 /// a single pointer operand that can have its address space changed by simply 604 /// mutating the use to a new value. 605 static bool isSimplePointerUseValidToReplace(Use &U) { 606 User *Inst = U.getUser(); 607 unsigned OpNo = U.getOperandNo(); 608 609 if (auto *LI = dyn_cast<LoadInst>(Inst)) 610 return OpNo == LoadInst::getPointerOperandIndex() && !LI->isVolatile(); 611 612 if (auto *SI = dyn_cast<StoreInst>(Inst)) 613 return OpNo == StoreInst::getPointerOperandIndex() && !SI->isVolatile(); 614 615 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) 616 return OpNo == AtomicRMWInst::getPointerOperandIndex() && !RMW->isVolatile(); 617 618 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 619 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() && 620 !CmpX->isVolatile(); 621 } 622 623 return false; 624 } 625 626 /// Update memory intrinsic uses that require more complex processing than 627 /// simple memory instructions. Thse require re-mangling and may have multiple 628 /// pointer operands. 629 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, 630 Value *OldV, Value *NewV) { 631 IRBuilder<> B(MI); 632 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa); 633 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope); 634 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias); 635 636 if (auto *MSI = dyn_cast<MemSetInst>(MI)) { 637 B.CreateMemSet(NewV, MSI->getValue(), 638 MSI->getLength(), MSI->getAlignment(), 639 false, // isVolatile 640 TBAA, ScopeMD, NoAliasMD); 641 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) { 642 Value *Src = MTI->getRawSource(); 643 Value *Dest = MTI->getRawDest(); 644 645 // Be careful in case this is a self-to-self copy. 646 if (Src == OldV) 647 Src = NewV; 648 649 if (Dest == OldV) 650 Dest = NewV; 651 652 if (isa<MemCpyInst>(MTI)) { 653 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 654 B.CreateMemCpy(Dest, Src, MTI->getLength(), 655 MTI->getAlignment(), 656 false, // isVolatile 657 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 658 } else { 659 assert(isa<MemMoveInst>(MTI)); 660 B.CreateMemMove(Dest, Src, MTI->getLength(), 661 MTI->getAlignment(), 662 false, // isVolatile 663 TBAA, ScopeMD, NoAliasMD); 664 } 665 } else 666 llvm_unreachable("unhandled MemIntrinsic"); 667 668 MI->eraseFromParent(); 669 return true; 670 } 671 672 // \p returns true if it is OK to change the address space of constant \p C with 673 // a ConstantExpr addrspacecast. 674 bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const { 675 unsigned SrcAS = C->getType()->getPointerAddressSpace(); 676 if (SrcAS == NewAS || isa<UndefValue>(C)) 677 return true; 678 679 // Prevent illegal casts between different non-flat address spaces. 680 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace) 681 return false; 682 683 if (isa<ConstantPointerNull>(C)) 684 return true; 685 686 if (auto *Op = dyn_cast<Operator>(C)) { 687 // If we already have a constant addrspacecast, it should be safe to cast it 688 // off. 689 if (Op->getOpcode() == Instruction::AddrSpaceCast) 690 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS); 691 692 if (Op->getOpcode() == Instruction::IntToPtr && 693 Op->getType()->getPointerAddressSpace() == FlatAddrSpace) 694 return true; 695 } 696 697 return false; 698 } 699 700 static Value::use_iterator skipToNextUser(Value::use_iterator I, 701 Value::use_iterator End) { 702 User *CurUser = I->getUser(); 703 ++I; 704 705 while (I != End && I->getUser() == CurUser) 706 ++I; 707 708 return I; 709 } 710 711 bool InferAddressSpaces::rewriteWithNewAddressSpaces( 712 const std::vector<Value *> &Postorder, 713 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const { 714 // For each address expression to be modified, creates a clone of it with its 715 // pointer operands converted to the new address space. Since the pointer 716 // operands are converted, the clone is naturally in the new address space by 717 // construction. 718 ValueToValueMapTy ValueWithNewAddrSpace; 719 SmallVector<const Use *, 32> UndefUsesToFix; 720 for (Value* V : Postorder) { 721 unsigned NewAddrSpace = InferredAddrSpace.lookup(V); 722 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) { 723 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace( 724 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix); 725 } 726 } 727 728 if (ValueWithNewAddrSpace.empty()) 729 return false; 730 731 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace. 732 for (const Use* UndefUse : UndefUsesToFix) { 733 User *V = UndefUse->getUser(); 734 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V)); 735 unsigned OperandNo = UndefUse->getOperandNo(); 736 assert(isa<UndefValue>(NewV->getOperand(OperandNo))); 737 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get())); 738 } 739 740 // Replaces the uses of the old address expressions with the new ones. 741 for (Value *V : Postorder) { 742 Value *NewV = ValueWithNewAddrSpace.lookup(V); 743 if (NewV == nullptr) 744 continue; 745 746 DEBUG(dbgs() << "Replacing the uses of " << *V 747 << "\n with\n " << *NewV << '\n'); 748 749 Value::use_iterator I, E, Next; 750 for (I = V->use_begin(), E = V->use_end(); I != E; ) { 751 Use &U = *I; 752 753 // Some users may see the same pointer operand in multiple operands. Skip 754 // to the next instruction. 755 I = skipToNextUser(I, E); 756 757 if (isSimplePointerUseValidToReplace(U)) { 758 // If V is used as the pointer operand of a compatible memory operation, 759 // sets the pointer operand to NewV. This replacement does not change 760 // the element type, so the resultant load/store is still valid. 761 U.set(NewV); 762 continue; 763 } 764 765 User *CurUser = U.getUser(); 766 // Handle more complex cases like intrinsic that need to be remangled. 767 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) { 768 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV)) 769 continue; 770 } 771 772 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) { 773 if (rewriteIntrinsicOperands(II, V, NewV)) 774 continue; 775 } 776 777 if (isa<Instruction>(CurUser)) { 778 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) { 779 // If we can infer that both pointers are in the same addrspace, 780 // transform e.g. 781 // %cmp = icmp eq float* %p, %q 782 // into 783 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q 784 785 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 786 int SrcIdx = U.getOperandNo(); 787 int OtherIdx = (SrcIdx == 0) ? 1 : 0; 788 Value *OtherSrc = Cmp->getOperand(OtherIdx); 789 790 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) { 791 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) { 792 Cmp->setOperand(OtherIdx, OtherNewV); 793 Cmp->setOperand(SrcIdx, NewV); 794 continue; 795 } 796 } 797 798 // Even if the type mismatches, we can cast the constant. 799 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) { 800 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) { 801 Cmp->setOperand(SrcIdx, NewV); 802 Cmp->setOperand(OtherIdx, 803 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType())); 804 continue; 805 } 806 } 807 } 808 809 // Otherwise, replaces the use with flat(NewV). 810 if (Instruction *I = dyn_cast<Instruction>(V)) { 811 BasicBlock::iterator InsertPos = std::next(I->getIterator()); 812 while (isa<PHINode>(InsertPos)) 813 ++InsertPos; 814 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos)); 815 } else { 816 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), 817 V->getType())); 818 } 819 } 820 } 821 822 if (V->use_empty()) 823 RecursivelyDeleteTriviallyDeadInstructions(V); 824 } 825 826 return true; 827 } 828 829 FunctionPass *llvm::createInferAddressSpacesPass() { 830 return new InferAddressSpaces(); 831 } 832