xref: /llvm-project/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp (revision 5d2529f28f93a08c33bb3a22387e669075b66504)
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 "undef" 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 `undef` and fix all the uses of undef later.
82 // For instance, our algorithm first converts %y to
83 //   %y' = phi float addrspace(3)* [ %input, undef ]
84 // Then, it converts %y2 to
85 //   %y2' = getelementptr %y', 1
86 // Finally, it fixes the undef in %y' so that
87 //   %y' = phi float addrspace(3)* [ %input, %y2' ]
88 //
89 //===----------------------------------------------------------------------===//
90 
91 #include "llvm/ADT/ArrayRef.h"
92 #include "llvm/ADT/DenseMap.h"
93 #include "llvm/ADT/DenseSet.h"
94 #include "llvm/ADT/None.h"
95 #include "llvm/ADT/Optional.h"
96 #include "llvm/ADT/SetVector.h"
97 #include "llvm/ADT/SmallVector.h"
98 #include "llvm/Analysis/TargetTransformInfo.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/Function.h"
103 #include "llvm/IR/IRBuilder.h"
104 #include "llvm/IR/InstIterator.h"
105 #include "llvm/IR/Instruction.h"
106 #include "llvm/IR/Instructions.h"
107 #include "llvm/IR/IntrinsicInst.h"
108 #include "llvm/IR/Intrinsics.h"
109 #include "llvm/IR/LLVMContext.h"
110 #include "llvm/IR/Operator.h"
111 #include "llvm/IR/Type.h"
112 #include "llvm/IR/Use.h"
113 #include "llvm/IR/User.h"
114 #include "llvm/IR/Value.h"
115 #include "llvm/IR/ValueHandle.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include "llvm/Transforms/Scalar.h"
124 #include "llvm/Transforms/Utils/Local.h"
125 #include "llvm/Transforms/Utils/ValueMapper.h"
126 #include <cassert>
127 #include <iterator>
128 #include <limits>
129 #include <utility>
130 #include <vector>
131 
132 #define DEBUG_TYPE "infer-address-spaces"
133 
134 using namespace llvm;
135 
136 static cl::opt<bool> AssumeDefaultIsFlatAddressSpace(
137     "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
138     cl::desc("The default address space is assumed as the flat address space. "
139              "This is mainly for test purpose."));
140 
141 static const unsigned UninitializedAddressSpace =
142     std::numeric_limits<unsigned>::max();
143 
144 namespace {
145 
146 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
147 using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
148 
149 /// InferAddressSpaces
150 class InferAddressSpaces : public FunctionPass {
151   const TargetTransformInfo *TTI = nullptr;
152   const DataLayout *DL = nullptr;
153 
154   /// Target specific address space which uses of should be replaced if
155   /// possible.
156   unsigned FlatAddrSpace = 0;
157 
158 public:
159   static char ID;
160 
161   InferAddressSpaces() :
162     FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
163   InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
164 
165   void getAnalysisUsage(AnalysisUsage &AU) const override {
166     AU.setPreservesCFG();
167     AU.addRequired<TargetTransformInfoWrapperPass>();
168   }
169 
170   bool runOnFunction(Function &F) override;
171 
172 private:
173   // Returns the new address space of V if updated; otherwise, returns None.
174   Optional<unsigned>
175   updateAddressSpace(const Value &V,
176                      const ValueToAddrSpaceMapTy &InferredAddrSpace) const;
177 
178   // Tries to infer the specific address space of each address expression in
179   // Postorder.
180   void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
181                           ValueToAddrSpaceMapTy *InferredAddrSpace) const;
182 
183   bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
184 
185   Value *cloneInstructionWithNewAddressSpace(
186       Instruction *I, unsigned NewAddrSpace,
187       const ValueToValueMapTy &ValueWithNewAddrSpace,
188       SmallVectorImpl<const Use *> *UndefUsesToFix) const;
189 
190   // Changes the flat address expressions in function F to point to specific
191   // address spaces if InferredAddrSpace says so. Postorder is the postorder of
192   // all flat expressions in the use-def graph of function F.
193   bool rewriteWithNewAddressSpaces(
194       const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder,
195       const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const;
196 
197   void appendsFlatAddressExpressionToPostorderStack(
198       Value *V, PostorderStackTy &PostorderStack,
199       DenseSet<Value *> &Visited) const;
200 
201   bool rewriteIntrinsicOperands(IntrinsicInst *II,
202                                 Value *OldV, Value *NewV) const;
203   void collectRewritableIntrinsicOperands(IntrinsicInst *II,
204                                           PostorderStackTy &PostorderStack,
205                                           DenseSet<Value *> &Visited) const;
206 
207   std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
208 
209   Value *cloneValueWithNewAddressSpace(
210     Value *V, unsigned NewAddrSpace,
211     const ValueToValueMapTy &ValueWithNewAddrSpace,
212     SmallVectorImpl<const Use *> *UndefUsesToFix) const;
213   unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
214 };
215 
216 } // end anonymous namespace
217 
218 char InferAddressSpaces::ID = 0;
219 
220 namespace llvm {
221 
222 void initializeInferAddressSpacesPass(PassRegistry &);
223 
224 } // end namespace llvm
225 
226 INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
227                 false, false)
228 
229 // Check whether that's no-op pointer bicast using a pair of
230 // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
231 // different address spaces.
232 static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
233                                  const TargetTransformInfo *TTI) {
234   assert(I2P->getOpcode() == Instruction::IntToPtr);
235   auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
236   if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
237     return false;
238   // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
239   // no-op cast. Besides checking both of them are no-op casts, as the
240   // reinterpreted pointer may be used in other pointer arithmetic, we also
241   // need to double-check that through the target-specific hook. That ensures
242   // the underlying target also agrees that's a no-op address space cast and
243   // pointer bits are preserved.
244   // The current IR spec doesn't have clear rules on address space casts,
245   // especially a clear definition for pointer bits in non-default address
246   // spaces. It would be undefined if that pointer is dereferenced after an
247   // invalid reinterpret cast. Also, due to the unclearness for the meaning of
248   // bits in non-default address spaces in the current spec, the pointer
249   // arithmetic may also be undefined after invalid pointer reinterpret cast.
250   // However, as we confirm through the target hooks that it's a no-op
251   // addrspacecast, it doesn't matter since the bits should be the same.
252   return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
253                               I2P->getOperand(0)->getType(), I2P->getType(),
254                               DL) &&
255          CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
256                               P2I->getOperand(0)->getType(), P2I->getType(),
257                               DL) &&
258          TTI->isNoopAddrSpaceCast(
259              P2I->getOperand(0)->getType()->getPointerAddressSpace(),
260              I2P->getType()->getPointerAddressSpace());
261 }
262 
263 // Returns true if V is an address expression.
264 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and
265 // getelementptr operators.
266 static bool isAddressExpression(const Value &V, const DataLayout &DL,
267                                 const TargetTransformInfo *TTI) {
268   const Operator *Op = dyn_cast<Operator>(&V);
269   if (!Op)
270     return false;
271 
272   switch (Op->getOpcode()) {
273   case Instruction::PHI:
274     assert(Op->getType()->isPointerTy());
275     return true;
276   case Instruction::BitCast:
277   case Instruction::AddrSpaceCast:
278   case Instruction::GetElementPtr:
279     return true;
280   case Instruction::Select:
281     return Op->getType()->isPointerTy();
282   case Instruction::Call: {
283     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
284     return II && II->getIntrinsicID() == Intrinsic::ptrmask;
285   }
286   case Instruction::IntToPtr:
287     return isNoopPtrIntCastPair(Op, DL, TTI);
288   default:
289     // That value is an address expression if it has an assumed address space.
290     return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
291   }
292 }
293 
294 // Returns the pointer operands of V.
295 //
296 // Precondition: V is an address expression.
297 static SmallVector<Value *, 2>
298 getPointerOperands(const Value &V, const DataLayout &DL,
299                    const TargetTransformInfo *TTI) {
300   const Operator &Op = cast<Operator>(V);
301   switch (Op.getOpcode()) {
302   case Instruction::PHI: {
303     auto IncomingValues = cast<PHINode>(Op).incoming_values();
304     return SmallVector<Value *, 2>(IncomingValues.begin(),
305                                    IncomingValues.end());
306   }
307   case Instruction::BitCast:
308   case Instruction::AddrSpaceCast:
309   case Instruction::GetElementPtr:
310     return {Op.getOperand(0)};
311   case Instruction::Select:
312     return {Op.getOperand(1), Op.getOperand(2)};
313   case Instruction::Call: {
314     const IntrinsicInst &II = cast<IntrinsicInst>(Op);
315     assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
316            "unexpected intrinsic call");
317     return {II.getArgOperand(0)};
318   }
319   case Instruction::IntToPtr: {
320     assert(isNoopPtrIntCastPair(&Op, DL, TTI));
321     auto *P2I = cast<Operator>(Op.getOperand(0));
322     return {P2I->getOperand(0)};
323   }
324   default:
325     llvm_unreachable("Unexpected instruction type.");
326   }
327 }
328 
329 bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II,
330                                                   Value *OldV,
331                                                   Value *NewV) const {
332   Module *M = II->getParent()->getParent()->getParent();
333 
334   switch (II->getIntrinsicID()) {
335   case Intrinsic::objectsize: {
336     Type *DestTy = II->getType();
337     Type *SrcTy = NewV->getType();
338     Function *NewDecl =
339         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
340     II->setArgOperand(0, NewV);
341     II->setCalledFunction(NewDecl);
342     return true;
343   }
344   case Intrinsic::ptrmask:
345     // This is handled as an address expression, not as a use memory operation.
346     return false;
347   default: {
348     Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
349     if (!Rewrite)
350       return false;
351     if (Rewrite != II)
352       II->replaceAllUsesWith(Rewrite);
353     return true;
354   }
355   }
356 }
357 
358 void InferAddressSpaces::collectRewritableIntrinsicOperands(
359     IntrinsicInst *II, PostorderStackTy &PostorderStack,
360     DenseSet<Value *> &Visited) const {
361   auto IID = II->getIntrinsicID();
362   switch (IID) {
363   case Intrinsic::ptrmask:
364   case Intrinsic::objectsize:
365     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
366                                                  PostorderStack, Visited);
367     break;
368   default:
369     SmallVector<int, 2> OpIndexes;
370     if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
371       for (int Idx : OpIndexes) {
372         appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
373                                                      PostorderStack, Visited);
374       }
375     }
376     break;
377   }
378 }
379 
380 // Returns all flat address expressions in function F. The elements are
381 // If V is an unvisited flat address expression, appends V to PostorderStack
382 // and marks it as visited.
383 void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
384     Value *V, PostorderStackTy &PostorderStack,
385     DenseSet<Value *> &Visited) const {
386   assert(V->getType()->isPointerTy());
387 
388   // Generic addressing expressions may be hidden in nested constant
389   // expressions.
390   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
391     // TODO: Look in non-address parts, like icmp operands.
392     if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
393       PostorderStack.emplace_back(CE, false);
394 
395     return;
396   }
397 
398   if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
399       isAddressExpression(*V, *DL, TTI)) {
400     if (Visited.insert(V).second) {
401       PostorderStack.emplace_back(V, false);
402 
403       Operator *Op = cast<Operator>(V);
404       for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
405         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
406           if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
407             PostorderStack.emplace_back(CE, false);
408         }
409       }
410     }
411   }
412 }
413 
414 // Returns all flat address expressions in function F. The elements are ordered
415 // ordered in postorder.
416 std::vector<WeakTrackingVH>
417 InferAddressSpaces::collectFlatAddressExpressions(Function &F) const {
418   // This function implements a non-recursive postorder traversal of a partial
419   // use-def graph of function F.
420   PostorderStackTy PostorderStack;
421   // The set of visited expressions.
422   DenseSet<Value *> Visited;
423 
424   auto PushPtrOperand = [&](Value *Ptr) {
425     appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
426                                                  Visited);
427   };
428 
429   // Look at operations that may be interesting accelerate by moving to a known
430   // address space. We aim at generating after loads and stores, but pure
431   // addressing calculations may also be faster.
432   for (Instruction &I : instructions(F)) {
433     if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
434       if (!GEP->getType()->isVectorTy())
435         PushPtrOperand(GEP->getPointerOperand());
436     } else if (auto *LI = dyn_cast<LoadInst>(&I))
437       PushPtrOperand(LI->getPointerOperand());
438     else if (auto *SI = dyn_cast<StoreInst>(&I))
439       PushPtrOperand(SI->getPointerOperand());
440     else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
441       PushPtrOperand(RMW->getPointerOperand());
442     else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
443       PushPtrOperand(CmpX->getPointerOperand());
444     else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
445       // For memset/memcpy/memmove, any pointer operand can be replaced.
446       PushPtrOperand(MI->getRawDest());
447 
448       // Handle 2nd operand for memcpy/memmove.
449       if (auto *MTI = dyn_cast<MemTransferInst>(MI))
450         PushPtrOperand(MTI->getRawSource());
451     } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
452       collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
453     else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
454       // FIXME: Handle vectors of pointers
455       if (Cmp->getOperand(0)->getType()->isPointerTy()) {
456         PushPtrOperand(Cmp->getOperand(0));
457         PushPtrOperand(Cmp->getOperand(1));
458       }
459     } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
460       if (!ASC->getType()->isVectorTy())
461         PushPtrOperand(ASC->getPointerOperand());
462     } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
463       if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
464         PushPtrOperand(
465             cast<PtrToIntInst>(I2P->getOperand(0))->getPointerOperand());
466     }
467   }
468 
469   std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
470   while (!PostorderStack.empty()) {
471     Value *TopVal = PostorderStack.back().getPointer();
472     // If the operands of the expression on the top are already explored,
473     // adds that expression to the resultant postorder.
474     if (PostorderStack.back().getInt()) {
475       if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
476         Postorder.push_back(TopVal);
477       PostorderStack.pop_back();
478       continue;
479     }
480     // Otherwise, adds its operands to the stack and explores them.
481     PostorderStack.back().setInt(true);
482     // Skip values with an assumed address space.
483     if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
484       for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
485         appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
486                                                      Visited);
487       }
488     }
489   }
490   return Postorder;
491 }
492 
493 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
494 // of OperandUse.get() in the new address space. If the clone is not ready yet,
495 // returns an undef in the new address space as a placeholder.
496 static Value *operandWithNewAddressSpaceOrCreateUndef(
497     const Use &OperandUse, unsigned NewAddrSpace,
498     const ValueToValueMapTy &ValueWithNewAddrSpace,
499     SmallVectorImpl<const Use *> *UndefUsesToFix) {
500   Value *Operand = OperandUse.get();
501 
502   Type *NewPtrTy =
503       Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
504 
505   if (Constant *C = dyn_cast<Constant>(Operand))
506     return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
507 
508   if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
509     return NewOperand;
510 
511   UndefUsesToFix->push_back(&OperandUse);
512   return UndefValue::get(NewPtrTy);
513 }
514 
515 // Returns a clone of `I` with its operands converted to those specified in
516 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
517 // operand whose address space needs to be modified might not exist in
518 // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
519 // adds that operand use to UndefUsesToFix so that caller can fix them later.
520 //
521 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
522 // from a pointer whose type already matches. Therefore, this function returns a
523 // Value* instead of an Instruction*.
524 //
525 // This may also return nullptr in the case the instruction could not be
526 // rewritten.
527 Value *InferAddressSpaces::cloneInstructionWithNewAddressSpace(
528     Instruction *I, unsigned NewAddrSpace,
529     const ValueToValueMapTy &ValueWithNewAddrSpace,
530     SmallVectorImpl<const Use *> *UndefUsesToFix) const {
531   Type *NewPtrType =
532       I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
533 
534   if (I->getOpcode() == Instruction::AddrSpaceCast) {
535     Value *Src = I->getOperand(0);
536     // Because `I` is flat, the source address space must be specific.
537     // Therefore, the inferred address space must be the source space, according
538     // to our algorithm.
539     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
540     if (Src->getType() != NewPtrType)
541       return new BitCastInst(Src, NewPtrType);
542     return Src;
543   }
544 
545   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
546     // Technically the intrinsic ID is a pointer typed argument, so specially
547     // handle calls early.
548     assert(II->getIntrinsicID() == Intrinsic::ptrmask);
549     Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef(
550         II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
551         UndefUsesToFix);
552     Value *Rewrite =
553         TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
554     if (Rewrite) {
555       assert(Rewrite != II && "cannot modify this pointer operation in place");
556       return Rewrite;
557     }
558 
559     return nullptr;
560   }
561 
562   unsigned AS = TTI->getAssumedAddrSpace(I);
563   if (AS != UninitializedAddressSpace) {
564     // For the assumed address space, insert an `addrspacecast` to make that
565     // explicit.
566     auto *NewPtrTy = I->getType()->getPointerElementType()->getPointerTo(AS);
567     auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
568     NewI->insertAfter(I);
569     return NewI;
570   }
571 
572   // Computes the converted pointer operands.
573   SmallVector<Value *, 4> NewPointerOperands;
574   for (const Use &OperandUse : I->operands()) {
575     if (!OperandUse.get()->getType()->isPointerTy())
576       NewPointerOperands.push_back(nullptr);
577     else
578       NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
579                                      OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
580   }
581 
582   switch (I->getOpcode()) {
583   case Instruction::BitCast:
584     return new BitCastInst(NewPointerOperands[0], NewPtrType);
585   case Instruction::PHI: {
586     assert(I->getType()->isPointerTy());
587     PHINode *PHI = cast<PHINode>(I);
588     PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
589     for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
590       unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
591       NewPHI->addIncoming(NewPointerOperands[OperandNo],
592                           PHI->getIncomingBlock(Index));
593     }
594     return NewPHI;
595   }
596   case Instruction::GetElementPtr: {
597     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
598     GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
599         GEP->getSourceElementType(), NewPointerOperands[0],
600         SmallVector<Value *, 4>(GEP->indices()));
601     NewGEP->setIsInBounds(GEP->isInBounds());
602     return NewGEP;
603   }
604   case Instruction::Select:
605     assert(I->getType()->isPointerTy());
606     return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
607                               NewPointerOperands[2], "", nullptr, I);
608   case Instruction::IntToPtr: {
609     assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
610     Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
611     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
612     if (Src->getType() != NewPtrType)
613       return new BitCastInst(Src, NewPtrType);
614     return Src;
615   }
616   default:
617     llvm_unreachable("Unexpected opcode");
618   }
619 }
620 
621 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
622 // constant expression `CE` with its operands replaced as specified in
623 // ValueWithNewAddrSpace.
624 static Value *cloneConstantExprWithNewAddressSpace(
625     ConstantExpr *CE, unsigned NewAddrSpace,
626     const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
627     const TargetTransformInfo *TTI) {
628   Type *TargetType =
629     CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
630 
631   if (CE->getOpcode() == Instruction::AddrSpaceCast) {
632     // Because CE 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(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
636            NewAddrSpace);
637     return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
638   }
639 
640   if (CE->getOpcode() == Instruction::BitCast) {
641     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
642       return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
643     return ConstantExpr::getAddrSpaceCast(CE, TargetType);
644   }
645 
646   if (CE->getOpcode() == Instruction::Select) {
647     Constant *Src0 = CE->getOperand(1);
648     Constant *Src1 = CE->getOperand(2);
649     if (Src0->getType()->getPointerAddressSpace() ==
650         Src1->getType()->getPointerAddressSpace()) {
651 
652       return ConstantExpr::getSelect(
653           CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
654           ConstantExpr::getAddrSpaceCast(Src1, TargetType));
655     }
656   }
657 
658   if (CE->getOpcode() == Instruction::IntToPtr) {
659     assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
660     Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
661     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
662     return ConstantExpr::getBitCast(Src, TargetType);
663   }
664 
665   // Computes the operands of the new constant expression.
666   bool IsNew = false;
667   SmallVector<Constant *, 4> NewOperands;
668   for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
669     Constant *Operand = CE->getOperand(Index);
670     // If the address space of `Operand` needs to be modified, the new operand
671     // with the new address space should already be in ValueWithNewAddrSpace
672     // because (1) the constant expressions we consider (i.e. addrspacecast,
673     // bitcast, and getelementptr) do not incur cycles in the data flow graph
674     // and (2) this function is called on constant expressions in postorder.
675     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
676       IsNew = true;
677       NewOperands.push_back(cast<Constant>(NewOperand));
678       continue;
679     }
680     if (auto CExpr = dyn_cast<ConstantExpr>(Operand))
681       if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
682               CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
683         IsNew = true;
684         NewOperands.push_back(cast<Constant>(NewOperand));
685         continue;
686       }
687     // Otherwise, reuses the old operand.
688     NewOperands.push_back(Operand);
689   }
690 
691   // If !IsNew, we will replace the Value with itself. However, replaced values
692   // are assumed to wrapped in a addrspace cast later so drop it now.
693   if (!IsNew)
694     return nullptr;
695 
696   if (CE->getOpcode() == Instruction::GetElementPtr) {
697     // Needs to specify the source type while constructing a getelementptr
698     // constant expression.
699     return CE->getWithOperands(
700       NewOperands, TargetType, /*OnlyIfReduced=*/false,
701       NewOperands[0]->getType()->getPointerElementType());
702   }
703 
704   return CE->getWithOperands(NewOperands, TargetType);
705 }
706 
707 // Returns a clone of the value `V`, with its operands replaced as specified in
708 // ValueWithNewAddrSpace. This function is called on every flat address
709 // expression whose address space needs to be modified, in postorder.
710 //
711 // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
712 Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
713   Value *V, unsigned NewAddrSpace,
714   const ValueToValueMapTy &ValueWithNewAddrSpace,
715   SmallVectorImpl<const Use *> *UndefUsesToFix) const {
716   // All values in Postorder are flat address expressions.
717   assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
718          isAddressExpression(*V, *DL, TTI));
719 
720   if (Instruction *I = dyn_cast<Instruction>(V)) {
721     Value *NewV = cloneInstructionWithNewAddressSpace(
722       I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
723     if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
724       if (NewI->getParent() == nullptr) {
725         NewI->insertBefore(I);
726         NewI->takeName(I);
727       }
728     }
729     return NewV;
730   }
731 
732   return cloneConstantExprWithNewAddressSpace(
733       cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
734 }
735 
736 // Defines the join operation on the address space lattice (see the file header
737 // comments).
738 unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1,
739                                                unsigned AS2) const {
740   if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
741     return FlatAddrSpace;
742 
743   if (AS1 == UninitializedAddressSpace)
744     return AS2;
745   if (AS2 == UninitializedAddressSpace)
746     return AS1;
747 
748   // The join of two different specific address spaces is flat.
749   return (AS1 == AS2) ? AS1 : FlatAddrSpace;
750 }
751 
752 bool InferAddressSpaces::runOnFunction(Function &F) {
753   if (skipFunction(F))
754     return false;
755 
756   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
757   DL = &F.getParent()->getDataLayout();
758 
759   if (AssumeDefaultIsFlatAddressSpace)
760     FlatAddrSpace = 0;
761 
762   if (FlatAddrSpace == UninitializedAddressSpace) {
763     FlatAddrSpace = TTI->getFlatAddressSpace();
764     if (FlatAddrSpace == UninitializedAddressSpace)
765       return false;
766   }
767 
768   // Collects all flat address expressions in postorder.
769   std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
770 
771   // Runs a data-flow analysis to refine the address spaces of every expression
772   // in Postorder.
773   ValueToAddrSpaceMapTy InferredAddrSpace;
774   inferAddressSpaces(Postorder, &InferredAddrSpace);
775 
776   // Changes the address spaces of the flat address expressions who are inferred
777   // to point to a specific address space.
778   return rewriteWithNewAddressSpaces(*TTI, Postorder, InferredAddrSpace, &F);
779 }
780 
781 // Constants need to be tracked through RAUW to handle cases with nested
782 // constant expressions, so wrap values in WeakTrackingVH.
783 void InferAddressSpaces::inferAddressSpaces(
784     ArrayRef<WeakTrackingVH> Postorder,
785     ValueToAddrSpaceMapTy *InferredAddrSpace) const {
786   SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
787   // Initially, all expressions are in the uninitialized address space.
788   for (Value *V : Postorder)
789     (*InferredAddrSpace)[V] = UninitializedAddressSpace;
790 
791   while (!Worklist.empty()) {
792     Value *V = Worklist.pop_back_val();
793 
794     // Tries to update the address space of the stack top according to the
795     // address spaces of its operands.
796     LLVM_DEBUG(dbgs() << "Updating the address space of\n  " << *V << '\n');
797     Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace);
798     if (!NewAS.hasValue())
799       continue;
800     // If any updates are made, grabs its users to the worklist because
801     // their address spaces can also be possibly updated.
802     LLVM_DEBUG(dbgs() << "  to " << NewAS.getValue() << '\n');
803     (*InferredAddrSpace)[V] = NewAS.getValue();
804 
805     for (Value *User : V->users()) {
806       // Skip if User is already in the worklist.
807       if (Worklist.count(User))
808         continue;
809 
810       auto Pos = InferredAddrSpace->find(User);
811       // Our algorithm only updates the address spaces of flat address
812       // expressions, which are those in InferredAddrSpace.
813       if (Pos == InferredAddrSpace->end())
814         continue;
815 
816       // Function updateAddressSpace moves the address space down a lattice
817       // path. Therefore, nothing to do if User is already inferred as flat (the
818       // bottom element in the lattice).
819       if (Pos->second == FlatAddrSpace)
820         continue;
821 
822       Worklist.insert(User);
823     }
824   }
825 }
826 
827 Optional<unsigned> InferAddressSpaces::updateAddressSpace(
828     const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const {
829   assert(InferredAddrSpace.count(&V));
830 
831   // The new inferred address space equals the join of the address spaces
832   // of all its pointer operands.
833   unsigned NewAS = UninitializedAddressSpace;
834 
835   const Operator &Op = cast<Operator>(V);
836   if (Op.getOpcode() == Instruction::Select) {
837     Value *Src0 = Op.getOperand(1);
838     Value *Src1 = Op.getOperand(2);
839 
840     auto I = InferredAddrSpace.find(Src0);
841     unsigned Src0AS = (I != InferredAddrSpace.end()) ?
842       I->second : Src0->getType()->getPointerAddressSpace();
843 
844     auto J = InferredAddrSpace.find(Src1);
845     unsigned Src1AS = (J != InferredAddrSpace.end()) ?
846       J->second : Src1->getType()->getPointerAddressSpace();
847 
848     auto *C0 = dyn_cast<Constant>(Src0);
849     auto *C1 = dyn_cast<Constant>(Src1);
850 
851     // If one of the inputs is a constant, we may be able to do a constant
852     // addrspacecast of it. Defer inferring the address space until the input
853     // address space is known.
854     if ((C1 && Src0AS == UninitializedAddressSpace) ||
855         (C0 && Src1AS == UninitializedAddressSpace))
856       return None;
857 
858     if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
859       NewAS = Src1AS;
860     else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
861       NewAS = Src0AS;
862     else
863       NewAS = joinAddressSpaces(Src0AS, Src1AS);
864   } else {
865     unsigned AS = TTI->getAssumedAddrSpace(&V);
866     if (AS != UninitializedAddressSpace) {
867       // Use the assumed address space directly.
868       NewAS = AS;
869     } else {
870       // Otherwise, infer the address space from its pointer operands.
871       for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
872         auto I = InferredAddrSpace.find(PtrOperand);
873         unsigned OperandAS =
874             I != InferredAddrSpace.end()
875                 ? I->second
876                 : PtrOperand->getType()->getPointerAddressSpace();
877 
878         // join(flat, *) = flat. So we can break if NewAS is already flat.
879         NewAS = joinAddressSpaces(NewAS, OperandAS);
880         if (NewAS == FlatAddrSpace)
881           break;
882       }
883     }
884   }
885 
886   unsigned OldAS = InferredAddrSpace.lookup(&V);
887   assert(OldAS != FlatAddrSpace);
888   if (OldAS == NewAS)
889     return None;
890   return NewAS;
891 }
892 
893 /// \p returns true if \p U is the pointer operand of a memory instruction with
894 /// a single pointer operand that can have its address space changed by simply
895 /// mutating the use to a new value. If the memory instruction is volatile,
896 /// return true only if the target allows the memory instruction to be volatile
897 /// in the new address space.
898 static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
899                                              Use &U, unsigned AddrSpace) {
900   User *Inst = U.getUser();
901   unsigned OpNo = U.getOperandNo();
902   bool VolatileIsAllowed = false;
903   if (auto *I = dyn_cast<Instruction>(Inst))
904     VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
905 
906   if (auto *LI = dyn_cast<LoadInst>(Inst))
907     return OpNo == LoadInst::getPointerOperandIndex() &&
908            (VolatileIsAllowed || !LI->isVolatile());
909 
910   if (auto *SI = dyn_cast<StoreInst>(Inst))
911     return OpNo == StoreInst::getPointerOperandIndex() &&
912            (VolatileIsAllowed || !SI->isVolatile());
913 
914   if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
915     return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
916            (VolatileIsAllowed || !RMW->isVolatile());
917 
918   if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
919     return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
920            (VolatileIsAllowed || !CmpX->isVolatile());
921 
922   return false;
923 }
924 
925 /// Update memory intrinsic uses that require more complex processing than
926 /// simple memory instructions. Thse require re-mangling and may have multiple
927 /// pointer operands.
928 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
929                                      Value *NewV) {
930   IRBuilder<> B(MI);
931   MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
932   MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
933   MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
934 
935   if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
936     B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(),
937                    MaybeAlign(MSI->getDestAlignment()),
938                    false, // isVolatile
939                    TBAA, ScopeMD, NoAliasMD);
940   } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
941     Value *Src = MTI->getRawSource();
942     Value *Dest = MTI->getRawDest();
943 
944     // Be careful in case this is a self-to-self copy.
945     if (Src == OldV)
946       Src = NewV;
947 
948     if (Dest == OldV)
949       Dest = NewV;
950 
951     if (isa<MemCpyInst>(MTI)) {
952       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
953       B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
954                      MTI->getLength(),
955                      false, // isVolatile
956                      TBAA, TBAAStruct, ScopeMD, NoAliasMD);
957     } else {
958       assert(isa<MemMoveInst>(MTI));
959       B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
960                       MTI->getLength(),
961                       false, // isVolatile
962                       TBAA, ScopeMD, NoAliasMD);
963     }
964   } else
965     llvm_unreachable("unhandled MemIntrinsic");
966 
967   MI->eraseFromParent();
968   return true;
969 }
970 
971 // \p returns true if it is OK to change the address space of constant \p C with
972 // a ConstantExpr addrspacecast.
973 bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const {
974   assert(NewAS != UninitializedAddressSpace);
975 
976   unsigned SrcAS = C->getType()->getPointerAddressSpace();
977   if (SrcAS == NewAS || isa<UndefValue>(C))
978     return true;
979 
980   // Prevent illegal casts between different non-flat address spaces.
981   if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
982     return false;
983 
984   if (isa<ConstantPointerNull>(C))
985     return true;
986 
987   if (auto *Op = dyn_cast<Operator>(C)) {
988     // If we already have a constant addrspacecast, it should be safe to cast it
989     // off.
990     if (Op->getOpcode() == Instruction::AddrSpaceCast)
991       return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
992 
993     if (Op->getOpcode() == Instruction::IntToPtr &&
994         Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
995       return true;
996   }
997 
998   return false;
999 }
1000 
1001 static Value::use_iterator skipToNextUser(Value::use_iterator I,
1002                                           Value::use_iterator End) {
1003   User *CurUser = I->getUser();
1004   ++I;
1005 
1006   while (I != End && I->getUser() == CurUser)
1007     ++I;
1008 
1009   return I;
1010 }
1011 
1012 bool InferAddressSpaces::rewriteWithNewAddressSpaces(
1013     const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder,
1014     const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const {
1015   // For each address expression to be modified, creates a clone of it with its
1016   // pointer operands converted to the new address space. Since the pointer
1017   // operands are converted, the clone is naturally in the new address space by
1018   // construction.
1019   ValueToValueMapTy ValueWithNewAddrSpace;
1020   SmallVector<const Use *, 32> UndefUsesToFix;
1021   for (Value* V : Postorder) {
1022     unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
1023 
1024     // In some degenerate cases (e.g. invalid IR in unreachable code), we may
1025     // not even infer the value to have its original address space.
1026     if (NewAddrSpace == UninitializedAddressSpace)
1027       continue;
1028 
1029     if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1030       Value *New = cloneValueWithNewAddressSpace(
1031           V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
1032       if (New)
1033         ValueWithNewAddrSpace[V] = New;
1034     }
1035   }
1036 
1037   if (ValueWithNewAddrSpace.empty())
1038     return false;
1039 
1040   // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
1041   for (const Use *UndefUse : UndefUsesToFix) {
1042     User *V = UndefUse->getUser();
1043     User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1044     if (!NewV)
1045       continue;
1046 
1047     unsigned OperandNo = UndefUse->getOperandNo();
1048     assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
1049     NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
1050   }
1051 
1052   SmallVector<Instruction *, 16> DeadInstructions;
1053 
1054   // Replaces the uses of the old address expressions with the new ones.
1055   for (const WeakTrackingVH &WVH : Postorder) {
1056     assert(WVH && "value was unexpectedly deleted");
1057     Value *V = WVH;
1058     Value *NewV = ValueWithNewAddrSpace.lookup(V);
1059     if (NewV == nullptr)
1060       continue;
1061 
1062     LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n  with\n  "
1063                       << *NewV << '\n');
1064 
1065     if (Constant *C = dyn_cast<Constant>(V)) {
1066       Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1067                                                          C->getType());
1068       if (C != Replace) {
1069         LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
1070                           << ": " << *Replace << '\n');
1071         C->replaceAllUsesWith(Replace);
1072         V = Replace;
1073       }
1074     }
1075 
1076     Value::use_iterator I, E, Next;
1077     for (I = V->use_begin(), E = V->use_end(); I != E; ) {
1078       Use &U = *I;
1079 
1080       // Some users may see the same pointer operand in multiple operands. Skip
1081       // to the next instruction.
1082       I = skipToNextUser(I, E);
1083 
1084       if (isSimplePointerUseValidToReplace(
1085               TTI, U, V->getType()->getPointerAddressSpace())) {
1086         // If V is used as the pointer operand of a compatible memory operation,
1087         // sets the pointer operand to NewV. This replacement does not change
1088         // the element type, so the resultant load/store is still valid.
1089         U.set(NewV);
1090         continue;
1091       }
1092 
1093       User *CurUser = U.getUser();
1094       // Skip if the current user is the new value itself.
1095       if (CurUser == NewV)
1096         continue;
1097       // Handle more complex cases like intrinsic that need to be remangled.
1098       if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
1099         if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
1100           continue;
1101       }
1102 
1103       if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
1104         if (rewriteIntrinsicOperands(II, V, NewV))
1105           continue;
1106       }
1107 
1108       if (isa<Instruction>(CurUser)) {
1109         if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
1110           // If we can infer that both pointers are in the same addrspace,
1111           // transform e.g.
1112           //   %cmp = icmp eq float* %p, %q
1113           // into
1114           //   %cmp = icmp eq float addrspace(3)* %new_p, %new_q
1115 
1116           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1117           int SrcIdx = U.getOperandNo();
1118           int OtherIdx = (SrcIdx == 0) ? 1 : 0;
1119           Value *OtherSrc = Cmp->getOperand(OtherIdx);
1120 
1121           if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
1122             if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
1123               Cmp->setOperand(OtherIdx, OtherNewV);
1124               Cmp->setOperand(SrcIdx, NewV);
1125               continue;
1126             }
1127           }
1128 
1129           // Even if the type mismatches, we can cast the constant.
1130           if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
1131             if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
1132               Cmp->setOperand(SrcIdx, NewV);
1133               Cmp->setOperand(OtherIdx,
1134                 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
1135               continue;
1136             }
1137           }
1138         }
1139 
1140         if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
1141           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1142           if (ASC->getDestAddressSpace() == NewAS) {
1143             if (ASC->getType()->getPointerElementType() !=
1144                 NewV->getType()->getPointerElementType()) {
1145               NewV = CastInst::Create(Instruction::BitCast, NewV,
1146                                       ASC->getType(), "", ASC);
1147             }
1148             ASC->replaceAllUsesWith(NewV);
1149             DeadInstructions.push_back(ASC);
1150             continue;
1151           }
1152         }
1153 
1154         // Otherwise, replaces the use with flat(NewV).
1155         if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1156           // Don't create a copy of the original addrspacecast.
1157           if (U == V && isa<AddrSpaceCastInst>(V))
1158             continue;
1159 
1160           BasicBlock::iterator InsertPos = std::next(Inst->getIterator());
1161           while (isa<PHINode>(InsertPos))
1162             ++InsertPos;
1163           U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
1164         } else {
1165           U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1166                                                V->getType()));
1167         }
1168       }
1169     }
1170 
1171     if (V->use_empty()) {
1172       if (Instruction *I = dyn_cast<Instruction>(V))
1173         DeadInstructions.push_back(I);
1174     }
1175   }
1176 
1177   for (Instruction *I : DeadInstructions)
1178     RecursivelyDeleteTriviallyDeadInstructions(I);
1179 
1180   return true;
1181 }
1182 
1183 FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
1184   return new InferAddressSpaces(AddressSpace);
1185 }
1186