blob: a2ce9b4907dee676e46d72c51d21cdb0a73ce621 [file] [log] [blame]
Jingyue Wu13755602016-03-20 20:59:20 +00001//===-- 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//
Jingyue Wu13755602016-03-20 20:59:20 +000090//===----------------------------------------------------------------------===//
91
Matt Arsenault850657a2017-01-31 01:10:58 +000092#include "llvm/Transforms/Scalar.h"
Jingyue Wu13755602016-03-20 20:59:20 +000093#include "llvm/ADT/DenseSet.h"
94#include "llvm/ADT/Optional.h"
95#include "llvm/ADT/SetVector.h"
Matt Arsenault42b64782017-01-30 23:02:12 +000096#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wu13755602016-03-20 20:59:20 +000097#include "llvm/IR/Function.h"
98#include "llvm/IR/InstIterator.h"
99#include "llvm/IR/Instructions.h"
100#include "llvm/IR/Operator.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000101#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
Matt Arsenault850657a2017-01-31 01:10:58 +0000106#define DEBUG_TYPE "infer-address-spaces"
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000107
Jingyue Wu13755602016-03-20 20:59:20 +0000108using namespace llvm;
109
110namespace {
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000111static const unsigned UninitializedAddressSpace = ~0u;
Jingyue Wu13755602016-03-20 20:59:20 +0000112
113using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
114
Matt Arsenault850657a2017-01-31 01:10:58 +0000115/// \brief InferAddressSpaces
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000116class InferAddressSpaces : public FunctionPass {
Matt Arsenault42b64782017-01-30 23:02:12 +0000117 /// Target specific address space which uses of should be replaced if
118 /// possible.
119 unsigned FlatAddrSpace;
120
Jingyue Wu13755602016-03-20 20:59:20 +0000121public:
122 static char ID;
123
Matt Arsenault850657a2017-01-31 01:10:58 +0000124 InferAddressSpaces() : FunctionPass(ID) {}
Jingyue Wu13755602016-03-20 20:59:20 +0000125
Matt Arsenault32b96002017-01-27 17:30:39 +0000126 void getAnalysisUsage(AnalysisUsage &AU) const override {
127 AU.setPreservesCFG();
Matt Arsenault42b64782017-01-30 23:02:12 +0000128 AU.addRequired<TargetTransformInfoWrapperPass>();
Matt Arsenault32b96002017-01-27 17:30:39 +0000129 }
130
Jingyue Wu13755602016-03-20 20:59:20 +0000131 bool runOnFunction(Function &F) override;
132
133private:
134 // Returns the new address space of V if updated; otherwise, returns None.
135 Optional<unsigned>
136 updateAddressSpace(const Value &V,
Matt Arsenault42b64782017-01-30 23:02:12 +0000137 const ValueToAddrSpaceMapTy &InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000138
139 // Tries to infer the specific address space of each address expression in
140 // Postorder.
141 void inferAddressSpaces(const std::vector<Value *> &Postorder,
Matt Arsenault42b64782017-01-30 23:02:12 +0000142 ValueToAddrSpaceMapTy *InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000143
Matt Arsenault72f259b2017-01-31 02:17:32 +0000144 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
145
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000146 // Changes the flat address expressions in function F to point to specific
Jingyue Wu13755602016-03-20 20:59:20 +0000147 // address spaces if InferredAddrSpace says so. Postorder is the postorder of
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000148 // all flat expressions in the use-def graph of function F.
Jingyue Wu13755602016-03-20 20:59:20 +0000149 bool
150 rewriteWithNewAddressSpaces(const std::vector<Value *> &Postorder,
151 const ValueToAddrSpaceMapTy &InferredAddrSpace,
Matt Arsenault42b64782017-01-30 23:02:12 +0000152 Function *F) const;
153
154 void appendsFlatAddressExpressionToPostorderStack(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000155 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
156 DenseSet<Value *> &Visited) const;
Matt Arsenault42b64782017-01-30 23:02:12 +0000157
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000158 bool rewriteIntrinsicOperands(IntrinsicInst *II,
159 Value *OldV, Value *NewV) const;
160 void collectRewritableIntrinsicOperands(
161 IntrinsicInst *II,
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000162 std::vector<std::pair<Value *, bool>> &PostorderStack,
163 DenseSet<Value *> &Visited) const;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000164
Matt Arsenault42b64782017-01-30 23:02:12 +0000165 std::vector<Value *> collectFlatAddressExpressions(Function &F) const;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000166
Matt Arsenault42b64782017-01-30 23:02:12 +0000167 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;
Jingyue Wu13755602016-03-20 20:59:20 +0000172};
173} // end anonymous namespace
174
Matt Arsenault850657a2017-01-31 01:10:58 +0000175char InferAddressSpaces::ID = 0;
Jingyue Wu13755602016-03-20 20:59:20 +0000176
177namespace llvm {
Matt Arsenault850657a2017-01-31 01:10:58 +0000178void initializeInferAddressSpacesPass(PassRegistry &);
Jingyue Wu13755602016-03-20 20:59:20 +0000179}
Matt Arsenault850657a2017-01-31 01:10:58 +0000180
181INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
Jingyue Wu13755602016-03-20 20:59:20 +0000182 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.
187static 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:
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000196 case Instruction::Select:
Jingyue Wu13755602016-03-20 20:59:20 +0000197 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.
206static SmallVector<Value *, 2> getPointerOperands(const Value &V) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000207 const Operator &Op = cast<Operator>(V);
Jingyue Wu13755602016-03-20 20:59:20 +0000208 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)};
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000218 case Instruction::Select:
219 return {Op.getOperand(1), Op.getOperand(2)};
Jingyue Wu13755602016-03-20 20:59:20 +0000220 default:
221 llvm_unreachable("Unexpected instruction type.");
222 }
223}
224
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000225// TODO: Move logic to TTI?
226bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II,
227 Value *OldV,
228 Value *NewV) const {
229 Module *M = II->getParent()->getParent()->getParent();
230
231 switch (II->getIntrinsicID()) {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000232 case Intrinsic::amdgcn_atomic_inc:
Matt Arsenault79f837c2017-03-30 22:21:40 +0000233 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: {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000241 Type *DestTy = II->getType();
242 Type *SrcTy = NewV->getType();
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000243 Function *NewDecl =
244 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000245 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?
255void InferAddressSpaces::collectRewritableIntrinsicOperands(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000256 IntrinsicInst *II, std::vector<std::pair<Value *, bool>> &PostorderStack,
257 DenseSet<Value *> &Visited) const {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000258 switch (II->getIntrinsicID()) {
259 case Intrinsic::objectsize:
260 case Intrinsic::amdgcn_atomic_inc:
261 case Intrinsic::amdgcn_atomic_dec:
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000262 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
263 PostorderStack, Visited);
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000264 break;
265 default:
266 break;
267 }
268}
269
270// Returns all flat address expressions in function F. The elements are
Matt Arsenault42b64782017-01-30 23:02:12 +0000271// If V is an unvisited flat address expression, appends V to PostorderStack
Jingyue Wu13755602016-03-20 20:59:20 +0000272// and marks it as visited.
Matt Arsenault850657a2017-01-31 01:10:58 +0000273void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000274 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
275 DenseSet<Value *> &Visited) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000276 assert(V->getType()->isPointerTy());
277 if (isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000278 V->getType()->getPointerAddressSpace() == FlatAddrSpace) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000279 if (Visited.insert(V).second)
280 PostorderStack.push_back(std::make_pair(V, false));
Jingyue Wu13755602016-03-20 20:59:20 +0000281 }
282}
283
Matt Arsenault42b64782017-01-30 23:02:12 +0000284// Returns all flat address expressions in function F. The elements are ordered
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000285// ordered in postorder.
Matt Arsenault42b64782017-01-30 23:02:12 +0000286std::vector<Value *>
Matt Arsenault850657a2017-01-31 01:10:58 +0000287InferAddressSpaces::collectFlatAddressExpressions(Function &F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000288 // This function implements a non-recursive postorder traversal of a partial
289 // use-def graph of function F.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000290 std::vector<std::pair<Value *, bool>> PostorderStack;
Jingyue Wu13755602016-03-20 20:59:20 +0000291 // The set of visited expressions.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000292 DenseSet<Value *> Visited;
Matt Arsenault6c907a92017-01-31 01:40:38 +0000293
294 auto PushPtrOperand = [&](Value *Ptr) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000295 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
296 Visited);
Matt Arsenault6c907a92017-01-31 01:40:38 +0000297 };
298
Matt Arsenaultc07bda72017-04-21 21:35:04 +0000299 // Look at operations that may be interesting accelerate by moving to a known
300 // address space. We aim at generating after loads and stores, but pure
301 // addressing calculations may also be faster.
Jingyue Wu13755602016-03-20 20:59:20 +0000302 for (Instruction &I : instructions(F)) {
Matt Arsenaultc07bda72017-04-21 21:35:04 +0000303 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
304 if (!GEP->getType()->isVectorTy())
305 PushPtrOperand(GEP->getPointerOperand());
306 } else if (auto *LI = dyn_cast<LoadInst>(&I))
Matt Arsenault6c907a92017-01-31 01:40:38 +0000307 PushPtrOperand(LI->getPointerOperand());
308 else if (auto *SI = dyn_cast<StoreInst>(&I))
309 PushPtrOperand(SI->getPointerOperand());
310 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
311 PushPtrOperand(RMW->getPointerOperand());
312 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
313 PushPtrOperand(CmpX->getPointerOperand());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000314 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
315 // For memset/memcpy/memmove, any pointer operand can be replaced.
316 PushPtrOperand(MI->getRawDest());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000317
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000318 // Handle 2nd operand for memcpy/memmove.
319 if (auto *MTI = dyn_cast<MemTransferInst>(MI))
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000320 PushPtrOperand(MTI->getRawSource());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000321 } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000322 collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
Matt Arsenault72f259b2017-01-31 02:17:32 +0000323 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
324 // FIXME: Handle vectors of pointers
325 if (Cmp->getOperand(0)->getType()->isPointerTy()) {
326 PushPtrOperand(Cmp->getOperand(0));
327 PushPtrOperand(Cmp->getOperand(1));
328 }
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000329 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
330 if (!ASC->getType()->isVectorTy())
331 PushPtrOperand(ASC->getPointerOperand());
Matt Arsenault72f259b2017-01-31 02:17:32 +0000332 }
Jingyue Wu13755602016-03-20 20:59:20 +0000333 }
334
335 std::vector<Value *> Postorder; // The resultant postorder.
336 while (!PostorderStack.empty()) {
337 // If the operands of the expression on the top are already explored,
338 // adds that expression to the resultant postorder.
339 if (PostorderStack.back().second) {
340 Postorder.push_back(PostorderStack.back().first);
341 PostorderStack.pop_back();
342 continue;
343 }
344 // Otherwise, adds its operands to the stack and explores them.
345 PostorderStack.back().second = true;
346 for (Value *PtrOperand : getPointerOperands(*PostorderStack.back().first)) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000347 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
348 Visited);
Jingyue Wu13755602016-03-20 20:59:20 +0000349 }
350 }
351 return Postorder;
352}
353
354// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
355// of OperandUse.get() in the new address space. If the clone is not ready yet,
356// returns an undef in the new address space as a placeholder.
357static Value *operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000358 const Use &OperandUse, unsigned NewAddrSpace,
359 const ValueToValueMapTy &ValueWithNewAddrSpace,
360 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000361 Value *Operand = OperandUse.get();
Matt Arsenault30083602017-02-02 03:37:22 +0000362
363 Type *NewPtrTy =
364 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
365
366 if (Constant *C = dyn_cast<Constant>(Operand))
367 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
368
Jingyue Wu13755602016-03-20 20:59:20 +0000369 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
370 return NewOperand;
371
372 UndefUsesToFix->push_back(&OperandUse);
Matt Arsenault30083602017-02-02 03:37:22 +0000373 return UndefValue::get(NewPtrTy);
Jingyue Wu13755602016-03-20 20:59:20 +0000374}
375
376// Returns a clone of `I` with its operands converted to those specified in
377// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
378// operand whose address space needs to be modified might not exist in
379// ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
380// adds that operand use to UndefUsesToFix so that caller can fix them later.
381//
382// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
383// from a pointer whose type already matches. Therefore, this function returns a
384// Value* instead of an Instruction*.
385static Value *cloneInstructionWithNewAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000386 Instruction *I, unsigned NewAddrSpace,
387 const ValueToValueMapTy &ValueWithNewAddrSpace,
388 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000389 Type *NewPtrType =
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000390 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000391
392 if (I->getOpcode() == Instruction::AddrSpaceCast) {
393 Value *Src = I->getOperand(0);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000394 // Because `I` is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000395 // Therefore, the inferred address space must be the source space, according
396 // to our algorithm.
397 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
398 if (Src->getType() != NewPtrType)
399 return new BitCastInst(Src, NewPtrType);
400 return Src;
401 }
402
403 // Computes the converted pointer operands.
404 SmallVector<Value *, 4> NewPointerOperands;
405 for (const Use &OperandUse : I->operands()) {
406 if (!OperandUse.get()->getType()->isPointerTy())
407 NewPointerOperands.push_back(nullptr);
408 else
409 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenault850657a2017-01-31 01:10:58 +0000410 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
Jingyue Wu13755602016-03-20 20:59:20 +0000411 }
412
413 switch (I->getOpcode()) {
414 case Instruction::BitCast:
415 return new BitCastInst(NewPointerOperands[0], NewPtrType);
416 case Instruction::PHI: {
417 assert(I->getType()->isPointerTy());
418 PHINode *PHI = cast<PHINode>(I);
419 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
420 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
421 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
422 NewPHI->addIncoming(NewPointerOperands[OperandNo],
423 PHI->getIncomingBlock(Index));
424 }
425 return NewPHI;
426 }
427 case Instruction::GetElementPtr: {
428 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
429 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000430 GEP->getSourceElementType(), NewPointerOperands[0],
431 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end()));
Jingyue Wu13755602016-03-20 20:59:20 +0000432 NewGEP->setIsInBounds(GEP->isInBounds());
433 return NewGEP;
434 }
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000435 case Instruction::Select: {
436 assert(I->getType()->isPointerTy());
437 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
438 NewPointerOperands[2], "", nullptr, I);
439 }
Jingyue Wu13755602016-03-20 20:59:20 +0000440 default:
441 llvm_unreachable("Unexpected opcode");
442 }
443}
444
445// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
446// constant expression `CE` with its operands replaced as specified in
447// ValueWithNewAddrSpace.
448static Value *cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000449 ConstantExpr *CE, unsigned NewAddrSpace,
450 const ValueToValueMapTy &ValueWithNewAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000451 Type *TargetType =
Matt Arsenault850657a2017-01-31 01:10:58 +0000452 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000453
454 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000455 // Because CE is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000456 // Therefore, the inferred address space must be the source space according
457 // to our algorithm.
458 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
459 NewAddrSpace);
460 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
461 }
462
Matt Arsenaultc18b6772017-02-17 00:32:19 +0000463 if (CE->getOpcode() == Instruction::BitCast) {
464 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
465 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
466 return ConstantExpr::getAddrSpaceCast(CE, TargetType);
467 }
468
Matt Arsenault30083602017-02-02 03:37:22 +0000469 if (CE->getOpcode() == Instruction::Select) {
470 Constant *Src0 = CE->getOperand(1);
471 Constant *Src1 = CE->getOperand(2);
472 if (Src0->getType()->getPointerAddressSpace() ==
473 Src1->getType()->getPointerAddressSpace()) {
474
475 return ConstantExpr::getSelect(
476 CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
477 ConstantExpr::getAddrSpaceCast(Src1, TargetType));
478 }
479 }
480
Jingyue Wu13755602016-03-20 20:59:20 +0000481 // Computes the operands of the new constant expression.
482 SmallVector<Constant *, 4> NewOperands;
483 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
484 Constant *Operand = CE->getOperand(Index);
485 // If the address space of `Operand` needs to be modified, the new operand
486 // with the new address space should already be in ValueWithNewAddrSpace
487 // because (1) the constant expressions we consider (i.e. addrspacecast,
488 // bitcast, and getelementptr) do not incur cycles in the data flow graph
489 // and (2) this function is called on constant expressions in postorder.
490 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
491 NewOperands.push_back(cast<Constant>(NewOperand));
492 } else {
493 // Otherwise, reuses the old operand.
494 NewOperands.push_back(Operand);
495 }
496 }
497
498 if (CE->getOpcode() == Instruction::GetElementPtr) {
499 // Needs to specify the source type while constructing a getelementptr
500 // constant expression.
501 return CE->getWithOperands(
Matt Arsenault850657a2017-01-31 01:10:58 +0000502 NewOperands, TargetType, /*OnlyIfReduced=*/false,
503 NewOperands[0]->getType()->getPointerElementType());
Jingyue Wu13755602016-03-20 20:59:20 +0000504 }
505
506 return CE->getWithOperands(NewOperands, TargetType);
507}
508
509// Returns a clone of the value `V`, with its operands replaced as specified in
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000510// ValueWithNewAddrSpace. This function is called on every flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000511// expression whose address space needs to be modified, in postorder.
512//
513// See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
Matt Arsenault850657a2017-01-31 01:10:58 +0000514Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
Matt Arsenault42b64782017-01-30 23:02:12 +0000515 Value *V, unsigned NewAddrSpace,
516 const ValueToValueMapTy &ValueWithNewAddrSpace,
517 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000518 // All values in Postorder are flat address expressions.
Jingyue Wu13755602016-03-20 20:59:20 +0000519 assert(isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000520 V->getType()->getPointerAddressSpace() == FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000521
522 if (Instruction *I = dyn_cast<Instruction>(V)) {
523 Value *NewV = cloneInstructionWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000524 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000525 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) {
526 if (NewI->getParent() == nullptr) {
527 NewI->insertBefore(I);
528 NewI->takeName(I);
529 }
530 }
531 return NewV;
532 }
533
534 return cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000535 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000536}
537
538// Defines the join operation on the address space lattice (see the file header
539// comments).
Matt Arsenault850657a2017-01-31 01:10:58 +0000540unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1,
541 unsigned AS2) const {
Matt Arsenault42b64782017-01-30 23:02:12 +0000542 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
543 return FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000544
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000545 if (AS1 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000546 return AS2;
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000547 if (AS2 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000548 return AS1;
549
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000550 // The join of two different specific address spaces is flat.
Matt Arsenault42b64782017-01-30 23:02:12 +0000551 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000552}
553
Matt Arsenault850657a2017-01-31 01:10:58 +0000554bool InferAddressSpaces::runOnFunction(Function &F) {
Andrew Kaylor87b10dd2016-04-26 23:44:31 +0000555 if (skipFunction(F))
556 return false;
557
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000558 const TargetTransformInfo &TTI =
559 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Matt Arsenault42b64782017-01-30 23:02:12 +0000560 FlatAddrSpace = TTI.getFlatAddressSpace();
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000561 if (FlatAddrSpace == UninitializedAddressSpace)
Matt Arsenault42b64782017-01-30 23:02:12 +0000562 return false;
563
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000564 // Collects all flat address expressions in postorder.
Matt Arsenault42b64782017-01-30 23:02:12 +0000565 std::vector<Value *> Postorder = collectFlatAddressExpressions(F);
Jingyue Wu13755602016-03-20 20:59:20 +0000566
567 // Runs a data-flow analysis to refine the address spaces of every expression
568 // in Postorder.
569 ValueToAddrSpaceMapTy InferredAddrSpace;
570 inferAddressSpaces(Postorder, &InferredAddrSpace);
571
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000572 // Changes the address spaces of the flat address expressions who are inferred
573 // to point to a specific address space.
Jingyue Wu13755602016-03-20 20:59:20 +0000574 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, &F);
575}
576
Matt Arsenault850657a2017-01-31 01:10:58 +0000577void InferAddressSpaces::inferAddressSpaces(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000578 const std::vector<Value *> &Postorder,
579 ValueToAddrSpaceMapTy *InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000580 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
581 // Initially, all expressions are in the uninitialized address space.
582 for (Value *V : Postorder)
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000583 (*InferredAddrSpace)[V] = UninitializedAddressSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000584
585 while (!Worklist.empty()) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000586 Value *V = Worklist.pop_back_val();
Jingyue Wu13755602016-03-20 20:59:20 +0000587
588 // Tries to update the address space of the stack top according to the
589 // address spaces of its operands.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000590 DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000591 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace);
592 if (!NewAS.hasValue())
593 continue;
594 // If any updates are made, grabs its users to the worklist because
595 // their address spaces can also be possibly updated.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000596 DEBUG(dbgs() << " to " << NewAS.getValue() << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000597 (*InferredAddrSpace)[V] = NewAS.getValue();
598
599 for (Value *User : V->users()) {
600 // Skip if User is already in the worklist.
601 if (Worklist.count(User))
602 continue;
603
604 auto Pos = InferredAddrSpace->find(User);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000605 // Our algorithm only updates the address spaces of flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000606 // expressions, which are those in InferredAddrSpace.
607 if (Pos == InferredAddrSpace->end())
608 continue;
609
610 // Function updateAddressSpace moves the address space down a lattice
Matt Arsenault850657a2017-01-31 01:10:58 +0000611 // path. Therefore, nothing to do if User is already inferred as flat (the
612 // bottom element in the lattice).
Matt Arsenault42b64782017-01-30 23:02:12 +0000613 if (Pos->second == FlatAddrSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000614 continue;
615
616 Worklist.insert(User);
617 }
618 }
619}
620
Matt Arsenault850657a2017-01-31 01:10:58 +0000621Optional<unsigned> InferAddressSpaces::updateAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000622 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000623 assert(InferredAddrSpace.count(&V));
624
625 // The new inferred address space equals the join of the address spaces
626 // of all its pointer operands.
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000627 unsigned NewAS = UninitializedAddressSpace;
Matt Arsenault850657a2017-01-31 01:10:58 +0000628
Matt Arsenault30083602017-02-02 03:37:22 +0000629 const Operator &Op = cast<Operator>(V);
630 if (Op.getOpcode() == Instruction::Select) {
631 Value *Src0 = Op.getOperand(1);
632 Value *Src1 = Op.getOperand(2);
633
634 auto I = InferredAddrSpace.find(Src0);
635 unsigned Src0AS = (I != InferredAddrSpace.end()) ?
636 I->second : Src0->getType()->getPointerAddressSpace();
637
638 auto J = InferredAddrSpace.find(Src1);
639 unsigned Src1AS = (J != InferredAddrSpace.end()) ?
640 J->second : Src1->getType()->getPointerAddressSpace();
641
642 auto *C0 = dyn_cast<Constant>(Src0);
643 auto *C1 = dyn_cast<Constant>(Src1);
644
645 // If one of the inputs is a constant, we may be able to do a constant
646 // addrspacecast of it. Defer inferring the address space until the input
647 // address space is known.
648 if ((C1 && Src0AS == UninitializedAddressSpace) ||
649 (C0 && Src1AS == UninitializedAddressSpace))
650 return None;
651
652 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
653 NewAS = Src1AS;
654 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
655 NewAS = Src0AS;
656 else
657 NewAS = joinAddressSpaces(Src0AS, Src1AS);
658 } else {
659 for (Value *PtrOperand : getPointerOperands(V)) {
660 auto I = InferredAddrSpace.find(PtrOperand);
661 unsigned OperandAS = I != InferredAddrSpace.end() ?
662 I->second : PtrOperand->getType()->getPointerAddressSpace();
663
664 // join(flat, *) = flat. So we can break if NewAS is already flat.
665 NewAS = joinAddressSpaces(NewAS, OperandAS);
666 if (NewAS == FlatAddrSpace)
667 break;
668 }
Jingyue Wu13755602016-03-20 20:59:20 +0000669 }
670
671 unsigned OldAS = InferredAddrSpace.lookup(&V);
Matt Arsenault42b64782017-01-30 23:02:12 +0000672 assert(OldAS != FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000673 if (OldAS == NewAS)
674 return None;
675 return NewAS;
676}
677
Matt Arsenault6c907a92017-01-31 01:40:38 +0000678/// \p returns true if \p U is the pointer operand of a memory instruction with
679/// a single pointer operand that can have its address space changed by simply
680/// mutating the use to a new value.
681static bool isSimplePointerUseValidToReplace(Use &U) {
682 User *Inst = U.getUser();
683 unsigned OpNo = U.getOperandNo();
684
685 if (auto *LI = dyn_cast<LoadInst>(Inst))
686 return OpNo == LoadInst::getPointerOperandIndex() && !LI->isVolatile();
687
688 if (auto *SI = dyn_cast<StoreInst>(Inst))
689 return OpNo == StoreInst::getPointerOperandIndex() && !SI->isVolatile();
690
691 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
692 return OpNo == AtomicRMWInst::getPointerOperandIndex() && !RMW->isVolatile();
693
694 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
695 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
696 !CmpX->isVolatile();
697 }
698
699 return false;
700}
701
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000702/// Update memory intrinsic uses that require more complex processing than
703/// simple memory instructions. Thse require re-mangling and may have multiple
704/// pointer operands.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000705static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
706 Value *NewV) {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000707 IRBuilder<> B(MI);
708 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
709 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
710 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
711
712 if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
713 B.CreateMemSet(NewV, MSI->getValue(),
714 MSI->getLength(), MSI->getAlignment(),
715 false, // isVolatile
716 TBAA, ScopeMD, NoAliasMD);
717 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
718 Value *Src = MTI->getRawSource();
719 Value *Dest = MTI->getRawDest();
720
721 // Be careful in case this is a self-to-self copy.
722 if (Src == OldV)
723 Src = NewV;
724
725 if (Dest == OldV)
726 Dest = NewV;
727
728 if (isa<MemCpyInst>(MTI)) {
729 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
730 B.CreateMemCpy(Dest, Src, MTI->getLength(),
731 MTI->getAlignment(),
732 false, // isVolatile
733 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
734 } else {
735 assert(isa<MemMoveInst>(MTI));
736 B.CreateMemMove(Dest, Src, MTI->getLength(),
737 MTI->getAlignment(),
738 false, // isVolatile
739 TBAA, ScopeMD, NoAliasMD);
740 }
741 } else
742 llvm_unreachable("unhandled MemIntrinsic");
743
744 MI->eraseFromParent();
745 return true;
746}
747
Matt Arsenault72f259b2017-01-31 02:17:32 +0000748// \p returns true if it is OK to change the address space of constant \p C with
749// a ConstantExpr addrspacecast.
750bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const {
Matt Arsenault30083602017-02-02 03:37:22 +0000751 assert(NewAS != UninitializedAddressSpace);
752
Matt Arsenault2a46d812017-01-31 23:48:40 +0000753 unsigned SrcAS = C->getType()->getPointerAddressSpace();
754 if (SrcAS == NewAS || isa<UndefValue>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000755 return true;
756
Matt Arsenault2a46d812017-01-31 23:48:40 +0000757 // Prevent illegal casts between different non-flat address spaces.
758 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
759 return false;
760
761 if (isa<ConstantPointerNull>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000762 return true;
763
764 if (auto *Op = dyn_cast<Operator>(C)) {
765 // If we already have a constant addrspacecast, it should be safe to cast it
766 // off.
767 if (Op->getOpcode() == Instruction::AddrSpaceCast)
768 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
769
770 if (Op->getOpcode() == Instruction::IntToPtr &&
771 Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
772 return true;
773 }
774
775 return false;
776}
777
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000778static Value::use_iterator skipToNextUser(Value::use_iterator I,
779 Value::use_iterator End) {
780 User *CurUser = I->getUser();
781 ++I;
782
783 while (I != End && I->getUser() == CurUser)
784 ++I;
785
786 return I;
787}
788
Matt Arsenault850657a2017-01-31 01:10:58 +0000789bool InferAddressSpaces::rewriteWithNewAddressSpaces(
790 const std::vector<Value *> &Postorder,
791 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000792 // For each address expression to be modified, creates a clone of it with its
793 // pointer operands converted to the new address space. Since the pointer
794 // operands are converted, the clone is naturally in the new address space by
795 // construction.
796 ValueToValueMapTy ValueWithNewAddrSpace;
797 SmallVector<const Use *, 32> UndefUsesToFix;
798 for (Value* V : Postorder) {
799 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
800 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
801 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000802 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000803 }
804 }
805
806 if (ValueWithNewAddrSpace.empty())
807 return false;
808
809 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000810 for (const Use *UndefUse : UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000811 User *V = UndefUse->getUser();
812 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V));
813 unsigned OperandNo = UndefUse->getOperandNo();
814 assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
815 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
816 }
817
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000818 SmallVector<Instruction *, 16> DeadInstructions;
819
Jingyue Wu13755602016-03-20 20:59:20 +0000820 // Replaces the uses of the old address expressions with the new ones.
821 for (Value *V : Postorder) {
822 Value *NewV = ValueWithNewAddrSpace.lookup(V);
823 if (NewV == nullptr)
824 continue;
825
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000826 DEBUG(dbgs() << "Replacing the uses of " << *V
827 << "\n with\n " << *NewV << '\n');
828
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000829 Value::use_iterator I, E, Next;
830 for (I = V->use_begin(), E = V->use_end(); I != E; ) {
831 Use &U = *I;
832
833 // Some users may see the same pointer operand in multiple operands. Skip
834 // to the next instruction.
835 I = skipToNextUser(I, E);
836
837 if (isSimplePointerUseValidToReplace(U)) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000838 // If V is used as the pointer operand of a compatible memory operation,
839 // sets the pointer operand to NewV. This replacement does not change
840 // the element type, so the resultant load/store is still valid.
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000841 U.set(NewV);
842 continue;
843 }
844
845 User *CurUser = U.getUser();
846 // Handle more complex cases like intrinsic that need to be remangled.
847 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
848 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
849 continue;
850 }
851
852 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
853 if (rewriteIntrinsicOperands(II, V, NewV))
854 continue;
855 }
856
857 if (isa<Instruction>(CurUser)) {
Matt Arsenault72f259b2017-01-31 02:17:32 +0000858 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
859 // If we can infer that both pointers are in the same addrspace,
860 // transform e.g.
861 // %cmp = icmp eq float* %p, %q
862 // into
863 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
864
865 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
866 int SrcIdx = U.getOperandNo();
867 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
868 Value *OtherSrc = Cmp->getOperand(OtherIdx);
869
870 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
871 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
872 Cmp->setOperand(OtherIdx, OtherNewV);
873 Cmp->setOperand(SrcIdx, NewV);
874 continue;
875 }
876 }
877
878 // Even if the type mismatches, we can cast the constant.
879 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
880 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
881 Cmp->setOperand(SrcIdx, NewV);
882 Cmp->setOperand(OtherIdx,
883 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
884 continue;
885 }
886 }
887 }
888
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000889 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
890 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
891 if (ASC->getDestAddressSpace() == NewAS) {
892 ASC->replaceAllUsesWith(NewV);
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000893 DeadInstructions.push_back(ASC);
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000894 continue;
895 }
896 }
897
Matt Arsenault850657a2017-01-31 01:10:58 +0000898 // Otherwise, replaces the use with flat(NewV).
Jingyue Wu13755602016-03-20 20:59:20 +0000899 if (Instruction *I = dyn_cast<Instruction>(V)) {
900 BasicBlock::iterator InsertPos = std::next(I->getIterator());
901 while (isa<PHINode>(InsertPos))
902 ++InsertPos;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000903 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
Jingyue Wu13755602016-03-20 20:59:20 +0000904 } else {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000905 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
906 V->getType()));
Jingyue Wu13755602016-03-20 20:59:20 +0000907 }
908 }
909 }
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000910
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000911 if (V->use_empty()) {
912 if (Instruction *I = dyn_cast<Instruction>(V))
913 DeadInstructions.push_back(I);
914 }
Jingyue Wu13755602016-03-20 20:59:20 +0000915 }
916
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000917 for (Instruction *I : DeadInstructions)
918 RecursivelyDeleteTriviallyDeadInstructions(I);
919
Jingyue Wu13755602016-03-20 20:59:20 +0000920 return true;
921}
922
Matt Arsenault850657a2017-01-31 01:10:58 +0000923FunctionPass *llvm::createInferAddressSpacesPass() {
924 return new InferAddressSpaces();
Jingyue Wu13755602016-03-20 20:59:20 +0000925}