blob: a59248cc8c527bbb0b735d5dacece39f32216f0f [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- InferAddressSpace.cpp - --------------------------------------------===//
Jingyue Wu13755602016-03-20 20:59:20 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Jingyue Wu13755602016-03-20 20:59:20 +00006//
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//
Jingyue Wu13755602016-03-20 20:59:20 +000089//===----------------------------------------------------------------------===//
90
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000091#include "llvm/ADT/ArrayRef.h"
92#include "llvm/ADT/DenseMap.h"
Jingyue Wu13755602016-03-20 20:59:20 +000093#include "llvm/ADT/DenseSet.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000094#include "llvm/ADT/None.h"
Jingyue Wu13755602016-03-20 20:59:20 +000095#include "llvm/ADT/Optional.h"
96#include "llvm/ADT/SetVector.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000097#include "llvm/ADT/SmallVector.h"
Matt Arsenault42b64782017-01-30 23:02:12 +000098#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000099#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000100#include "llvm/IR/BasicBlock.h"
101#include "llvm/IR/Constant.h"
102#include "llvm/IR/Constants.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000103#include "llvm/IR/Function.h"
Reid Kleckner0e8c4bb2017-09-07 23:27:44 +0000104#include "llvm/IR/IRBuilder.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000105#include "llvm/IR/InstIterator.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000106#include "llvm/IR/Instruction.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000107#include "llvm/IR/Instructions.h"
Reid Kleckner0e8c4bb2017-09-07 23:27:44 +0000108#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000109#include "llvm/IR/Intrinsics.h"
110#include "llvm/IR/LLVMContext.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000111#include "llvm/IR/Operator.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000112#include "llvm/IR/Type.h"
113#include "llvm/IR/Use.h"
114#include "llvm/IR/User.h"
115#include "llvm/IR/Value.h"
116#include "llvm/IR/ValueHandle.h"
117#include "llvm/Pass.h"
118#include "llvm/Support/Casting.h"
119#include "llvm/Support/Compiler.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000120#include "llvm/Support/Debug.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000121#include "llvm/Support/ErrorHandling.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000122#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000123#include "llvm/Transforms/Scalar.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000124#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000125#include <cassert>
126#include <iterator>
127#include <limits>
128#include <utility>
129#include <vector>
Jingyue Wu13755602016-03-20 20:59:20 +0000130
Matt Arsenault850657a2017-01-31 01:10:58 +0000131#define DEBUG_TYPE "infer-address-spaces"
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000132
Jingyue Wu13755602016-03-20 20:59:20 +0000133using namespace llvm;
134
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000135static const unsigned UninitializedAddressSpace =
136 std::numeric_limits<unsigned>::max();
137
Jingyue Wu13755602016-03-20 20:59:20 +0000138namespace {
Jingyue Wu13755602016-03-20 20:59:20 +0000139
140using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
141
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000142/// InferAddressSpaces
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000143class InferAddressSpaces : public FunctionPass {
Matt Arsenault42b64782017-01-30 23:02:12 +0000144 /// Target specific address space which uses of should be replaced if
145 /// possible.
146 unsigned FlatAddrSpace;
147
Jingyue Wu13755602016-03-20 20:59:20 +0000148public:
149 static char ID;
150
Sven van Haastregt66f61262019-04-26 09:21:25 +0000151 InferAddressSpaces() :
152 FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
153 InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
Jingyue Wu13755602016-03-20 20:59:20 +0000154
Matt Arsenault32b96002017-01-27 17:30:39 +0000155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.setPreservesCFG();
Matt Arsenault42b64782017-01-30 23:02:12 +0000157 AU.addRequired<TargetTransformInfoWrapperPass>();
Matt Arsenault32b96002017-01-27 17:30:39 +0000158 }
159
Jingyue Wu13755602016-03-20 20:59:20 +0000160 bool runOnFunction(Function &F) override;
161
162private:
163 // Returns the new address space of V if updated; otherwise, returns None.
164 Optional<unsigned>
165 updateAddressSpace(const Value &V,
Matt Arsenault42b64782017-01-30 23:02:12 +0000166 const ValueToAddrSpaceMapTy &InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000167
168 // Tries to infer the specific address space of each address expression in
169 // Postorder.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000170 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
Matt Arsenault42b64782017-01-30 23:02:12 +0000171 ValueToAddrSpaceMapTy *InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000172
Matt Arsenault72f259b2017-01-31 02:17:32 +0000173 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
174
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000175 // Changes the flat address expressions in function F to point to specific
Jingyue Wu13755602016-03-20 20:59:20 +0000176 // address spaces if InferredAddrSpace says so. Postorder is the postorder of
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000177 // all flat expressions in the use-def graph of function F.
Artem Belevichcb8f6322017-10-24 20:31:44 +0000178 bool rewriteWithNewAddressSpaces(
179 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder,
180 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const;
Matt Arsenault42b64782017-01-30 23:02:12 +0000181
182 void appendsFlatAddressExpressionToPostorderStack(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000183 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
184 DenseSet<Value *> &Visited) const;
Matt Arsenault42b64782017-01-30 23:02:12 +0000185
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000186 bool rewriteIntrinsicOperands(IntrinsicInst *II,
187 Value *OldV, Value *NewV) const;
188 void collectRewritableIntrinsicOperands(
189 IntrinsicInst *II,
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000190 std::vector<std::pair<Value *, bool>> &PostorderStack,
191 DenseSet<Value *> &Visited) const;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000192
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000193 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000194
Matt Arsenault42b64782017-01-30 23:02:12 +0000195 Value *cloneValueWithNewAddressSpace(
196 Value *V, unsigned NewAddrSpace,
197 const ValueToValueMapTy &ValueWithNewAddrSpace,
198 SmallVectorImpl<const Use *> *UndefUsesToFix) const;
199 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000200};
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000201
Jingyue Wu13755602016-03-20 20:59:20 +0000202} // end anonymous namespace
203
Matt Arsenault850657a2017-01-31 01:10:58 +0000204char InferAddressSpaces::ID = 0;
Jingyue Wu13755602016-03-20 20:59:20 +0000205
206namespace llvm {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000207
Matt Arsenault850657a2017-01-31 01:10:58 +0000208void initializeInferAddressSpacesPass(PassRegistry &);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000209
210} // end namespace llvm
Matt Arsenault850657a2017-01-31 01:10:58 +0000211
212INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
Jingyue Wu13755602016-03-20 20:59:20 +0000213 false, false)
214
215// Returns true if V is an address expression.
216// TODO: Currently, we consider only phi, bitcast, addrspacecast, and
217// getelementptr operators.
218static bool isAddressExpression(const Value &V) {
219 if (!isa<Operator>(V))
220 return false;
221
Joey Gouly92af1362019-02-21 12:31:36 +0000222 const Operator &Op = cast<Operator>(V);
223 switch (Op.getOpcode()) {
Jingyue Wu13755602016-03-20 20:59:20 +0000224 case Instruction::PHI:
Joey Gouly92af1362019-02-21 12:31:36 +0000225 assert(Op.getType()->isPointerTy());
Joey Goulyfdf651e2019-02-21 13:10:37 +0000226 return true;
Jingyue Wu13755602016-03-20 20:59:20 +0000227 case Instruction::BitCast:
228 case Instruction::AddrSpaceCast:
229 case Instruction::GetElementPtr:
230 return true;
Joey Gouly92af1362019-02-21 12:31:36 +0000231 case Instruction::Select:
232 return Op.getType()->isPointerTy();
Jingyue Wu13755602016-03-20 20:59:20 +0000233 default:
234 return false;
235 }
236}
237
238// Returns the pointer operands of V.
239//
240// Precondition: V is an address expression.
241static SmallVector<Value *, 2> getPointerOperands(const Value &V) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000242 const Operator &Op = cast<Operator>(V);
Jingyue Wu13755602016-03-20 20:59:20 +0000243 switch (Op.getOpcode()) {
244 case Instruction::PHI: {
245 auto IncomingValues = cast<PHINode>(Op).incoming_values();
246 return SmallVector<Value *, 2>(IncomingValues.begin(),
247 IncomingValues.end());
248 }
249 case Instruction::BitCast:
250 case Instruction::AddrSpaceCast:
251 case Instruction::GetElementPtr:
252 return {Op.getOperand(0)};
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000253 case Instruction::Select:
254 return {Op.getOperand(1), Op.getOperand(2)};
Jingyue Wu13755602016-03-20 20:59:20 +0000255 default:
256 llvm_unreachable("Unexpected instruction type.");
257 }
258}
259
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000260// TODO: Move logic to TTI?
261bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II,
262 Value *OldV,
263 Value *NewV) const {
264 Module *M = II->getParent()->getParent()->getParent();
265
266 switch (II->getIntrinsicID()) {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000267 case Intrinsic::amdgcn_atomic_inc:
Daniil Fukalovd5fca552018-01-17 14:05:05 +0000268 case Intrinsic::amdgcn_atomic_dec:
Daniil Fukalov6e1dc682018-01-26 11:09:38 +0000269 case Intrinsic::amdgcn_ds_fadd:
270 case Intrinsic::amdgcn_ds_fmin:
271 case Intrinsic::amdgcn_ds_fmax: {
Matt Arsenault79f837c2017-03-30 22:21:40 +0000272 const ConstantInt *IsVolatile = dyn_cast<ConstantInt>(II->getArgOperand(4));
Craig Topper79ab6432017-07-06 18:39:47 +0000273 if (!IsVolatile || !IsVolatile->isZero())
Matt Arsenault79f837c2017-03-30 22:21:40 +0000274 return false;
275
276 LLVM_FALLTHROUGH;
277 }
278 case Intrinsic::objectsize: {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000279 Type *DestTy = II->getType();
280 Type *SrcTy = NewV->getType();
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000281 Function *NewDecl =
282 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000283 II->setArgOperand(0, NewV);
284 II->setCalledFunction(NewDecl);
285 return true;
286 }
287 default:
288 return false;
289 }
290}
291
292// TODO: Move logic to TTI?
293void InferAddressSpaces::collectRewritableIntrinsicOperands(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000294 IntrinsicInst *II, std::vector<std::pair<Value *, bool>> &PostorderStack,
295 DenseSet<Value *> &Visited) const {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000296 switch (II->getIntrinsicID()) {
297 case Intrinsic::objectsize:
298 case Intrinsic::amdgcn_atomic_inc:
299 case Intrinsic::amdgcn_atomic_dec:
Daniil Fukalov6e1dc682018-01-26 11:09:38 +0000300 case Intrinsic::amdgcn_ds_fadd:
301 case Intrinsic::amdgcn_ds_fmin:
302 case Intrinsic::amdgcn_ds_fmax:
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000303 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
304 PostorderStack, Visited);
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000305 break;
306 default:
307 break;
308 }
309}
310
311// Returns all flat address expressions in function F. The elements are
Matt Arsenault42b64782017-01-30 23:02:12 +0000312// If V is an unvisited flat address expression, appends V to PostorderStack
Jingyue Wu13755602016-03-20 20:59:20 +0000313// and marks it as visited.
Matt Arsenault850657a2017-01-31 01:10:58 +0000314void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000315 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
316 DenseSet<Value *> &Visited) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000317 assert(V->getType()->isPointerTy());
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000318
319 // Generic addressing expressions may be hidden in nested constant
320 // expressions.
321 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
322 // TODO: Look in non-address parts, like icmp operands.
323 if (isAddressExpression(*CE) && Visited.insert(CE).second)
324 PostorderStack.push_back(std::make_pair(CE, false));
325
326 return;
327 }
328
Jingyue Wu13755602016-03-20 20:59:20 +0000329 if (isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000330 V->getType()->getPointerAddressSpace() == FlatAddrSpace) {
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000331 if (Visited.insert(V).second) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000332 PostorderStack.push_back(std::make_pair(V, false));
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000333
334 Operator *Op = cast<Operator>(V);
335 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
337 if (isAddressExpression(*CE) && Visited.insert(CE).second)
338 PostorderStack.emplace_back(CE, false);
339 }
340 }
341 }
Jingyue Wu13755602016-03-20 20:59:20 +0000342 }
343}
344
Matt Arsenault42b64782017-01-30 23:02:12 +0000345// Returns all flat address expressions in function F. The elements are ordered
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000346// ordered in postorder.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000347std::vector<WeakTrackingVH>
Matt Arsenault850657a2017-01-31 01:10:58 +0000348InferAddressSpaces::collectFlatAddressExpressions(Function &F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000349 // This function implements a non-recursive postorder traversal of a partial
350 // use-def graph of function F.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000351 std::vector<std::pair<Value *, bool>> PostorderStack;
Jingyue Wu13755602016-03-20 20:59:20 +0000352 // The set of visited expressions.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000353 DenseSet<Value *> Visited;
Matt Arsenault6c907a92017-01-31 01:40:38 +0000354
355 auto PushPtrOperand = [&](Value *Ptr) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000356 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
357 Visited);
Matt Arsenault6c907a92017-01-31 01:40:38 +0000358 };
359
Matt Arsenaultc07bda72017-04-21 21:35:04 +0000360 // Look at operations that may be interesting accelerate by moving to a known
361 // address space. We aim at generating after loads and stores, but pure
362 // addressing calculations may also be faster.
Jingyue Wu13755602016-03-20 20:59:20 +0000363 for (Instruction &I : instructions(F)) {
Matt Arsenaultc07bda72017-04-21 21:35:04 +0000364 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
365 if (!GEP->getType()->isVectorTy())
366 PushPtrOperand(GEP->getPointerOperand());
367 } else if (auto *LI = dyn_cast<LoadInst>(&I))
Matt Arsenault6c907a92017-01-31 01:40:38 +0000368 PushPtrOperand(LI->getPointerOperand());
369 else if (auto *SI = dyn_cast<StoreInst>(&I))
370 PushPtrOperand(SI->getPointerOperand());
371 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
372 PushPtrOperand(RMW->getPointerOperand());
373 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
374 PushPtrOperand(CmpX->getPointerOperand());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000375 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
376 // For memset/memcpy/memmove, any pointer operand can be replaced.
377 PushPtrOperand(MI->getRawDest());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000378
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000379 // Handle 2nd operand for memcpy/memmove.
380 if (auto *MTI = dyn_cast<MemTransferInst>(MI))
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000381 PushPtrOperand(MTI->getRawSource());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000382 } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000383 collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
Matt Arsenault72f259b2017-01-31 02:17:32 +0000384 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
385 // FIXME: Handle vectors of pointers
386 if (Cmp->getOperand(0)->getType()->isPointerTy()) {
387 PushPtrOperand(Cmp->getOperand(0));
388 PushPtrOperand(Cmp->getOperand(1));
389 }
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000390 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
391 if (!ASC->getType()->isVectorTy())
392 PushPtrOperand(ASC->getPointerOperand());
Matt Arsenault72f259b2017-01-31 02:17:32 +0000393 }
Jingyue Wu13755602016-03-20 20:59:20 +0000394 }
395
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000396 std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
Jingyue Wu13755602016-03-20 20:59:20 +0000397 while (!PostorderStack.empty()) {
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000398 Value *TopVal = PostorderStack.back().first;
Jingyue Wu13755602016-03-20 20:59:20 +0000399 // If the operands of the expression on the top are already explored,
400 // adds that expression to the resultant postorder.
401 if (PostorderStack.back().second) {
Yaxun Liub909f112017-07-07 02:40:13 +0000402 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
403 Postorder.push_back(TopVal);
Jingyue Wu13755602016-03-20 20:59:20 +0000404 PostorderStack.pop_back();
405 continue;
406 }
407 // Otherwise, adds its operands to the stack and explores them.
408 PostorderStack.back().second = true;
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000409 for (Value *PtrOperand : getPointerOperands(*TopVal)) {
Matt Arsenault6d7f01e2017-04-24 23:42:41 +0000410 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
411 Visited);
Jingyue Wu13755602016-03-20 20:59:20 +0000412 }
413 }
414 return Postorder;
415}
416
417// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
418// of OperandUse.get() in the new address space. If the clone is not ready yet,
419// returns an undef in the new address space as a placeholder.
420static Value *operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000421 const Use &OperandUse, unsigned NewAddrSpace,
422 const ValueToValueMapTy &ValueWithNewAddrSpace,
423 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000424 Value *Operand = OperandUse.get();
Matt Arsenault30083602017-02-02 03:37:22 +0000425
426 Type *NewPtrTy =
427 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
428
429 if (Constant *C = dyn_cast<Constant>(Operand))
430 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
431
Jingyue Wu13755602016-03-20 20:59:20 +0000432 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
433 return NewOperand;
434
435 UndefUsesToFix->push_back(&OperandUse);
Matt Arsenault30083602017-02-02 03:37:22 +0000436 return UndefValue::get(NewPtrTy);
Jingyue Wu13755602016-03-20 20:59:20 +0000437}
438
439// Returns a clone of `I` with its operands converted to those specified in
440// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
441// operand whose address space needs to be modified might not exist in
442// ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
443// adds that operand use to UndefUsesToFix so that caller can fix them later.
444//
445// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
446// from a pointer whose type already matches. Therefore, this function returns a
447// Value* instead of an Instruction*.
448static Value *cloneInstructionWithNewAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000449 Instruction *I, unsigned NewAddrSpace,
450 const ValueToValueMapTy &ValueWithNewAddrSpace,
451 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000452 Type *NewPtrType =
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000453 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000454
455 if (I->getOpcode() == Instruction::AddrSpaceCast) {
456 Value *Src = I->getOperand(0);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000457 // Because `I` is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000458 // Therefore, the inferred address space must be the source space, according
459 // to our algorithm.
460 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
461 if (Src->getType() != NewPtrType)
462 return new BitCastInst(Src, NewPtrType);
463 return Src;
464 }
465
466 // Computes the converted pointer operands.
467 SmallVector<Value *, 4> NewPointerOperands;
468 for (const Use &OperandUse : I->operands()) {
469 if (!OperandUse.get()->getType()->isPointerTy())
470 NewPointerOperands.push_back(nullptr);
471 else
472 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenault850657a2017-01-31 01:10:58 +0000473 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
Jingyue Wu13755602016-03-20 20:59:20 +0000474 }
475
476 switch (I->getOpcode()) {
477 case Instruction::BitCast:
478 return new BitCastInst(NewPointerOperands[0], NewPtrType);
479 case Instruction::PHI: {
480 assert(I->getType()->isPointerTy());
481 PHINode *PHI = cast<PHINode>(I);
482 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
483 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
484 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
485 NewPHI->addIncoming(NewPointerOperands[OperandNo],
486 PHI->getIncomingBlock(Index));
487 }
488 return NewPHI;
489 }
490 case Instruction::GetElementPtr: {
491 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
492 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000493 GEP->getSourceElementType(), NewPointerOperands[0],
494 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end()));
Jingyue Wu13755602016-03-20 20:59:20 +0000495 NewGEP->setIsInBounds(GEP->isInBounds());
496 return NewGEP;
497 }
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000498 case Instruction::Select:
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000499 assert(I->getType()->isPointerTy());
500 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
501 NewPointerOperands[2], "", nullptr, I);
Jingyue Wu13755602016-03-20 20:59:20 +0000502 default:
503 llvm_unreachable("Unexpected opcode");
504 }
505}
506
507// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
508// constant expression `CE` with its operands replaced as specified in
509// ValueWithNewAddrSpace.
510static Value *cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000511 ConstantExpr *CE, unsigned NewAddrSpace,
512 const ValueToValueMapTy &ValueWithNewAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000513 Type *TargetType =
Matt Arsenault850657a2017-01-31 01:10:58 +0000514 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000515
516 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000517 // Because CE is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000518 // Therefore, the inferred address space must be the source space according
519 // to our algorithm.
520 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
521 NewAddrSpace);
522 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
523 }
524
Matt Arsenaultc18b6772017-02-17 00:32:19 +0000525 if (CE->getOpcode() == Instruction::BitCast) {
526 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
527 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
528 return ConstantExpr::getAddrSpaceCast(CE, TargetType);
529 }
530
Matt Arsenault30083602017-02-02 03:37:22 +0000531 if (CE->getOpcode() == Instruction::Select) {
532 Constant *Src0 = CE->getOperand(1);
533 Constant *Src1 = CE->getOperand(2);
534 if (Src0->getType()->getPointerAddressSpace() ==
535 Src1->getType()->getPointerAddressSpace()) {
536
537 return ConstantExpr::getSelect(
538 CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
539 ConstantExpr::getAddrSpaceCast(Src1, TargetType));
540 }
541 }
542
Jingyue Wu13755602016-03-20 20:59:20 +0000543 // Computes the operands of the new constant expression.
Nirav Dave62fb8492017-06-08 13:20:55 +0000544 bool IsNew = false;
Jingyue Wu13755602016-03-20 20:59:20 +0000545 SmallVector<Constant *, 4> NewOperands;
546 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
547 Constant *Operand = CE->getOperand(Index);
548 // If the address space of `Operand` needs to be modified, the new operand
549 // with the new address space should already be in ValueWithNewAddrSpace
550 // because (1) the constant expressions we consider (i.e. addrspacecast,
551 // bitcast, and getelementptr) do not incur cycles in the data flow graph
552 // and (2) this function is called on constant expressions in postorder.
553 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
Nirav Dave62fb8492017-06-08 13:20:55 +0000554 IsNew = true;
Jingyue Wu13755602016-03-20 20:59:20 +0000555 NewOperands.push_back(cast<Constant>(NewOperand));
556 } else {
557 // Otherwise, reuses the old operand.
558 NewOperands.push_back(Operand);
559 }
560 }
561
Nirav Dave62fb8492017-06-08 13:20:55 +0000562 // If !IsNew, we will replace the Value with itself. However, replaced values
563 // are assumed to wrapped in a addrspace cast later so drop it now.
564 if (!IsNew)
565 return nullptr;
566
Jingyue Wu13755602016-03-20 20:59:20 +0000567 if (CE->getOpcode() == Instruction::GetElementPtr) {
568 // Needs to specify the source type while constructing a getelementptr
569 // constant expression.
570 return CE->getWithOperands(
Matt Arsenault850657a2017-01-31 01:10:58 +0000571 NewOperands, TargetType, /*OnlyIfReduced=*/false,
572 NewOperands[0]->getType()->getPointerElementType());
Jingyue Wu13755602016-03-20 20:59:20 +0000573 }
574
575 return CE->getWithOperands(NewOperands, TargetType);
576}
577
578// Returns a clone of the value `V`, with its operands replaced as specified in
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000579// ValueWithNewAddrSpace. This function is called on every flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000580// expression whose address space needs to be modified, in postorder.
581//
582// See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
Matt Arsenault850657a2017-01-31 01:10:58 +0000583Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
Matt Arsenault42b64782017-01-30 23:02:12 +0000584 Value *V, unsigned NewAddrSpace,
585 const ValueToValueMapTy &ValueWithNewAddrSpace,
586 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000587 // All values in Postorder are flat address expressions.
Jingyue Wu13755602016-03-20 20:59:20 +0000588 assert(isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000589 V->getType()->getPointerAddressSpace() == FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000590
591 if (Instruction *I = dyn_cast<Instruction>(V)) {
592 Value *NewV = cloneInstructionWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000593 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000594 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) {
595 if (NewI->getParent() == nullptr) {
596 NewI->insertBefore(I);
597 NewI->takeName(I);
598 }
599 }
600 return NewV;
601 }
602
603 return cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000604 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000605}
606
607// Defines the join operation on the address space lattice (see the file header
608// comments).
Matt Arsenault850657a2017-01-31 01:10:58 +0000609unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1,
610 unsigned AS2) const {
Matt Arsenault42b64782017-01-30 23:02:12 +0000611 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
612 return FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000613
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000614 if (AS1 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000615 return AS2;
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000616 if (AS2 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000617 return AS1;
618
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000619 // The join of two different specific address spaces is flat.
Matt Arsenault42b64782017-01-30 23:02:12 +0000620 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000621}
622
Matt Arsenault850657a2017-01-31 01:10:58 +0000623bool InferAddressSpaces::runOnFunction(Function &F) {
Andrew Kaylor87b10dd2016-04-26 23:44:31 +0000624 if (skipFunction(F))
625 return false;
626
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000627 const TargetTransformInfo &TTI =
628 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sven van Haastregt66f61262019-04-26 09:21:25 +0000629
630 if (FlatAddrSpace == UninitializedAddressSpace) {
631 FlatAddrSpace = TTI.getFlatAddressSpace();
632 if (FlatAddrSpace == UninitializedAddressSpace)
633 return false;
634 }
Matt Arsenault42b64782017-01-30 23:02:12 +0000635
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000636 // Collects all flat address expressions in postorder.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000637 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
Jingyue Wu13755602016-03-20 20:59:20 +0000638
639 // Runs a data-flow analysis to refine the address spaces of every expression
640 // in Postorder.
641 ValueToAddrSpaceMapTy InferredAddrSpace;
642 inferAddressSpaces(Postorder, &InferredAddrSpace);
643
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000644 // Changes the address spaces of the flat address expressions who are inferred
645 // to point to a specific address space.
Artem Belevichcb8f6322017-10-24 20:31:44 +0000646 return rewriteWithNewAddressSpaces(TTI, Postorder, InferredAddrSpace, &F);
Jingyue Wu13755602016-03-20 20:59:20 +0000647}
648
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000649// Constants need to be tracked through RAUW to handle cases with nested
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000650// constant expressions, so wrap values in WeakTrackingVH.
Matt Arsenault850657a2017-01-31 01:10:58 +0000651void InferAddressSpaces::inferAddressSpaces(
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000652 ArrayRef<WeakTrackingVH> Postorder,
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000653 ValueToAddrSpaceMapTy *InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000654 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
655 // Initially, all expressions are in the uninitialized address space.
656 for (Value *V : Postorder)
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000657 (*InferredAddrSpace)[V] = UninitializedAddressSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000658
659 while (!Worklist.empty()) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000660 Value *V = Worklist.pop_back_val();
Jingyue Wu13755602016-03-20 20:59:20 +0000661
662 // Tries to update the address space of the stack top according to the
663 // address spaces of its operands.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000664 LLVM_DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000665 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace);
666 if (!NewAS.hasValue())
667 continue;
668 // If any updates are made, grabs its users to the worklist because
669 // their address spaces can also be possibly updated.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000670 LLVM_DEBUG(dbgs() << " to " << NewAS.getValue() << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000671 (*InferredAddrSpace)[V] = NewAS.getValue();
672
673 for (Value *User : V->users()) {
674 // Skip if User is already in the worklist.
675 if (Worklist.count(User))
676 continue;
677
678 auto Pos = InferredAddrSpace->find(User);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000679 // Our algorithm only updates the address spaces of flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000680 // expressions, which are those in InferredAddrSpace.
681 if (Pos == InferredAddrSpace->end())
682 continue;
683
684 // Function updateAddressSpace moves the address space down a lattice
Matt Arsenault850657a2017-01-31 01:10:58 +0000685 // path. Therefore, nothing to do if User is already inferred as flat (the
686 // bottom element in the lattice).
Matt Arsenault42b64782017-01-30 23:02:12 +0000687 if (Pos->second == FlatAddrSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000688 continue;
689
690 Worklist.insert(User);
691 }
692 }
693}
694
Matt Arsenault850657a2017-01-31 01:10:58 +0000695Optional<unsigned> InferAddressSpaces::updateAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000696 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000697 assert(InferredAddrSpace.count(&V));
698
699 // The new inferred address space equals the join of the address spaces
700 // of all its pointer operands.
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000701 unsigned NewAS = UninitializedAddressSpace;
Matt Arsenault850657a2017-01-31 01:10:58 +0000702
Matt Arsenault30083602017-02-02 03:37:22 +0000703 const Operator &Op = cast<Operator>(V);
704 if (Op.getOpcode() == Instruction::Select) {
705 Value *Src0 = Op.getOperand(1);
706 Value *Src1 = Op.getOperand(2);
707
708 auto I = InferredAddrSpace.find(Src0);
709 unsigned Src0AS = (I != InferredAddrSpace.end()) ?
710 I->second : Src0->getType()->getPointerAddressSpace();
711
712 auto J = InferredAddrSpace.find(Src1);
713 unsigned Src1AS = (J != InferredAddrSpace.end()) ?
714 J->second : Src1->getType()->getPointerAddressSpace();
715
716 auto *C0 = dyn_cast<Constant>(Src0);
717 auto *C1 = dyn_cast<Constant>(Src1);
718
719 // If one of the inputs is a constant, we may be able to do a constant
720 // addrspacecast of it. Defer inferring the address space until the input
721 // address space is known.
722 if ((C1 && Src0AS == UninitializedAddressSpace) ||
723 (C0 && Src1AS == UninitializedAddressSpace))
724 return None;
725
726 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
727 NewAS = Src1AS;
728 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
729 NewAS = Src0AS;
730 else
731 NewAS = joinAddressSpaces(Src0AS, Src1AS);
732 } else {
733 for (Value *PtrOperand : getPointerOperands(V)) {
734 auto I = InferredAddrSpace.find(PtrOperand);
735 unsigned OperandAS = I != InferredAddrSpace.end() ?
736 I->second : PtrOperand->getType()->getPointerAddressSpace();
737
738 // join(flat, *) = flat. So we can break if NewAS is already flat.
739 NewAS = joinAddressSpaces(NewAS, OperandAS);
740 if (NewAS == FlatAddrSpace)
741 break;
742 }
Jingyue Wu13755602016-03-20 20:59:20 +0000743 }
744
745 unsigned OldAS = InferredAddrSpace.lookup(&V);
Matt Arsenault42b64782017-01-30 23:02:12 +0000746 assert(OldAS != FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000747 if (OldAS == NewAS)
748 return None;
749 return NewAS;
750}
751
Matt Arsenault6c907a92017-01-31 01:40:38 +0000752/// \p returns true if \p U is the pointer operand of a memory instruction with
753/// a single pointer operand that can have its address space changed by simply
Artem Belevichcb8f6322017-10-24 20:31:44 +0000754/// mutating the use to a new value. If the memory instruction is volatile,
755/// return true only if the target allows the memory instruction to be volatile
756/// in the new address space.
757static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
758 Use &U, unsigned AddrSpace) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000759 User *Inst = U.getUser();
760 unsigned OpNo = U.getOperandNo();
Artem Belevichcb8f6322017-10-24 20:31:44 +0000761 bool VolatileIsAllowed = false;
762 if (auto *I = dyn_cast<Instruction>(Inst))
763 VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
Matt Arsenault6c907a92017-01-31 01:40:38 +0000764
765 if (auto *LI = dyn_cast<LoadInst>(Inst))
Artem Belevichcb8f6322017-10-24 20:31:44 +0000766 return OpNo == LoadInst::getPointerOperandIndex() &&
767 (VolatileIsAllowed || !LI->isVolatile());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000768
769 if (auto *SI = dyn_cast<StoreInst>(Inst))
Artem Belevichcb8f6322017-10-24 20:31:44 +0000770 return OpNo == StoreInst::getPointerOperandIndex() &&
771 (VolatileIsAllowed || !SI->isVolatile());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000772
773 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
Artem Belevichcb8f6322017-10-24 20:31:44 +0000774 return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
775 (VolatileIsAllowed || !RMW->isVolatile());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000776
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000777 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
Matt Arsenault6c907a92017-01-31 01:40:38 +0000778 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
Artem Belevichcb8f6322017-10-24 20:31:44 +0000779 (VolatileIsAllowed || !CmpX->isVolatile());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000780
781 return false;
782}
783
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000784/// Update memory intrinsic uses that require more complex processing than
785/// simple memory instructions. Thse require re-mangling and may have multiple
786/// pointer operands.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000787static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
788 Value *NewV) {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000789 IRBuilder<> B(MI);
790 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
791 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
792 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
793
794 if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
795 B.CreateMemSet(NewV, MSI->getValue(),
Daniel Neilson5fdf08f2018-02-06 20:33:36 +0000796 MSI->getLength(), MSI->getDestAlignment(),
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000797 false, // isVolatile
798 TBAA, ScopeMD, NoAliasMD);
799 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
800 Value *Src = MTI->getRawSource();
801 Value *Dest = MTI->getRawDest();
802
803 // Be careful in case this is a self-to-self copy.
804 if (Src == OldV)
805 Src = NewV;
806
807 if (Dest == OldV)
808 Dest = NewV;
809
810 if (isa<MemCpyInst>(MTI)) {
811 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
Daniel Neilson5fdf08f2018-02-06 20:33:36 +0000812 B.CreateMemCpy(Dest, MTI->getDestAlignment(),
813 Src, MTI->getSourceAlignment(),
814 MTI->getLength(),
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000815 false, // isVolatile
816 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
817 } else {
818 assert(isa<MemMoveInst>(MTI));
Daniel Neilson5fdf08f2018-02-06 20:33:36 +0000819 B.CreateMemMove(Dest, MTI->getDestAlignment(),
820 Src, MTI->getSourceAlignment(),
821 MTI->getLength(),
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000822 false, // isVolatile
823 TBAA, ScopeMD, NoAliasMD);
824 }
825 } else
826 llvm_unreachable("unhandled MemIntrinsic");
827
828 MI->eraseFromParent();
829 return true;
830}
831
Matt Arsenault72f259b2017-01-31 02:17:32 +0000832// \p returns true if it is OK to change the address space of constant \p C with
833// a ConstantExpr addrspacecast.
834bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const {
Matt Arsenault30083602017-02-02 03:37:22 +0000835 assert(NewAS != UninitializedAddressSpace);
836
Matt Arsenault2a46d812017-01-31 23:48:40 +0000837 unsigned SrcAS = C->getType()->getPointerAddressSpace();
838 if (SrcAS == NewAS || isa<UndefValue>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000839 return true;
840
Matt Arsenault2a46d812017-01-31 23:48:40 +0000841 // Prevent illegal casts between different non-flat address spaces.
842 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
843 return false;
844
845 if (isa<ConstantPointerNull>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000846 return true;
847
848 if (auto *Op = dyn_cast<Operator>(C)) {
849 // If we already have a constant addrspacecast, it should be safe to cast it
850 // off.
851 if (Op->getOpcode() == Instruction::AddrSpaceCast)
852 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
853
854 if (Op->getOpcode() == Instruction::IntToPtr &&
855 Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
856 return true;
857 }
858
859 return false;
860}
861
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000862static Value::use_iterator skipToNextUser(Value::use_iterator I,
863 Value::use_iterator End) {
864 User *CurUser = I->getUser();
865 ++I;
866
867 while (I != End && I->getUser() == CurUser)
868 ++I;
869
870 return I;
871}
872
Matt Arsenault850657a2017-01-31 01:10:58 +0000873bool InferAddressSpaces::rewriteWithNewAddressSpaces(
Artem Belevichcb8f6322017-10-24 20:31:44 +0000874 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000875 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000876 // For each address expression to be modified, creates a clone of it with its
877 // pointer operands converted to the new address space. Since the pointer
878 // operands are converted, the clone is naturally in the new address space by
879 // construction.
880 ValueToValueMapTy ValueWithNewAddrSpace;
881 SmallVector<const Use *, 32> UndefUsesToFix;
882 for (Value* V : Postorder) {
883 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
884 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
885 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000886 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000887 }
888 }
889
890 if (ValueWithNewAddrSpace.empty())
891 return false;
892
893 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000894 for (const Use *UndefUse : UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000895 User *V = UndefUse->getUser();
896 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V));
897 unsigned OperandNo = UndefUse->getOperandNo();
898 assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
899 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
900 }
901
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000902 SmallVector<Instruction *, 16> DeadInstructions;
903
Jingyue Wu13755602016-03-20 20:59:20 +0000904 // Replaces the uses of the old address expressions with the new ones.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000905 for (const WeakTrackingVH &WVH : Postorder) {
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000906 assert(WVH && "value was unexpectedly deleted");
907 Value *V = WVH;
Jingyue Wu13755602016-03-20 20:59:20 +0000908 Value *NewV = ValueWithNewAddrSpace.lookup(V);
909 if (NewV == nullptr)
910 continue;
911
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000912 LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n "
913 << *NewV << '\n');
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000914
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000915 if (Constant *C = dyn_cast<Constant>(V)) {
916 Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
917 C->getType());
918 if (C != Replace) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000919 LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
920 << ": " << *Replace << '\n');
Matt Arsenaulte0f9e982017-04-28 22:52:41 +0000921 C->replaceAllUsesWith(Replace);
922 V = Replace;
923 }
924 }
925
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000926 Value::use_iterator I, E, Next;
927 for (I = V->use_begin(), E = V->use_end(); I != E; ) {
928 Use &U = *I;
929
930 // Some users may see the same pointer operand in multiple operands. Skip
931 // to the next instruction.
932 I = skipToNextUser(I, E);
933
Artem Belevichcb8f6322017-10-24 20:31:44 +0000934 if (isSimplePointerUseValidToReplace(
935 TTI, U, V->getType()->getPointerAddressSpace())) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000936 // If V is used as the pointer operand of a compatible memory operation,
937 // sets the pointer operand to NewV. This replacement does not change
938 // the element type, so the resultant load/store is still valid.
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000939 U.set(NewV);
940 continue;
941 }
942
943 User *CurUser = U.getUser();
944 // Handle more complex cases like intrinsic that need to be remangled.
945 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
946 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
947 continue;
948 }
949
950 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
951 if (rewriteIntrinsicOperands(II, V, NewV))
952 continue;
953 }
954
955 if (isa<Instruction>(CurUser)) {
Matt Arsenault72f259b2017-01-31 02:17:32 +0000956 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
957 // If we can infer that both pointers are in the same addrspace,
958 // transform e.g.
959 // %cmp = icmp eq float* %p, %q
960 // into
961 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
962
963 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
964 int SrcIdx = U.getOperandNo();
965 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
966 Value *OtherSrc = Cmp->getOperand(OtherIdx);
967
968 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
969 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
970 Cmp->setOperand(OtherIdx, OtherNewV);
971 Cmp->setOperand(SrcIdx, NewV);
972 continue;
973 }
974 }
975
976 // Even if the type mismatches, we can cast the constant.
977 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
978 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
979 Cmp->setOperand(SrcIdx, NewV);
980 Cmp->setOperand(OtherIdx,
981 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
982 continue;
983 }
984 }
985 }
986
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000987 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
988 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
989 if (ASC->getDestAddressSpace() == NewAS) {
Yaxun Liud23f23d2017-10-30 21:19:41 +0000990 if (ASC->getType()->getPointerElementType() !=
991 NewV->getType()->getPointerElementType()) {
992 NewV = CastInst::Create(Instruction::BitCast, NewV,
993 ASC->getType(), "", ASC);
994 }
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000995 ASC->replaceAllUsesWith(NewV);
Matt Arsenaultc20ccd22017-04-28 22:18:19 +0000996 DeadInstructions.push_back(ASC);
Matt Arsenaulta1e73402017-04-28 22:18:08 +0000997 continue;
998 }
999 }
1000
Matt Arsenault850657a2017-01-31 01:10:58 +00001001 // Otherwise, replaces the use with flat(NewV).
Jingyue Wu13755602016-03-20 20:59:20 +00001002 if (Instruction *I = dyn_cast<Instruction>(V)) {
1003 BasicBlock::iterator InsertPos = std::next(I->getIterator());
1004 while (isa<PHINode>(InsertPos))
1005 ++InsertPos;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +00001006 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
Jingyue Wu13755602016-03-20 20:59:20 +00001007 } else {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +00001008 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1009 V->getType()));
Jingyue Wu13755602016-03-20 20:59:20 +00001010 }
1011 }
1012 }
Matt Arsenault6d5a8d42017-01-31 01:56:57 +00001013
Matt Arsenaultc20ccd22017-04-28 22:18:19 +00001014 if (V->use_empty()) {
1015 if (Instruction *I = dyn_cast<Instruction>(V))
1016 DeadInstructions.push_back(I);
1017 }
Jingyue Wu13755602016-03-20 20:59:20 +00001018 }
1019
Matt Arsenaultc20ccd22017-04-28 22:18:19 +00001020 for (Instruction *I : DeadInstructions)
1021 RecursivelyDeleteTriviallyDeadInstructions(I);
1022
Jingyue Wu13755602016-03-20 20:59:20 +00001023 return true;
1024}
1025
Sven van Haastregt66f61262019-04-26 09:21:25 +00001026FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
1027 return new InferAddressSpaces(AddressSpace);
Jingyue Wu13755602016-03-20 20:59:20 +00001028}