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