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