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