1 //===- InferAddressSpace.cpp - --------------------------------------------===// 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 // CUDA C/C++ includes memory space designation as variable type qualifers (such 10 // as __global__ and __shared__). Knowing the space of a memory access allows 11 // CUDA compilers to emit faster PTX loads and stores. For example, a load from 12 // shared memory can be translated to `ld.shared` which is roughly 10% faster 13 // than a generic `ld` on an NVIDIA Tesla K40c. 14 // 15 // Unfortunately, type qualifiers only apply to variable declarations, so CUDA 16 // compilers must infer the memory space of an address expression from 17 // type-qualified variables. 18 // 19 // LLVM IR uses non-zero (so-called) specific address spaces to represent memory 20 // spaces (e.g. addrspace(3) means shared memory). The Clang frontend 21 // places only type-qualified variables in specific address spaces, and then 22 // conservatively `addrspacecast`s each type-qualified variable to addrspace(0) 23 // (so-called the generic address space) for other instructions to use. 24 // 25 // For example, the Clang translates the following CUDA code 26 // __shared__ float a[10]; 27 // float v = a[i]; 28 // to 29 // %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]* 30 // %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i 31 // %v = load float, float* %1 ; emits ld.f32 32 // @a is in addrspace(3) since it's type-qualified, but its use from %1 is 33 // redirected to %0 (the generic version of @a). 34 // 35 // The optimization implemented in this file propagates specific address spaces 36 // from type-qualified variable declarations to its users. For example, it 37 // optimizes the above IR to 38 // %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i 39 // %v = load float addrspace(3)* %1 ; emits ld.shared.f32 40 // propagating the addrspace(3) from @a to %1. As the result, the NVPTX 41 // codegen is able to emit ld.shared.f32 for %v. 42 // 43 // Address space inference works in two steps. First, it uses a data-flow 44 // analysis to infer as many generic pointers as possible to point to only one 45 // specific address space. In the above example, it can prove that %1 only 46 // points to addrspace(3). This algorithm was published in 47 // CUDA: Compiling and optimizing for a GPU platform 48 // Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang 49 // ICCS 2012 50 // 51 // Then, address space inference replaces all refinable generic pointers with 52 // equivalent specific pointers. 53 // 54 // The major challenge of implementing this optimization is handling PHINodes, 55 // which may create loops in the data flow graph. This brings two complications. 56 // 57 // First, the data flow analysis in Step 1 needs to be circular. For example, 58 // %generic.input = addrspacecast float addrspace(3)* %input to float* 59 // loop: 60 // %y = phi [ %generic.input, %y2 ] 61 // %y2 = getelementptr %y, 1 62 // %v = load %y2 63 // br ..., label %loop, ... 64 // proving %y specific requires proving both %generic.input and %y2 specific, 65 // but proving %y2 specific circles back to %y. To address this complication, 66 // the data flow analysis operates on a lattice: 67 // uninitialized > specific address spaces > generic. 68 // All address expressions (our implementation only considers phi, bitcast, 69 // addrspacecast, and getelementptr) start with the uninitialized address space. 70 // The monotone transfer function moves the address space of a pointer down a 71 // lattice path from uninitialized to specific and then to generic. A join 72 // operation of two different specific address spaces pushes the expression down 73 // to the generic address space. The analysis completes once it reaches a fixed 74 // point. 75 // 76 // Second, IR rewriting in Step 2 also needs to be circular. For example, 77 // converting %y to addrspace(3) requires the compiler to know the converted 78 // %y2, but converting %y2 needs the converted %y. To address this complication, 79 // we break these cycles using "poison" placeholders. When converting an 80 // instruction `I` to a new address space, if its operand `Op` is not converted 81 // yet, we let `I` temporarily use `poison` and fix all the uses later. 82 // For instance, our algorithm first converts %y to 83 // %y' = phi float addrspace(3)* [ %input, poison ] 84 // Then, it converts %y2 to 85 // %y2' = getelementptr %y', 1 86 // Finally, it fixes the poison in %y' so that 87 // %y' = phi float addrspace(3)* [ %input, %y2' ] 88 // 89 //===----------------------------------------------------------------------===// 90 91 #include "llvm/Transforms/Scalar/InferAddressSpaces.h" 92 #include "llvm/ADT/ArrayRef.h" 93 #include "llvm/ADT/DenseMap.h" 94 #include "llvm/ADT/DenseSet.h" 95 #include "llvm/ADT/SetVector.h" 96 #include "llvm/ADT/SmallVector.h" 97 #include "llvm/Analysis/AssumptionCache.h" 98 #include "llvm/Analysis/TargetTransformInfo.h" 99 #include "llvm/Analysis/ValueTracking.h" 100 #include "llvm/IR/BasicBlock.h" 101 #include "llvm/IR/Constant.h" 102 #include "llvm/IR/Constants.h" 103 #include "llvm/IR/Dominators.h" 104 #include "llvm/IR/Function.h" 105 #include "llvm/IR/IRBuilder.h" 106 #include "llvm/IR/InstIterator.h" 107 #include "llvm/IR/Instruction.h" 108 #include "llvm/IR/Instructions.h" 109 #include "llvm/IR/IntrinsicInst.h" 110 #include "llvm/IR/Intrinsics.h" 111 #include "llvm/IR/LLVMContext.h" 112 #include "llvm/IR/Operator.h" 113 #include "llvm/IR/PassManager.h" 114 #include "llvm/IR/Type.h" 115 #include "llvm/IR/Use.h" 116 #include "llvm/IR/User.h" 117 #include "llvm/IR/Value.h" 118 #include "llvm/IR/ValueHandle.h" 119 #include "llvm/InitializePasses.h" 120 #include "llvm/Pass.h" 121 #include "llvm/Support/Casting.h" 122 #include "llvm/Support/CommandLine.h" 123 #include "llvm/Support/Compiler.h" 124 #include "llvm/Support/Debug.h" 125 #include "llvm/Support/ErrorHandling.h" 126 #include "llvm/Support/raw_ostream.h" 127 #include "llvm/Transforms/Scalar.h" 128 #include "llvm/Transforms/Utils/Local.h" 129 #include "llvm/Transforms/Utils/ValueMapper.h" 130 #include <cassert> 131 #include <iterator> 132 #include <limits> 133 #include <utility> 134 #include <vector> 135 136 #define DEBUG_TYPE "infer-address-spaces" 137 138 using namespace llvm; 139 140 static cl::opt<bool> AssumeDefaultIsFlatAddressSpace( 141 "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden, 142 cl::desc("The default address space is assumed as the flat address space. " 143 "This is mainly for test purpose.")); 144 145 static const unsigned UninitializedAddressSpace = 146 std::numeric_limits<unsigned>::max(); 147 148 namespace { 149 150 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>; 151 // Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on 152 // the *def* of a value, PredicatedAddrSpaceMapTy is map where a new 153 // addrspace is inferred on the *use* of a pointer. This map is introduced to 154 // infer addrspace from the addrspace predicate assumption built from assume 155 // intrinsic. In that scenario, only specific uses (under valid assumption 156 // context) could be inferred with a new addrspace. 157 using PredicatedAddrSpaceMapTy = 158 DenseMap<std::pair<const Value *, const Value *>, unsigned>; 159 using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>; 160 161 class InferAddressSpaces : public FunctionPass { 162 unsigned FlatAddrSpace = 0; 163 164 public: 165 static char ID; 166 167 InferAddressSpaces() 168 : FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) { 169 initializeInferAddressSpacesPass(*PassRegistry::getPassRegistry()); 170 } 171 InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) { 172 initializeInferAddressSpacesPass(*PassRegistry::getPassRegistry()); 173 } 174 175 void getAnalysisUsage(AnalysisUsage &AU) const override { 176 AU.setPreservesCFG(); 177 AU.addPreserved<DominatorTreeWrapperPass>(); 178 AU.addRequired<AssumptionCacheTracker>(); 179 AU.addRequired<TargetTransformInfoWrapperPass>(); 180 } 181 182 bool runOnFunction(Function &F) override; 183 }; 184 185 class InferAddressSpacesImpl { 186 AssumptionCache &AC; 187 Function *F = nullptr; 188 const DominatorTree *DT = nullptr; 189 const TargetTransformInfo *TTI = nullptr; 190 const DataLayout *DL = nullptr; 191 192 /// Target specific address space which uses of should be replaced if 193 /// possible. 194 unsigned FlatAddrSpace = 0; 195 196 // Try to update the address space of V. If V is updated, returns true and 197 // false otherwise. 198 bool updateAddressSpace(const Value &V, 199 ValueToAddrSpaceMapTy &InferredAddrSpace, 200 PredicatedAddrSpaceMapTy &PredicatedAS) const; 201 202 // Tries to infer the specific address space of each address expression in 203 // Postorder. 204 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder, 205 ValueToAddrSpaceMapTy &InferredAddrSpace, 206 PredicatedAddrSpaceMapTy &PredicatedAS) const; 207 208 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const; 209 210 Value *cloneInstructionWithNewAddressSpace( 211 Instruction *I, unsigned NewAddrSpace, 212 const ValueToValueMapTy &ValueWithNewAddrSpace, 213 const PredicatedAddrSpaceMapTy &PredicatedAS, 214 SmallVectorImpl<const Use *> *PoisonUsesToFix) const; 215 216 void performPointerReplacement( 217 Value *V, Value *NewV, Use &U, ValueToValueMapTy &ValueWithNewAddrSpace, 218 SmallVectorImpl<Instruction *> &DeadInstructions) const; 219 220 // Changes the flat address expressions in function F to point to specific 221 // address spaces if InferredAddrSpace says so. Postorder is the postorder of 222 // all flat expressions in the use-def graph of function F. 223 bool rewriteWithNewAddressSpaces( 224 ArrayRef<WeakTrackingVH> Postorder, 225 const ValueToAddrSpaceMapTy &InferredAddrSpace, 226 const PredicatedAddrSpaceMapTy &PredicatedAS) const; 227 228 void appendsFlatAddressExpressionToPostorderStack( 229 Value *V, PostorderStackTy &PostorderStack, 230 DenseSet<Value *> &Visited) const; 231 232 bool rewriteIntrinsicOperands(IntrinsicInst *II, Value *OldV, 233 Value *NewV) const; 234 void collectRewritableIntrinsicOperands(IntrinsicInst *II, 235 PostorderStackTy &PostorderStack, 236 DenseSet<Value *> &Visited) const; 237 238 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const; 239 240 Value *cloneValueWithNewAddressSpace( 241 Value *V, unsigned NewAddrSpace, 242 const ValueToValueMapTy &ValueWithNewAddrSpace, 243 const PredicatedAddrSpaceMapTy &PredicatedAS, 244 SmallVectorImpl<const Use *> *PoisonUsesToFix) const; 245 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const; 246 247 unsigned getPredicatedAddrSpace(const Value &PtrV, 248 const Value *UserCtx) const; 249 250 public: 251 InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT, 252 const TargetTransformInfo *TTI, unsigned FlatAddrSpace) 253 : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {} 254 bool run(Function &F); 255 }; 256 257 } // end anonymous namespace 258 259 char InferAddressSpaces::ID = 0; 260 261 INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 262 false, false) 263 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 264 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 265 INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 266 false, false) 267 268 static Type *getPtrOrVecOfPtrsWithNewAS(Type *Ty, unsigned NewAddrSpace) { 269 assert(Ty->isPtrOrPtrVectorTy()); 270 PointerType *NPT = PointerType::get(Ty->getContext(), NewAddrSpace); 271 return Ty->getWithNewType(NPT); 272 } 273 274 // Check whether that's no-op pointer bicast using a pair of 275 // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over 276 // different address spaces. 277 static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL, 278 const TargetTransformInfo *TTI) { 279 assert(I2P->getOpcode() == Instruction::IntToPtr); 280 auto *P2I = dyn_cast<Operator>(I2P->getOperand(0)); 281 if (!P2I || P2I->getOpcode() != Instruction::PtrToInt) 282 return false; 283 // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a 284 // no-op cast. Besides checking both of them are no-op casts, as the 285 // reinterpreted pointer may be used in other pointer arithmetic, we also 286 // need to double-check that through the target-specific hook. That ensures 287 // the underlying target also agrees that's a no-op address space cast and 288 // pointer bits are preserved. 289 // The current IR spec doesn't have clear rules on address space casts, 290 // especially a clear definition for pointer bits in non-default address 291 // spaces. It would be undefined if that pointer is dereferenced after an 292 // invalid reinterpret cast. Also, due to the unclearness for the meaning of 293 // bits in non-default address spaces in the current spec, the pointer 294 // arithmetic may also be undefined after invalid pointer reinterpret cast. 295 // However, as we confirm through the target hooks that it's a no-op 296 // addrspacecast, it doesn't matter since the bits should be the same. 297 unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace(); 298 unsigned I2PAS = I2P->getType()->getPointerAddressSpace(); 299 return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()), 300 I2P->getOperand(0)->getType(), I2P->getType(), 301 DL) && 302 CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()), 303 P2I->getOperand(0)->getType(), P2I->getType(), 304 DL) && 305 (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS)); 306 } 307 308 // Returns true if V is an address expression. 309 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and 310 // getelementptr operators. 311 static bool isAddressExpression(const Value &V, const DataLayout &DL, 312 const TargetTransformInfo *TTI) { 313 const Operator *Op = dyn_cast<Operator>(&V); 314 if (!Op) 315 return false; 316 317 switch (Op->getOpcode()) { 318 case Instruction::PHI: 319 assert(Op->getType()->isPtrOrPtrVectorTy()); 320 return true; 321 case Instruction::BitCast: 322 case Instruction::AddrSpaceCast: 323 case Instruction::GetElementPtr: 324 return true; 325 case Instruction::Select: 326 return Op->getType()->isPtrOrPtrVectorTy(); 327 case Instruction::Call: { 328 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V); 329 return II && II->getIntrinsicID() == Intrinsic::ptrmask; 330 } 331 case Instruction::IntToPtr: 332 return isNoopPtrIntCastPair(Op, DL, TTI); 333 default: 334 // That value is an address expression if it has an assumed address space. 335 return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace; 336 } 337 } 338 339 // Returns the pointer operands of V. 340 // 341 // Precondition: V is an address expression. 342 static SmallVector<Value *, 2> 343 getPointerOperands(const Value &V, const DataLayout &DL, 344 const TargetTransformInfo *TTI) { 345 const Operator &Op = cast<Operator>(V); 346 switch (Op.getOpcode()) { 347 case Instruction::PHI: { 348 auto IncomingValues = cast<PHINode>(Op).incoming_values(); 349 return {IncomingValues.begin(), IncomingValues.end()}; 350 } 351 case Instruction::BitCast: 352 case Instruction::AddrSpaceCast: 353 case Instruction::GetElementPtr: 354 return {Op.getOperand(0)}; 355 case Instruction::Select: 356 return {Op.getOperand(1), Op.getOperand(2)}; 357 case Instruction::Call: { 358 const IntrinsicInst &II = cast<IntrinsicInst>(Op); 359 assert(II.getIntrinsicID() == Intrinsic::ptrmask && 360 "unexpected intrinsic call"); 361 return {II.getArgOperand(0)}; 362 } 363 case Instruction::IntToPtr: { 364 assert(isNoopPtrIntCastPair(&Op, DL, TTI)); 365 auto *P2I = cast<Operator>(Op.getOperand(0)); 366 return {P2I->getOperand(0)}; 367 } 368 default: 369 llvm_unreachable("Unexpected instruction type."); 370 } 371 } 372 373 bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II, 374 Value *OldV, 375 Value *NewV) const { 376 Module *M = II->getParent()->getParent()->getParent(); 377 Intrinsic::ID IID = II->getIntrinsicID(); 378 switch (IID) { 379 case Intrinsic::objectsize: 380 case Intrinsic::masked_load: { 381 Type *DestTy = II->getType(); 382 Type *SrcTy = NewV->getType(); 383 Function *NewDecl = Intrinsic::getDeclaration(M, IID, {DestTy, SrcTy}); 384 II->setArgOperand(0, NewV); 385 II->setCalledFunction(NewDecl); 386 return true; 387 } 388 case Intrinsic::ptrmask: 389 // This is handled as an address expression, not as a use memory operation. 390 return false; 391 case Intrinsic::masked_gather: { 392 Type *RetTy = II->getType(); 393 Type *NewPtrTy = NewV->getType(); 394 Function *NewDecl = Intrinsic::getDeclaration(M, IID, {RetTy, NewPtrTy}); 395 II->setArgOperand(0, NewV); 396 II->setCalledFunction(NewDecl); 397 return true; 398 } 399 case Intrinsic::masked_store: 400 case Intrinsic::masked_scatter: { 401 Type *ValueTy = II->getOperand(0)->getType(); 402 Type *NewPtrTy = NewV->getType(); 403 Function *NewDecl = 404 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {ValueTy, NewPtrTy}); 405 II->setArgOperand(1, NewV); 406 II->setCalledFunction(NewDecl); 407 return true; 408 } 409 case Intrinsic::prefetch: 410 case Intrinsic::is_constant: { 411 Function *NewDecl = 412 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {NewV->getType()}); 413 II->setArgOperand(0, NewV); 414 II->setCalledFunction(NewDecl); 415 return true; 416 } 417 default: { 418 Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV); 419 if (!Rewrite) 420 return false; 421 if (Rewrite != II) 422 II->replaceAllUsesWith(Rewrite); 423 return true; 424 } 425 } 426 } 427 428 void InferAddressSpacesImpl::collectRewritableIntrinsicOperands( 429 IntrinsicInst *II, PostorderStackTy &PostorderStack, 430 DenseSet<Value *> &Visited) const { 431 auto IID = II->getIntrinsicID(); 432 switch (IID) { 433 case Intrinsic::ptrmask: 434 case Intrinsic::objectsize: 435 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0), 436 PostorderStack, Visited); 437 break; 438 case Intrinsic::is_constant: { 439 Value *Ptr = II->getArgOperand(0); 440 if (Ptr->getType()->isPtrOrPtrVectorTy()) { 441 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack, 442 Visited); 443 } 444 445 break; 446 } 447 case Intrinsic::masked_load: 448 case Intrinsic::masked_gather: 449 case Intrinsic::prefetch: 450 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0), 451 PostorderStack, Visited); 452 break; 453 case Intrinsic::masked_store: 454 case Intrinsic::masked_scatter: 455 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(1), 456 PostorderStack, Visited); 457 break; 458 default: 459 SmallVector<int, 2> OpIndexes; 460 if (TTI->collectFlatAddressOperands(OpIndexes, IID)) { 461 for (int Idx : OpIndexes) { 462 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx), 463 PostorderStack, Visited); 464 } 465 } 466 break; 467 } 468 } 469 470 // Returns all flat address expressions in function F. The elements are 471 // If V is an unvisited flat address expression, appends V to PostorderStack 472 // and marks it as visited. 473 void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack( 474 Value *V, PostorderStackTy &PostorderStack, 475 DenseSet<Value *> &Visited) const { 476 assert(V->getType()->isPtrOrPtrVectorTy()); 477 478 // Generic addressing expressions may be hidden in nested constant 479 // expressions. 480 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 481 // TODO: Look in non-address parts, like icmp operands. 482 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second) 483 PostorderStack.emplace_back(CE, false); 484 485 return; 486 } 487 488 if (V->getType()->getPointerAddressSpace() == FlatAddrSpace && 489 isAddressExpression(*V, *DL, TTI)) { 490 if (Visited.insert(V).second) { 491 PostorderStack.emplace_back(V, false); 492 493 Operator *Op = cast<Operator>(V); 494 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) { 495 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) { 496 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second) 497 PostorderStack.emplace_back(CE, false); 498 } 499 } 500 } 501 } 502 } 503 504 // Returns all flat address expressions in function F. The elements are ordered 505 // in postorder. 506 std::vector<WeakTrackingVH> 507 InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const { 508 // This function implements a non-recursive postorder traversal of a partial 509 // use-def graph of function F. 510 PostorderStackTy PostorderStack; 511 // The set of visited expressions. 512 DenseSet<Value *> Visited; 513 514 auto PushPtrOperand = [&](Value *Ptr) { 515 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack, Visited); 516 }; 517 518 // Look at operations that may be interesting accelerate by moving to a known 519 // address space. We aim at generating after loads and stores, but pure 520 // addressing calculations may also be faster. 521 for (Instruction &I : instructions(F)) { 522 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 523 PushPtrOperand(GEP->getPointerOperand()); 524 } else if (auto *LI = dyn_cast<LoadInst>(&I)) 525 PushPtrOperand(LI->getPointerOperand()); 526 else if (auto *SI = dyn_cast<StoreInst>(&I)) 527 PushPtrOperand(SI->getPointerOperand()); 528 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I)) 529 PushPtrOperand(RMW->getPointerOperand()); 530 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I)) 531 PushPtrOperand(CmpX->getPointerOperand()); 532 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) { 533 // For memset/memcpy/memmove, any pointer operand can be replaced. 534 PushPtrOperand(MI->getRawDest()); 535 536 // Handle 2nd operand for memcpy/memmove. 537 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) 538 PushPtrOperand(MTI->getRawSource()); 539 } else if (auto *II = dyn_cast<IntrinsicInst>(&I)) 540 collectRewritableIntrinsicOperands(II, PostorderStack, Visited); 541 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) { 542 if (Cmp->getOperand(0)->getType()->isPtrOrPtrVectorTy()) { 543 PushPtrOperand(Cmp->getOperand(0)); 544 PushPtrOperand(Cmp->getOperand(1)); 545 } 546 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) { 547 PushPtrOperand(ASC->getPointerOperand()); 548 } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) { 549 if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI)) 550 PushPtrOperand(cast<Operator>(I2P->getOperand(0))->getOperand(0)); 551 } else if (auto *RI = dyn_cast<ReturnInst>(&I)) { 552 if (auto *RV = RI->getReturnValue(); 553 RV && RV->getType()->isPtrOrPtrVectorTy()) 554 PushPtrOperand(RV); 555 } 556 } 557 558 std::vector<WeakTrackingVH> Postorder; // The resultant postorder. 559 while (!PostorderStack.empty()) { 560 Value *TopVal = PostorderStack.back().getPointer(); 561 // If the operands of the expression on the top are already explored, 562 // adds that expression to the resultant postorder. 563 if (PostorderStack.back().getInt()) { 564 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace) 565 Postorder.push_back(TopVal); 566 PostorderStack.pop_back(); 567 continue; 568 } 569 // Otherwise, adds its operands to the stack and explores them. 570 PostorderStack.back().setInt(true); 571 // Skip values with an assumed address space. 572 if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) { 573 for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) { 574 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack, 575 Visited); 576 } 577 } 578 } 579 return Postorder; 580 } 581 582 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone 583 // of OperandUse.get() in the new address space. If the clone is not ready yet, 584 // returns poison in the new address space as a placeholder. 585 static Value *operandWithNewAddressSpaceOrCreatePoison( 586 const Use &OperandUse, unsigned NewAddrSpace, 587 const ValueToValueMapTy &ValueWithNewAddrSpace, 588 const PredicatedAddrSpaceMapTy &PredicatedAS, 589 SmallVectorImpl<const Use *> *PoisonUsesToFix) { 590 Value *Operand = OperandUse.get(); 591 592 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAddrSpace); 593 594 if (Constant *C = dyn_cast<Constant>(Operand)) 595 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy); 596 597 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) 598 return NewOperand; 599 600 Instruction *Inst = cast<Instruction>(OperandUse.getUser()); 601 auto I = PredicatedAS.find(std::make_pair(Inst, Operand)); 602 if (I != PredicatedAS.end()) { 603 // Insert an addrspacecast on that operand before the user. 604 unsigned NewAS = I->second; 605 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAS); 606 auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy); 607 NewI->insertBefore(Inst); 608 NewI->setDebugLoc(Inst->getDebugLoc()); 609 return NewI; 610 } 611 612 PoisonUsesToFix->push_back(&OperandUse); 613 return PoisonValue::get(NewPtrTy); 614 } 615 616 // Returns a clone of `I` with its operands converted to those specified in 617 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an 618 // operand whose address space needs to be modified might not exist in 619 // ValueWithNewAddrSpace. In that case, uses poison as a placeholder operand and 620 // adds that operand use to PoisonUsesToFix so that caller can fix them later. 621 // 622 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast 623 // from a pointer whose type already matches. Therefore, this function returns a 624 // Value* instead of an Instruction*. 625 // 626 // This may also return nullptr in the case the instruction could not be 627 // rewritten. 628 Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace( 629 Instruction *I, unsigned NewAddrSpace, 630 const ValueToValueMapTy &ValueWithNewAddrSpace, 631 const PredicatedAddrSpaceMapTy &PredicatedAS, 632 SmallVectorImpl<const Use *> *PoisonUsesToFix) const { 633 Type *NewPtrType = getPtrOrVecOfPtrsWithNewAS(I->getType(), NewAddrSpace); 634 635 if (I->getOpcode() == Instruction::AddrSpaceCast) { 636 Value *Src = I->getOperand(0); 637 // Because `I` is flat, the source address space must be specific. 638 // Therefore, the inferred address space must be the source space, according 639 // to our algorithm. 640 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 641 if (Src->getType() != NewPtrType) 642 return new BitCastInst(Src, NewPtrType); 643 return Src; 644 } 645 646 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 647 // Technically the intrinsic ID is a pointer typed argument, so specially 648 // handle calls early. 649 assert(II->getIntrinsicID() == Intrinsic::ptrmask); 650 Value *NewPtr = operandWithNewAddressSpaceOrCreatePoison( 651 II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace, 652 PredicatedAS, PoisonUsesToFix); 653 Value *Rewrite = 654 TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr); 655 if (Rewrite) { 656 assert(Rewrite != II && "cannot modify this pointer operation in place"); 657 return Rewrite; 658 } 659 660 return nullptr; 661 } 662 663 unsigned AS = TTI->getAssumedAddrSpace(I); 664 if (AS != UninitializedAddressSpace) { 665 // For the assumed address space, insert an `addrspacecast` to make that 666 // explicit. 667 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(I->getType(), AS); 668 auto *NewI = new AddrSpaceCastInst(I, NewPtrTy); 669 NewI->insertAfter(I); 670 NewI->setDebugLoc(I->getDebugLoc()); 671 return NewI; 672 } 673 674 // Computes the converted pointer operands. 675 SmallVector<Value *, 4> NewPointerOperands; 676 for (const Use &OperandUse : I->operands()) { 677 if (!OperandUse.get()->getType()->isPtrOrPtrVectorTy()) 678 NewPointerOperands.push_back(nullptr); 679 else 680 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreatePoison( 681 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, 682 PoisonUsesToFix)); 683 } 684 685 switch (I->getOpcode()) { 686 case Instruction::BitCast: 687 return new BitCastInst(NewPointerOperands[0], NewPtrType); 688 case Instruction::PHI: { 689 assert(I->getType()->isPtrOrPtrVectorTy()); 690 PHINode *PHI = cast<PHINode>(I); 691 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues()); 692 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) { 693 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index); 694 NewPHI->addIncoming(NewPointerOperands[OperandNo], 695 PHI->getIncomingBlock(Index)); 696 } 697 return NewPHI; 698 } 699 case Instruction::GetElementPtr: { 700 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 701 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 702 GEP->getSourceElementType(), NewPointerOperands[0], 703 SmallVector<Value *, 4>(GEP->indices())); 704 NewGEP->setIsInBounds(GEP->isInBounds()); 705 return NewGEP; 706 } 707 case Instruction::Select: 708 assert(I->getType()->isPtrOrPtrVectorTy()); 709 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1], 710 NewPointerOperands[2], "", nullptr, I); 711 case Instruction::IntToPtr: { 712 assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI)); 713 Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0); 714 if (Src->getType() == NewPtrType) 715 return Src; 716 717 // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a 718 // source address space from a generic pointer source need to insert a cast 719 // back. 720 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType); 721 } 722 default: 723 llvm_unreachable("Unexpected opcode"); 724 } 725 } 726 727 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the 728 // constant expression `CE` with its operands replaced as specified in 729 // ValueWithNewAddrSpace. 730 static Value *cloneConstantExprWithNewAddressSpace( 731 ConstantExpr *CE, unsigned NewAddrSpace, 732 const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL, 733 const TargetTransformInfo *TTI) { 734 Type *TargetType = 735 CE->getType()->isPtrOrPtrVectorTy() 736 ? getPtrOrVecOfPtrsWithNewAS(CE->getType(), NewAddrSpace) 737 : CE->getType(); 738 739 if (CE->getOpcode() == Instruction::AddrSpaceCast) { 740 // Because CE is flat, the source address space must be specific. 741 // Therefore, the inferred address space must be the source space according 742 // to our algorithm. 743 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() == 744 NewAddrSpace); 745 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType); 746 } 747 748 if (CE->getOpcode() == Instruction::BitCast) { 749 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0))) 750 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType); 751 return ConstantExpr::getAddrSpaceCast(CE, TargetType); 752 } 753 754 if (CE->getOpcode() == Instruction::IntToPtr) { 755 assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI)); 756 Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0); 757 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 758 return ConstantExpr::getBitCast(Src, TargetType); 759 } 760 761 // Computes the operands of the new constant expression. 762 bool IsNew = false; 763 SmallVector<Constant *, 4> NewOperands; 764 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) { 765 Constant *Operand = CE->getOperand(Index); 766 // If the address space of `Operand` needs to be modified, the new operand 767 // with the new address space should already be in ValueWithNewAddrSpace 768 // because (1) the constant expressions we consider (i.e. addrspacecast, 769 // bitcast, and getelementptr) do not incur cycles in the data flow graph 770 // and (2) this function is called on constant expressions in postorder. 771 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) { 772 IsNew = true; 773 NewOperands.push_back(cast<Constant>(NewOperand)); 774 continue; 775 } 776 if (auto *CExpr = dyn_cast<ConstantExpr>(Operand)) 777 if (Value *NewOperand = cloneConstantExprWithNewAddressSpace( 778 CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) { 779 IsNew = true; 780 NewOperands.push_back(cast<Constant>(NewOperand)); 781 continue; 782 } 783 // Otherwise, reuses the old operand. 784 NewOperands.push_back(Operand); 785 } 786 787 // If !IsNew, we will replace the Value with itself. However, replaced values 788 // are assumed to wrapped in an addrspacecast cast later so drop it now. 789 if (!IsNew) 790 return nullptr; 791 792 if (CE->getOpcode() == Instruction::GetElementPtr) { 793 // Needs to specify the source type while constructing a getelementptr 794 // constant expression. 795 return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false, 796 cast<GEPOperator>(CE)->getSourceElementType()); 797 } 798 799 return CE->getWithOperands(NewOperands, TargetType); 800 } 801 802 // Returns a clone of the value `V`, with its operands replaced as specified in 803 // ValueWithNewAddrSpace. This function is called on every flat address 804 // expression whose address space needs to be modified, in postorder. 805 // 806 // See cloneInstructionWithNewAddressSpace for the meaning of PoisonUsesToFix. 807 Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace( 808 Value *V, unsigned NewAddrSpace, 809 const ValueToValueMapTy &ValueWithNewAddrSpace, 810 const PredicatedAddrSpaceMapTy &PredicatedAS, 811 SmallVectorImpl<const Use *> *PoisonUsesToFix) const { 812 // All values in Postorder are flat address expressions. 813 assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace && 814 isAddressExpression(*V, *DL, TTI)); 815 816 if (Instruction *I = dyn_cast<Instruction>(V)) { 817 Value *NewV = cloneInstructionWithNewAddressSpace( 818 I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, PoisonUsesToFix); 819 if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) { 820 if (NewI->getParent() == nullptr) { 821 NewI->insertBefore(I); 822 NewI->takeName(I); 823 NewI->setDebugLoc(I->getDebugLoc()); 824 } 825 } 826 return NewV; 827 } 828 829 return cloneConstantExprWithNewAddressSpace( 830 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI); 831 } 832 833 // Defines the join operation on the address space lattice (see the file header 834 // comments). 835 unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1, 836 unsigned AS2) const { 837 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace) 838 return FlatAddrSpace; 839 840 if (AS1 == UninitializedAddressSpace) 841 return AS2; 842 if (AS2 == UninitializedAddressSpace) 843 return AS1; 844 845 // The join of two different specific address spaces is flat. 846 return (AS1 == AS2) ? AS1 : FlatAddrSpace; 847 } 848 849 bool InferAddressSpacesImpl::run(Function &CurFn) { 850 F = &CurFn; 851 DL = &F->getDataLayout(); 852 853 if (AssumeDefaultIsFlatAddressSpace) 854 FlatAddrSpace = 0; 855 856 if (FlatAddrSpace == UninitializedAddressSpace) { 857 FlatAddrSpace = TTI->getFlatAddressSpace(); 858 if (FlatAddrSpace == UninitializedAddressSpace) 859 return false; 860 } 861 862 // Collects all flat address expressions in postorder. 863 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(*F); 864 865 // Runs a data-flow analysis to refine the address spaces of every expression 866 // in Postorder. 867 ValueToAddrSpaceMapTy InferredAddrSpace; 868 PredicatedAddrSpaceMapTy PredicatedAS; 869 inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS); 870 871 // Changes the address spaces of the flat address expressions who are inferred 872 // to point to a specific address space. 873 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, 874 PredicatedAS); 875 } 876 877 // Constants need to be tracked through RAUW to handle cases with nested 878 // constant expressions, so wrap values in WeakTrackingVH. 879 void InferAddressSpacesImpl::inferAddressSpaces( 880 ArrayRef<WeakTrackingVH> Postorder, 881 ValueToAddrSpaceMapTy &InferredAddrSpace, 882 PredicatedAddrSpaceMapTy &PredicatedAS) const { 883 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end()); 884 // Initially, all expressions are in the uninitialized address space. 885 for (Value *V : Postorder) 886 InferredAddrSpace[V] = UninitializedAddressSpace; 887 888 while (!Worklist.empty()) { 889 Value *V = Worklist.pop_back_val(); 890 891 // Try to update the address space of the stack top according to the 892 // address spaces of its operands. 893 if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS)) 894 continue; 895 896 for (Value *User : V->users()) { 897 // Skip if User is already in the worklist. 898 if (Worklist.count(User)) 899 continue; 900 901 auto Pos = InferredAddrSpace.find(User); 902 // Our algorithm only updates the address spaces of flat address 903 // expressions, which are those in InferredAddrSpace. 904 if (Pos == InferredAddrSpace.end()) 905 continue; 906 907 // Function updateAddressSpace moves the address space down a lattice 908 // path. Therefore, nothing to do if User is already inferred as flat (the 909 // bottom element in the lattice). 910 if (Pos->second == FlatAddrSpace) 911 continue; 912 913 Worklist.insert(User); 914 } 915 } 916 } 917 918 unsigned 919 InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &Ptr, 920 const Value *UserCtx) const { 921 const Instruction *UserCtxI = dyn_cast<Instruction>(UserCtx); 922 if (!UserCtxI) 923 return UninitializedAddressSpace; 924 925 const Value *StrippedPtr = Ptr.stripInBoundsOffsets(); 926 for (auto &AssumeVH : AC.assumptionsFor(StrippedPtr)) { 927 if (!AssumeVH) 928 continue; 929 CallInst *CI = cast<CallInst>(AssumeVH); 930 if (!isValidAssumeForContext(CI, UserCtxI, DT)) 931 continue; 932 933 const Value *Ptr; 934 unsigned AS; 935 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0)); 936 if (Ptr) 937 return AS; 938 } 939 940 return UninitializedAddressSpace; 941 } 942 943 bool InferAddressSpacesImpl::updateAddressSpace( 944 const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace, 945 PredicatedAddrSpaceMapTy &PredicatedAS) const { 946 assert(InferredAddrSpace.count(&V)); 947 948 LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n'); 949 950 // The new inferred address space equals the join of the address spaces 951 // of all its pointer operands. 952 unsigned NewAS = UninitializedAddressSpace; 953 954 const Operator &Op = cast<Operator>(V); 955 if (Op.getOpcode() == Instruction::Select) { 956 Value *Src0 = Op.getOperand(1); 957 Value *Src1 = Op.getOperand(2); 958 959 auto I = InferredAddrSpace.find(Src0); 960 unsigned Src0AS = (I != InferredAddrSpace.end()) 961 ? I->second 962 : Src0->getType()->getPointerAddressSpace(); 963 964 auto J = InferredAddrSpace.find(Src1); 965 unsigned Src1AS = (J != InferredAddrSpace.end()) 966 ? J->second 967 : Src1->getType()->getPointerAddressSpace(); 968 969 auto *C0 = dyn_cast<Constant>(Src0); 970 auto *C1 = dyn_cast<Constant>(Src1); 971 972 // If one of the inputs is a constant, we may be able to do a constant 973 // addrspacecast of it. Defer inferring the address space until the input 974 // address space is known. 975 if ((C1 && Src0AS == UninitializedAddressSpace) || 976 (C0 && Src1AS == UninitializedAddressSpace)) 977 return false; 978 979 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS)) 980 NewAS = Src1AS; 981 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS)) 982 NewAS = Src0AS; 983 else 984 NewAS = joinAddressSpaces(Src0AS, Src1AS); 985 } else { 986 unsigned AS = TTI->getAssumedAddrSpace(&V); 987 if (AS != UninitializedAddressSpace) { 988 // Use the assumed address space directly. 989 NewAS = AS; 990 } else { 991 // Otherwise, infer the address space from its pointer operands. 992 for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) { 993 auto I = InferredAddrSpace.find(PtrOperand); 994 unsigned OperandAS; 995 if (I == InferredAddrSpace.end()) { 996 OperandAS = PtrOperand->getType()->getPointerAddressSpace(); 997 if (OperandAS == FlatAddrSpace) { 998 // Check AC for assumption dominating V. 999 unsigned AS = getPredicatedAddrSpace(*PtrOperand, &V); 1000 if (AS != UninitializedAddressSpace) { 1001 LLVM_DEBUG(dbgs() 1002 << " deduce operand AS from the predicate addrspace " 1003 << AS << '\n'); 1004 OperandAS = AS; 1005 // Record this use with the predicated AS. 1006 PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS; 1007 } 1008 } 1009 } else 1010 OperandAS = I->second; 1011 1012 // join(flat, *) = flat. So we can break if NewAS is already flat. 1013 NewAS = joinAddressSpaces(NewAS, OperandAS); 1014 if (NewAS == FlatAddrSpace) 1015 break; 1016 } 1017 } 1018 } 1019 1020 unsigned OldAS = InferredAddrSpace.lookup(&V); 1021 assert(OldAS != FlatAddrSpace); 1022 if (OldAS == NewAS) 1023 return false; 1024 1025 // If any updates are made, grabs its users to the worklist because 1026 // their address spaces can also be possibly updated. 1027 LLVM_DEBUG(dbgs() << " to " << NewAS << '\n'); 1028 InferredAddrSpace[&V] = NewAS; 1029 return true; 1030 } 1031 1032 /// Replace operand \p OpIdx in \p Inst, if the value is the same as \p OldVal 1033 /// with \p NewVal. 1034 static bool replaceOperandIfSame(Instruction *Inst, unsigned OpIdx, 1035 Value *OldVal, Value *NewVal) { 1036 Use &U = Inst->getOperandUse(OpIdx); 1037 if (U.get() == OldVal) { 1038 U.set(NewVal); 1039 return true; 1040 } 1041 1042 return false; 1043 } 1044 1045 template <typename InstrType> 1046 static bool replaceSimplePointerUse(const TargetTransformInfo &TTI, 1047 InstrType *MemInstr, unsigned AddrSpace, 1048 Value *OldV, Value *NewV) { 1049 if (!MemInstr->isVolatile() || TTI.hasVolatileVariant(MemInstr, AddrSpace)) { 1050 return replaceOperandIfSame(MemInstr, InstrType::getPointerOperandIndex(), 1051 OldV, NewV); 1052 } 1053 1054 return false; 1055 } 1056 1057 /// If \p OldV is used as the pointer operand of a compatible memory operation 1058 /// \p Inst, replaces the pointer operand with NewV. 1059 /// 1060 /// This covers memory instructions with a single pointer operand that can have 1061 /// its address space changed by simply mutating the use to a new value. 1062 /// 1063 /// \p returns true the user replacement was made. 1064 static bool replaceIfSimplePointerUse(const TargetTransformInfo &TTI, 1065 User *Inst, unsigned AddrSpace, 1066 Value *OldV, Value *NewV) { 1067 if (auto *LI = dyn_cast<LoadInst>(Inst)) 1068 return replaceSimplePointerUse(TTI, LI, AddrSpace, OldV, NewV); 1069 1070 if (auto *SI = dyn_cast<StoreInst>(Inst)) 1071 return replaceSimplePointerUse(TTI, SI, AddrSpace, OldV, NewV); 1072 1073 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) 1074 return replaceSimplePointerUse(TTI, RMW, AddrSpace, OldV, NewV); 1075 1076 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) 1077 return replaceSimplePointerUse(TTI, CmpX, AddrSpace, OldV, NewV); 1078 1079 return false; 1080 } 1081 1082 /// Update memory intrinsic uses that require more complex processing than 1083 /// simple memory instructions. These require re-mangling and may have multiple 1084 /// pointer operands. 1085 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, 1086 Value *NewV) { 1087 IRBuilder<> B(MI); 1088 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa); 1089 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope); 1090 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias); 1091 1092 if (auto *MSI = dyn_cast<MemSetInst>(MI)) { 1093 B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(), 1094 false, // isVolatile 1095 TBAA, ScopeMD, NoAliasMD); 1096 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) { 1097 Value *Src = MTI->getRawSource(); 1098 Value *Dest = MTI->getRawDest(); 1099 1100 // Be careful in case this is a self-to-self copy. 1101 if (Src == OldV) 1102 Src = NewV; 1103 1104 if (Dest == OldV) 1105 Dest = NewV; 1106 1107 if (isa<MemCpyInlineInst>(MTI)) { 1108 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 1109 B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src, 1110 MTI->getSourceAlign(), MTI->getLength(), 1111 false, // isVolatile 1112 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 1113 } else if (isa<MemCpyInst>(MTI)) { 1114 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 1115 B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(), 1116 MTI->getLength(), 1117 false, // isVolatile 1118 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 1119 } else { 1120 assert(isa<MemMoveInst>(MTI)); 1121 B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(), 1122 MTI->getLength(), 1123 false, // isVolatile 1124 TBAA, ScopeMD, NoAliasMD); 1125 } 1126 } else 1127 llvm_unreachable("unhandled MemIntrinsic"); 1128 1129 MI->eraseFromParent(); 1130 return true; 1131 } 1132 1133 // \p returns true if it is OK to change the address space of constant \p C with 1134 // a ConstantExpr addrspacecast. 1135 bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C, 1136 unsigned NewAS) const { 1137 assert(NewAS != UninitializedAddressSpace); 1138 1139 unsigned SrcAS = C->getType()->getPointerAddressSpace(); 1140 if (SrcAS == NewAS || isa<UndefValue>(C)) 1141 return true; 1142 1143 // Prevent illegal casts between different non-flat address spaces. 1144 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace) 1145 return false; 1146 1147 if (isa<ConstantPointerNull>(C)) 1148 return true; 1149 1150 if (auto *Op = dyn_cast<Operator>(C)) { 1151 // If we already have a constant addrspacecast, it should be safe to cast it 1152 // off. 1153 if (Op->getOpcode() == Instruction::AddrSpaceCast) 1154 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), 1155 NewAS); 1156 1157 if (Op->getOpcode() == Instruction::IntToPtr && 1158 Op->getType()->getPointerAddressSpace() == FlatAddrSpace) 1159 return true; 1160 } 1161 1162 return false; 1163 } 1164 1165 static Value::use_iterator skipToNextUser(Value::use_iterator I, 1166 Value::use_iterator End) { 1167 User *CurUser = I->getUser(); 1168 ++I; 1169 1170 while (I != End && I->getUser() == CurUser) 1171 ++I; 1172 1173 return I; 1174 } 1175 1176 void InferAddressSpacesImpl::performPointerReplacement( 1177 Value *V, Value *NewV, Use &U, ValueToValueMapTy &ValueWithNewAddrSpace, 1178 SmallVectorImpl<Instruction *> &DeadInstructions) const { 1179 1180 User *CurUser = U.getUser(); 1181 1182 unsigned AddrSpace = V->getType()->getPointerAddressSpace(); 1183 if (replaceIfSimplePointerUse(*TTI, CurUser, AddrSpace, V, NewV)) 1184 return; 1185 1186 // Skip if the current user is the new value itself. 1187 if (CurUser == NewV) 1188 return; 1189 1190 auto *CurUserI = dyn_cast<Instruction>(CurUser); 1191 if (!CurUserI || CurUserI->getFunction() != F) 1192 return; 1193 1194 // Handle more complex cases like intrinsic that need to be remangled. 1195 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) { 1196 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV)) 1197 return; 1198 } 1199 1200 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) { 1201 if (rewriteIntrinsicOperands(II, V, NewV)) 1202 return; 1203 } 1204 1205 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUserI)) { 1206 // If we can infer that both pointers are in the same addrspace, 1207 // transform e.g. 1208 // %cmp = icmp eq float* %p, %q 1209 // into 1210 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q 1211 1212 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1213 int SrcIdx = U.getOperandNo(); 1214 int OtherIdx = (SrcIdx == 0) ? 1 : 0; 1215 Value *OtherSrc = Cmp->getOperand(OtherIdx); 1216 1217 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) { 1218 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) { 1219 Cmp->setOperand(OtherIdx, OtherNewV); 1220 Cmp->setOperand(SrcIdx, NewV); 1221 return; 1222 } 1223 } 1224 1225 // Even if the type mismatches, we can cast the constant. 1226 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) { 1227 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) { 1228 Cmp->setOperand(SrcIdx, NewV); 1229 Cmp->setOperand(OtherIdx, ConstantExpr::getAddrSpaceCast( 1230 KOtherSrc, NewV->getType())); 1231 return; 1232 } 1233 } 1234 } 1235 1236 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUserI)) { 1237 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1238 if (ASC->getDestAddressSpace() == NewAS) { 1239 ASC->replaceAllUsesWith(NewV); 1240 DeadInstructions.push_back(ASC); 1241 return; 1242 } 1243 } 1244 1245 // Otherwise, replaces the use with flat(NewV). 1246 if (Instruction *VInst = dyn_cast<Instruction>(V)) { 1247 // Don't create a copy of the original addrspacecast. 1248 if (U == V && isa<AddrSpaceCastInst>(V)) 1249 return; 1250 1251 // Insert the addrspacecast after NewV. 1252 BasicBlock::iterator InsertPos; 1253 if (Instruction *NewVInst = dyn_cast<Instruction>(NewV)) 1254 InsertPos = std::next(NewVInst->getIterator()); 1255 else 1256 InsertPos = std::next(VInst->getIterator()); 1257 1258 while (isa<PHINode>(InsertPos)) 1259 ++InsertPos; 1260 // This instruction may contain multiple uses of V, update them all. 1261 CurUser->replaceUsesOfWith( 1262 V, new AddrSpaceCastInst(NewV, V->getType(), "", InsertPos)); 1263 } else { 1264 CurUserI->replaceUsesOfWith( 1265 V, ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), V->getType())); 1266 } 1267 } 1268 1269 bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces( 1270 ArrayRef<WeakTrackingVH> Postorder, 1271 const ValueToAddrSpaceMapTy &InferredAddrSpace, 1272 const PredicatedAddrSpaceMapTy &PredicatedAS) const { 1273 // For each address expression to be modified, creates a clone of it with its 1274 // pointer operands converted to the new address space. Since the pointer 1275 // operands are converted, the clone is naturally in the new address space by 1276 // construction. 1277 ValueToValueMapTy ValueWithNewAddrSpace; 1278 SmallVector<const Use *, 32> PoisonUsesToFix; 1279 for (Value *V : Postorder) { 1280 unsigned NewAddrSpace = InferredAddrSpace.lookup(V); 1281 1282 // In some degenerate cases (e.g. invalid IR in unreachable code), we may 1283 // not even infer the value to have its original address space. 1284 if (NewAddrSpace == UninitializedAddressSpace) 1285 continue; 1286 1287 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) { 1288 Value *New = 1289 cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace, 1290 PredicatedAS, &PoisonUsesToFix); 1291 if (New) 1292 ValueWithNewAddrSpace[V] = New; 1293 } 1294 } 1295 1296 if (ValueWithNewAddrSpace.empty()) 1297 return false; 1298 1299 // Fixes all the poison uses generated by cloneInstructionWithNewAddressSpace. 1300 for (const Use *PoisonUse : PoisonUsesToFix) { 1301 User *V = PoisonUse->getUser(); 1302 User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V)); 1303 if (!NewV) 1304 continue; 1305 1306 unsigned OperandNo = PoisonUse->getOperandNo(); 1307 assert(isa<PoisonValue>(NewV->getOperand(OperandNo))); 1308 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(PoisonUse->get())); 1309 } 1310 1311 SmallVector<Instruction *, 16> DeadInstructions; 1312 ValueToValueMapTy VMap; 1313 ValueMapper VMapper(VMap, RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1314 1315 // Replaces the uses of the old address expressions with the new ones. 1316 for (const WeakTrackingVH &WVH : Postorder) { 1317 assert(WVH && "value was unexpectedly deleted"); 1318 Value *V = WVH; 1319 Value *NewV = ValueWithNewAddrSpace.lookup(V); 1320 if (NewV == nullptr) 1321 continue; 1322 1323 LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n " 1324 << *NewV << '\n'); 1325 1326 if (Constant *C = dyn_cast<Constant>(V)) { 1327 Constant *Replace = 1328 ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), C->getType()); 1329 if (C != Replace) { 1330 LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace 1331 << ": " << *Replace << '\n'); 1332 SmallVector<User *, 16> WorkList; 1333 for (User *U : make_early_inc_range(C->users())) { 1334 if (auto *I = dyn_cast<Instruction>(U)) { 1335 if (I->getFunction() == F) 1336 I->replaceUsesOfWith(C, Replace); 1337 } else { 1338 WorkList.append(U->user_begin(), U->user_end()); 1339 } 1340 } 1341 if (!WorkList.empty()) { 1342 VMap[C] = Replace; 1343 DenseSet<User *> Visited{WorkList.begin(), WorkList.end()}; 1344 while (!WorkList.empty()) { 1345 User *U = WorkList.pop_back_val(); 1346 if (auto *I = dyn_cast<Instruction>(U)) { 1347 if (I->getFunction() == F) 1348 VMapper.remapInstruction(*I); 1349 continue; 1350 } 1351 for (User *U2 : U->users()) 1352 if (Visited.insert(U2).second) 1353 WorkList.push_back(U2); 1354 } 1355 } 1356 V = Replace; 1357 } 1358 } 1359 1360 Value::use_iterator I, E, Next; 1361 for (I = V->use_begin(), E = V->use_end(); I != E;) { 1362 Use &U = *I; 1363 1364 // Some users may see the same pointer operand in multiple operands. Skip 1365 // to the next instruction. 1366 I = skipToNextUser(I, E); 1367 1368 performPointerReplacement(V, NewV, U, ValueWithNewAddrSpace, 1369 DeadInstructions); 1370 } 1371 1372 if (V->use_empty()) { 1373 if (Instruction *I = dyn_cast<Instruction>(V)) 1374 DeadInstructions.push_back(I); 1375 } 1376 } 1377 1378 for (Instruction *I : DeadInstructions) 1379 RecursivelyDeleteTriviallyDeadInstructions(I); 1380 1381 return true; 1382 } 1383 1384 bool InferAddressSpaces::runOnFunction(Function &F) { 1385 if (skipFunction(F)) 1386 return false; 1387 1388 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1389 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 1390 return InferAddressSpacesImpl( 1391 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT, 1392 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F), 1393 FlatAddrSpace) 1394 .run(F); 1395 } 1396 1397 FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) { 1398 return new InferAddressSpaces(AddressSpace); 1399 } 1400 1401 InferAddressSpacesPass::InferAddressSpacesPass() 1402 : FlatAddrSpace(UninitializedAddressSpace) {} 1403 InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace) 1404 : FlatAddrSpace(AddressSpace) {} 1405 1406 PreservedAnalyses InferAddressSpacesPass::run(Function &F, 1407 FunctionAnalysisManager &AM) { 1408 bool Changed = 1409 InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F), 1410 AM.getCachedResult<DominatorTreeAnalysis>(F), 1411 &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace) 1412 .run(F); 1413 if (Changed) { 1414 PreservedAnalyses PA; 1415 PA.preserveSet<CFGAnalyses>(); 1416 PA.preserve<DominatorTreeAnalysis>(); 1417 return PA; 1418 } 1419 return PreservedAnalyses::all(); 1420 } 1421