blob: 8e1e037457667d3ca60a90e02bfdae87906bf398 [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(
155 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack,
156 DenseSet<Value *> *Visited) const;
157
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000158 bool rewriteIntrinsicOperands(IntrinsicInst *II,
159 Value *OldV, Value *NewV) const;
160 void collectRewritableIntrinsicOperands(
161 IntrinsicInst *II,
162 std::vector<std::pair<Value *, bool>> *PostorderStack,
163 DenseSet<Value *> *Visited) const;
164
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) {
207 assert(isAddressExpression(V));
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000208 const Operator &Op = cast<Operator>(V);
Jingyue Wu13755602016-03-20 20:59:20 +0000209 switch (Op.getOpcode()) {
210 case Instruction::PHI: {
211 auto IncomingValues = cast<PHINode>(Op).incoming_values();
212 return SmallVector<Value *, 2>(IncomingValues.begin(),
213 IncomingValues.end());
214 }
215 case Instruction::BitCast:
216 case Instruction::AddrSpaceCast:
217 case Instruction::GetElementPtr:
218 return {Op.getOperand(0)};
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000219 case Instruction::Select:
220 return {Op.getOperand(1), Op.getOperand(2)};
Jingyue Wu13755602016-03-20 20:59:20 +0000221 default:
222 llvm_unreachable("Unexpected instruction type.");
223 }
224}
225
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000226// TODO: Move logic to TTI?
227bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II,
228 Value *OldV,
229 Value *NewV) const {
230 Module *M = II->getParent()->getParent()->getParent();
231
232 switch (II->getIntrinsicID()) {
233 case Intrinsic::objectsize:
234 case Intrinsic::amdgcn_atomic_inc:
235 case Intrinsic::amdgcn_atomic_dec: {
236 Type *DestTy = II->getType();
237 Type *SrcTy = NewV->getType();
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000238 Function *NewDecl =
239 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000240 II->setArgOperand(0, NewV);
241 II->setCalledFunction(NewDecl);
242 return true;
243 }
244 default:
245 return false;
246 }
247}
248
249// TODO: Move logic to TTI?
250void InferAddressSpaces::collectRewritableIntrinsicOperands(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000251 IntrinsicInst *II, std::vector<std::pair<Value *, bool>> *PostorderStack,
252 DenseSet<Value *> *Visited) const {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000253 switch (II->getIntrinsicID()) {
254 case Intrinsic::objectsize:
255 case Intrinsic::amdgcn_atomic_inc:
256 case Intrinsic::amdgcn_atomic_dec:
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000257 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
258 PostorderStack, Visited);
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000259 break;
260 default:
261 break;
262 }
263}
264
265// Returns all flat address expressions in function F. The elements are
Matt Arsenault42b64782017-01-30 23:02:12 +0000266// If V is an unvisited flat address expression, appends V to PostorderStack
Jingyue Wu13755602016-03-20 20:59:20 +0000267// and marks it as visited.
Matt Arsenault850657a2017-01-31 01:10:58 +0000268void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000269 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack,
270 DenseSet<Value *> *Visited) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000271 assert(V->getType()->isPointerTy());
272 if (isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000273 V->getType()->getPointerAddressSpace() == FlatAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000274 if (Visited->insert(V).second)
275 PostorderStack->push_back(std::make_pair(V, false));
276 }
277}
278
Matt Arsenault42b64782017-01-30 23:02:12 +0000279// Returns all flat address expressions in function F. The elements are ordered
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000280// ordered in postorder.
Matt Arsenault42b64782017-01-30 23:02:12 +0000281std::vector<Value *>
Matt Arsenault850657a2017-01-31 01:10:58 +0000282InferAddressSpaces::collectFlatAddressExpressions(Function &F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000283 // This function implements a non-recursive postorder traversal of a partial
284 // use-def graph of function F.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000285 std::vector<std::pair<Value *, bool>> PostorderStack;
Jingyue Wu13755602016-03-20 20:59:20 +0000286 // The set of visited expressions.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000287 DenseSet<Value *> Visited;
Matt Arsenault6c907a92017-01-31 01:40:38 +0000288
289 auto PushPtrOperand = [&](Value *Ptr) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000290 appendsFlatAddressExpressionToPostorderStack(Ptr, &PostorderStack,
291 &Visited);
Matt Arsenault6c907a92017-01-31 01:40:38 +0000292 };
293
Jingyue Wu13755602016-03-20 20:59:20 +0000294 // We only explore address expressions that are reachable from loads and
295 // stores for now because we aim at generating faster loads and stores.
296 for (Instruction &I : instructions(F)) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000297 if (auto *LI = dyn_cast<LoadInst>(&I))
298 PushPtrOperand(LI->getPointerOperand());
299 else if (auto *SI = dyn_cast<StoreInst>(&I))
300 PushPtrOperand(SI->getPointerOperand());
301 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
302 PushPtrOperand(RMW->getPointerOperand());
303 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
304 PushPtrOperand(CmpX->getPointerOperand());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000305 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
306 // For memset/memcpy/memmove, any pointer operand can be replaced.
307 PushPtrOperand(MI->getRawDest());
Matt Arsenault6c907a92017-01-31 01:40:38 +0000308
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000309 // Handle 2nd operand for memcpy/memmove.
310 if (auto *MTI = dyn_cast<MemTransferInst>(MI))
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000311 PushPtrOperand(MTI->getRawSource());
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000312 } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
313 collectRewritableIntrinsicOperands(II, &PostorderStack, &Visited);
Matt Arsenault72f259b2017-01-31 02:17:32 +0000314 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
315 // FIXME: Handle vectors of pointers
316 if (Cmp->getOperand(0)->getType()->isPointerTy()) {
317 PushPtrOperand(Cmp->getOperand(0));
318 PushPtrOperand(Cmp->getOperand(1));
319 }
320 }
Jingyue Wu13755602016-03-20 20:59:20 +0000321 }
322
323 std::vector<Value *> Postorder; // The resultant postorder.
324 while (!PostorderStack.empty()) {
325 // If the operands of the expression on the top are already explored,
326 // adds that expression to the resultant postorder.
327 if (PostorderStack.back().second) {
328 Postorder.push_back(PostorderStack.back().first);
329 PostorderStack.pop_back();
330 continue;
331 }
332 // Otherwise, adds its operands to the stack and explores them.
333 PostorderStack.back().second = true;
334 for (Value *PtrOperand : getPointerOperands(*PostorderStack.back().first)) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000335 appendsFlatAddressExpressionToPostorderStack(PtrOperand, &PostorderStack,
336 &Visited);
Jingyue Wu13755602016-03-20 20:59:20 +0000337 }
338 }
339 return Postorder;
340}
341
342// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
343// of OperandUse.get() in the new address space. If the clone is not ready yet,
344// returns an undef in the new address space as a placeholder.
345static Value *operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000346 const Use &OperandUse, unsigned NewAddrSpace,
347 const ValueToValueMapTy &ValueWithNewAddrSpace,
348 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000349 Value *Operand = OperandUse.get();
Matt Arsenault30083602017-02-02 03:37:22 +0000350
351 Type *NewPtrTy =
352 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
353
354 if (Constant *C = dyn_cast<Constant>(Operand))
355 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
356
Jingyue Wu13755602016-03-20 20:59:20 +0000357 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
358 return NewOperand;
359
360 UndefUsesToFix->push_back(&OperandUse);
Matt Arsenault30083602017-02-02 03:37:22 +0000361 return UndefValue::get(NewPtrTy);
Jingyue Wu13755602016-03-20 20:59:20 +0000362}
363
364// Returns a clone of `I` with its operands converted to those specified in
365// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
366// operand whose address space needs to be modified might not exist in
367// ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
368// adds that operand use to UndefUsesToFix so that caller can fix them later.
369//
370// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
371// from a pointer whose type already matches. Therefore, this function returns a
372// Value* instead of an Instruction*.
373static Value *cloneInstructionWithNewAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000374 Instruction *I, unsigned NewAddrSpace,
375 const ValueToValueMapTy &ValueWithNewAddrSpace,
376 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000377 Type *NewPtrType =
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000378 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000379
380 if (I->getOpcode() == Instruction::AddrSpaceCast) {
381 Value *Src = I->getOperand(0);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000382 // Because `I` is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000383 // Therefore, the inferred address space must be the source space, according
384 // to our algorithm.
385 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
386 if (Src->getType() != NewPtrType)
387 return new BitCastInst(Src, NewPtrType);
388 return Src;
389 }
390
391 // Computes the converted pointer operands.
392 SmallVector<Value *, 4> NewPointerOperands;
393 for (const Use &OperandUse : I->operands()) {
394 if (!OperandUse.get()->getType()->isPointerTy())
395 NewPointerOperands.push_back(nullptr);
396 else
397 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenault850657a2017-01-31 01:10:58 +0000398 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
Jingyue Wu13755602016-03-20 20:59:20 +0000399 }
400
401 switch (I->getOpcode()) {
402 case Instruction::BitCast:
403 return new BitCastInst(NewPointerOperands[0], NewPtrType);
404 case Instruction::PHI: {
405 assert(I->getType()->isPointerTy());
406 PHINode *PHI = cast<PHINode>(I);
407 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
408 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
409 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
410 NewPHI->addIncoming(NewPointerOperands[OperandNo],
411 PHI->getIncomingBlock(Index));
412 }
413 return NewPHI;
414 }
415 case Instruction::GetElementPtr: {
416 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
417 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000418 GEP->getSourceElementType(), NewPointerOperands[0],
419 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end()));
Jingyue Wu13755602016-03-20 20:59:20 +0000420 NewGEP->setIsInBounds(GEP->isInBounds());
421 return NewGEP;
422 }
Matt Arsenaultbdd59e62017-02-01 00:08:53 +0000423 case Instruction::Select: {
424 assert(I->getType()->isPointerTy());
425 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
426 NewPointerOperands[2], "", nullptr, I);
427 }
Jingyue Wu13755602016-03-20 20:59:20 +0000428 default:
429 llvm_unreachable("Unexpected opcode");
430 }
431}
432
433// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
434// constant expression `CE` with its operands replaced as specified in
435// ValueWithNewAddrSpace.
436static Value *cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000437 ConstantExpr *CE, unsigned NewAddrSpace,
438 const ValueToValueMapTy &ValueWithNewAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000439 Type *TargetType =
Matt Arsenault850657a2017-01-31 01:10:58 +0000440 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000441
442 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000443 // Because CE is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000444 // Therefore, the inferred address space must be the source space according
445 // to our algorithm.
446 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
447 NewAddrSpace);
448 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
449 }
450
Matt Arsenault30083602017-02-02 03:37:22 +0000451 if (CE->getOpcode() == Instruction::Select) {
452 Constant *Src0 = CE->getOperand(1);
453 Constant *Src1 = CE->getOperand(2);
454 if (Src0->getType()->getPointerAddressSpace() ==
455 Src1->getType()->getPointerAddressSpace()) {
456
457 return ConstantExpr::getSelect(
458 CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
459 ConstantExpr::getAddrSpaceCast(Src1, TargetType));
460 }
461 }
462
Jingyue Wu13755602016-03-20 20:59:20 +0000463 // Computes the operands of the new constant expression.
464 SmallVector<Constant *, 4> NewOperands;
465 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
466 Constant *Operand = CE->getOperand(Index);
467 // If the address space of `Operand` needs to be modified, the new operand
468 // with the new address space should already be in ValueWithNewAddrSpace
469 // because (1) the constant expressions we consider (i.e. addrspacecast,
470 // bitcast, and getelementptr) do not incur cycles in the data flow graph
471 // and (2) this function is called on constant expressions in postorder.
472 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
473 NewOperands.push_back(cast<Constant>(NewOperand));
474 } else {
475 // Otherwise, reuses the old operand.
476 NewOperands.push_back(Operand);
477 }
478 }
479
480 if (CE->getOpcode() == Instruction::GetElementPtr) {
481 // Needs to specify the source type while constructing a getelementptr
482 // constant expression.
483 return CE->getWithOperands(
Matt Arsenault850657a2017-01-31 01:10:58 +0000484 NewOperands, TargetType, /*OnlyIfReduced=*/false,
485 NewOperands[0]->getType()->getPointerElementType());
Jingyue Wu13755602016-03-20 20:59:20 +0000486 }
487
488 return CE->getWithOperands(NewOperands, TargetType);
489}
490
491// Returns a clone of the value `V`, with its operands replaced as specified in
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000492// ValueWithNewAddrSpace. This function is called on every flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000493// expression whose address space needs to be modified, in postorder.
494//
495// See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
Matt Arsenault850657a2017-01-31 01:10:58 +0000496Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
Matt Arsenault42b64782017-01-30 23:02:12 +0000497 Value *V, unsigned NewAddrSpace,
498 const ValueToValueMapTy &ValueWithNewAddrSpace,
499 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000500 // All values in Postorder are flat address expressions.
Jingyue Wu13755602016-03-20 20:59:20 +0000501 assert(isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000502 V->getType()->getPointerAddressSpace() == FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000503
504 if (Instruction *I = dyn_cast<Instruction>(V)) {
505 Value *NewV = cloneInstructionWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000506 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000507 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) {
508 if (NewI->getParent() == nullptr) {
509 NewI->insertBefore(I);
510 NewI->takeName(I);
511 }
512 }
513 return NewV;
514 }
515
516 return cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000517 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000518}
519
520// Defines the join operation on the address space lattice (see the file header
521// comments).
Matt Arsenault850657a2017-01-31 01:10:58 +0000522unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1,
523 unsigned AS2) const {
Matt Arsenault42b64782017-01-30 23:02:12 +0000524 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
525 return FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000526
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000527 if (AS1 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000528 return AS2;
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000529 if (AS2 == UninitializedAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000530 return AS1;
531
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000532 // The join of two different specific address spaces is flat.
Matt Arsenault42b64782017-01-30 23:02:12 +0000533 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000534}
535
Matt Arsenault850657a2017-01-31 01:10:58 +0000536bool InferAddressSpaces::runOnFunction(Function &F) {
Andrew Kaylor87b10dd2016-04-26 23:44:31 +0000537 if (skipFunction(F))
538 return false;
539
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000540 const TargetTransformInfo &TTI =
541 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Matt Arsenault42b64782017-01-30 23:02:12 +0000542 FlatAddrSpace = TTI.getFlatAddressSpace();
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000543 if (FlatAddrSpace == UninitializedAddressSpace)
Matt Arsenault42b64782017-01-30 23:02:12 +0000544 return false;
545
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000546 // Collects all flat address expressions in postorder.
Matt Arsenault42b64782017-01-30 23:02:12 +0000547 std::vector<Value *> Postorder = collectFlatAddressExpressions(F);
Jingyue Wu13755602016-03-20 20:59:20 +0000548
549 // Runs a data-flow analysis to refine the address spaces of every expression
550 // in Postorder.
551 ValueToAddrSpaceMapTy InferredAddrSpace;
552 inferAddressSpaces(Postorder, &InferredAddrSpace);
553
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000554 // Changes the address spaces of the flat address expressions who are inferred
555 // to point to a specific address space.
Jingyue Wu13755602016-03-20 20:59:20 +0000556 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, &F);
557}
558
Matt Arsenault850657a2017-01-31 01:10:58 +0000559void InferAddressSpaces::inferAddressSpaces(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000560 const std::vector<Value *> &Postorder,
561 ValueToAddrSpaceMapTy *InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000562 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
563 // Initially, all expressions are in the uninitialized address space.
564 for (Value *V : Postorder)
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000565 (*InferredAddrSpace)[V] = UninitializedAddressSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000566
567 while (!Worklist.empty()) {
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000568 Value *V = Worklist.pop_back_val();
Jingyue Wu13755602016-03-20 20:59:20 +0000569
570 // Tries to update the address space of the stack top according to the
571 // address spaces of its operands.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000572 DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000573 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace);
574 if (!NewAS.hasValue())
575 continue;
576 // If any updates are made, grabs its users to the worklist because
577 // their address spaces can also be possibly updated.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000578 DEBUG(dbgs() << " to " << NewAS.getValue() << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000579 (*InferredAddrSpace)[V] = NewAS.getValue();
580
581 for (Value *User : V->users()) {
582 // Skip if User is already in the worklist.
583 if (Worklist.count(User))
584 continue;
585
586 auto Pos = InferredAddrSpace->find(User);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000587 // Our algorithm only updates the address spaces of flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000588 // expressions, which are those in InferredAddrSpace.
589 if (Pos == InferredAddrSpace->end())
590 continue;
591
592 // Function updateAddressSpace moves the address space down a lattice
Matt Arsenault850657a2017-01-31 01:10:58 +0000593 // path. Therefore, nothing to do if User is already inferred as flat (the
594 // bottom element in the lattice).
Matt Arsenault42b64782017-01-30 23:02:12 +0000595 if (Pos->second == FlatAddrSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000596 continue;
597
598 Worklist.insert(User);
599 }
600 }
601}
602
Matt Arsenault850657a2017-01-31 01:10:58 +0000603Optional<unsigned> InferAddressSpaces::updateAddressSpace(
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000604 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000605 assert(InferredAddrSpace.count(&V));
606
607 // The new inferred address space equals the join of the address spaces
608 // of all its pointer operands.
Matt Arsenault973c4ae2017-01-31 02:17:41 +0000609 unsigned NewAS = UninitializedAddressSpace;
Matt Arsenault850657a2017-01-31 01:10:58 +0000610
Matt Arsenault30083602017-02-02 03:37:22 +0000611 const Operator &Op = cast<Operator>(V);
612 if (Op.getOpcode() == Instruction::Select) {
613 Value *Src0 = Op.getOperand(1);
614 Value *Src1 = Op.getOperand(2);
615
616 auto I = InferredAddrSpace.find(Src0);
617 unsigned Src0AS = (I != InferredAddrSpace.end()) ?
618 I->second : Src0->getType()->getPointerAddressSpace();
619
620 auto J = InferredAddrSpace.find(Src1);
621 unsigned Src1AS = (J != InferredAddrSpace.end()) ?
622 J->second : Src1->getType()->getPointerAddressSpace();
623
624 auto *C0 = dyn_cast<Constant>(Src0);
625 auto *C1 = dyn_cast<Constant>(Src1);
626
627 // If one of the inputs is a constant, we may be able to do a constant
628 // addrspacecast of it. Defer inferring the address space until the input
629 // address space is known.
630 if ((C1 && Src0AS == UninitializedAddressSpace) ||
631 (C0 && Src1AS == UninitializedAddressSpace))
632 return None;
633
634 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
635 NewAS = Src1AS;
636 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
637 NewAS = Src0AS;
638 else
639 NewAS = joinAddressSpaces(Src0AS, Src1AS);
640 } else {
641 for (Value *PtrOperand : getPointerOperands(V)) {
642 auto I = InferredAddrSpace.find(PtrOperand);
643 unsigned OperandAS = I != InferredAddrSpace.end() ?
644 I->second : PtrOperand->getType()->getPointerAddressSpace();
645
646 // join(flat, *) = flat. So we can break if NewAS is already flat.
647 NewAS = joinAddressSpaces(NewAS, OperandAS);
648 if (NewAS == FlatAddrSpace)
649 break;
650 }
Jingyue Wu13755602016-03-20 20:59:20 +0000651 }
652
653 unsigned OldAS = InferredAddrSpace.lookup(&V);
Matt Arsenault42b64782017-01-30 23:02:12 +0000654 assert(OldAS != FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000655 if (OldAS == NewAS)
656 return None;
657 return NewAS;
658}
659
Matt Arsenault6c907a92017-01-31 01:40:38 +0000660/// \p returns true if \p U is the pointer operand of a memory instruction with
661/// a single pointer operand that can have its address space changed by simply
662/// mutating the use to a new value.
663static bool isSimplePointerUseValidToReplace(Use &U) {
664 User *Inst = U.getUser();
665 unsigned OpNo = U.getOperandNo();
666
667 if (auto *LI = dyn_cast<LoadInst>(Inst))
668 return OpNo == LoadInst::getPointerOperandIndex() && !LI->isVolatile();
669
670 if (auto *SI = dyn_cast<StoreInst>(Inst))
671 return OpNo == StoreInst::getPointerOperandIndex() && !SI->isVolatile();
672
673 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
674 return OpNo == AtomicRMWInst::getPointerOperandIndex() && !RMW->isVolatile();
675
676 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
677 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
678 !CmpX->isVolatile();
679 }
680
681 return false;
682}
683
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000684/// Update memory intrinsic uses that require more complex processing than
685/// simple memory instructions. Thse require re-mangling and may have multiple
686/// pointer operands.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000687static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
688 Value *NewV) {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000689 IRBuilder<> B(MI);
690 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
691 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
692 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
693
694 if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
695 B.CreateMemSet(NewV, MSI->getValue(),
696 MSI->getLength(), MSI->getAlignment(),
697 false, // isVolatile
698 TBAA, ScopeMD, NoAliasMD);
699 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
700 Value *Src = MTI->getRawSource();
701 Value *Dest = MTI->getRawDest();
702
703 // Be careful in case this is a self-to-self copy.
704 if (Src == OldV)
705 Src = NewV;
706
707 if (Dest == OldV)
708 Dest = NewV;
709
710 if (isa<MemCpyInst>(MTI)) {
711 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
712 B.CreateMemCpy(Dest, Src, MTI->getLength(),
713 MTI->getAlignment(),
714 false, // isVolatile
715 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
716 } else {
717 assert(isa<MemMoveInst>(MTI));
718 B.CreateMemMove(Dest, Src, MTI->getLength(),
719 MTI->getAlignment(),
720 false, // isVolatile
721 TBAA, ScopeMD, NoAliasMD);
722 }
723 } else
724 llvm_unreachable("unhandled MemIntrinsic");
725
726 MI->eraseFromParent();
727 return true;
728}
729
Matt Arsenault72f259b2017-01-31 02:17:32 +0000730// \p returns true if it is OK to change the address space of constant \p C with
731// a ConstantExpr addrspacecast.
732bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const {
Matt Arsenault30083602017-02-02 03:37:22 +0000733 assert(NewAS != UninitializedAddressSpace);
734
Matt Arsenault2a46d812017-01-31 23:48:40 +0000735 unsigned SrcAS = C->getType()->getPointerAddressSpace();
736 if (SrcAS == NewAS || isa<UndefValue>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000737 return true;
738
Matt Arsenault2a46d812017-01-31 23:48:40 +0000739 // Prevent illegal casts between different non-flat address spaces.
740 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
741 return false;
742
743 if (isa<ConstantPointerNull>(C))
Matt Arsenault72f259b2017-01-31 02:17:32 +0000744 return true;
745
746 if (auto *Op = dyn_cast<Operator>(C)) {
747 // If we already have a constant addrspacecast, it should be safe to cast it
748 // off.
749 if (Op->getOpcode() == Instruction::AddrSpaceCast)
750 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
751
752 if (Op->getOpcode() == Instruction::IntToPtr &&
753 Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
754 return true;
755 }
756
757 return false;
758}
759
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000760static Value::use_iterator skipToNextUser(Value::use_iterator I,
761 Value::use_iterator End) {
762 User *CurUser = I->getUser();
763 ++I;
764
765 while (I != End && I->getUser() == CurUser)
766 ++I;
767
768 return I;
769}
770
Matt Arsenault850657a2017-01-31 01:10:58 +0000771bool InferAddressSpaces::rewriteWithNewAddressSpaces(
772 const std::vector<Value *> &Postorder,
773 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000774 // For each address expression to be modified, creates a clone of it with its
775 // pointer operands converted to the new address space. Since the pointer
776 // operands are converted, the clone is naturally in the new address space by
777 // construction.
778 ValueToValueMapTy ValueWithNewAddrSpace;
779 SmallVector<const Use *, 32> UndefUsesToFix;
780 for (Value* V : Postorder) {
781 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
782 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
783 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000784 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000785 }
786 }
787
788 if (ValueWithNewAddrSpace.empty())
789 return false;
790
791 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
Matt Arsenaultdb6e9e82017-02-02 00:28:25 +0000792 for (const Use *UndefUse : UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000793 User *V = UndefUse->getUser();
794 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V));
795 unsigned OperandNo = UndefUse->getOperandNo();
796 assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
797 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
798 }
799
800 // Replaces the uses of the old address expressions with the new ones.
801 for (Value *V : Postorder) {
802 Value *NewV = ValueWithNewAddrSpace.lookup(V);
803 if (NewV == nullptr)
804 continue;
805
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000806 DEBUG(dbgs() << "Replacing the uses of " << *V
807 << "\n with\n " << *NewV << '\n');
808
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000809 Value::use_iterator I, E, Next;
810 for (I = V->use_begin(), E = V->use_end(); I != E; ) {
811 Use &U = *I;
812
813 // Some users may see the same pointer operand in multiple operands. Skip
814 // to the next instruction.
815 I = skipToNextUser(I, E);
816
817 if (isSimplePointerUseValidToReplace(U)) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000818 // If V is used as the pointer operand of a compatible memory operation,
819 // sets the pointer operand to NewV. This replacement does not change
820 // the element type, so the resultant load/store is still valid.
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000821 U.set(NewV);
822 continue;
823 }
824
825 User *CurUser = U.getUser();
826 // Handle more complex cases like intrinsic that need to be remangled.
827 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
828 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
829 continue;
830 }
831
832 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
833 if (rewriteIntrinsicOperands(II, V, NewV))
834 continue;
835 }
836
837 if (isa<Instruction>(CurUser)) {
Matt Arsenault72f259b2017-01-31 02:17:32 +0000838 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
839 // If we can infer that both pointers are in the same addrspace,
840 // transform e.g.
841 // %cmp = icmp eq float* %p, %q
842 // into
843 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
844
845 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
846 int SrcIdx = U.getOperandNo();
847 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
848 Value *OtherSrc = Cmp->getOperand(OtherIdx);
849
850 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
851 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
852 Cmp->setOperand(OtherIdx, OtherNewV);
853 Cmp->setOperand(SrcIdx, NewV);
854 continue;
855 }
856 }
857
858 // Even if the type mismatches, we can cast the constant.
859 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
860 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
861 Cmp->setOperand(SrcIdx, NewV);
862 Cmp->setOperand(OtherIdx,
863 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
864 continue;
865 }
866 }
867 }
868
Matt Arsenault850657a2017-01-31 01:10:58 +0000869 // Otherwise, replaces the use with flat(NewV).
Jingyue Wu13755602016-03-20 20:59:20 +0000870 if (Instruction *I = dyn_cast<Instruction>(V)) {
871 BasicBlock::iterator InsertPos = std::next(I->getIterator());
872 while (isa<PHINode>(InsertPos))
873 ++InsertPos;
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000874 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
Jingyue Wu13755602016-03-20 20:59:20 +0000875 } else {
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000876 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
877 V->getType()));
Jingyue Wu13755602016-03-20 20:59:20 +0000878 }
879 }
880 }
Matt Arsenault6d5a8d42017-01-31 01:56:57 +0000881
Jingyue Wu13755602016-03-20 20:59:20 +0000882 if (V->use_empty())
883 RecursivelyDeleteTriviallyDeadInstructions(V);
884 }
885
886 return true;
887}
888
Matt Arsenault850657a2017-01-31 01:10:58 +0000889FunctionPass *llvm::createInferAddressSpacesPass() {
890 return new InferAddressSpaces();
Jingyue Wu13755602016-03-20 20:59:20 +0000891}