LLVM 24.0.0git
InferAddressSpaces.cpp
Go to the documentation of this file.
1//===- InferAddressSpace.cpp - --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// CUDA C/C++ includes memory space designation as variable type qualifers (such
10// as __global__ and __shared__). Knowing the space of a memory access allows
11// CUDA compilers to emit faster PTX loads and stores. For example, a load from
12// shared memory can be translated to `ld.shared` which is roughly 10% faster
13// than a generic `ld` on an NVIDIA Tesla K40c.
14//
15// Unfortunately, type qualifiers only apply to variable declarations, so CUDA
16// compilers must infer the memory space of an address expression from
17// type-qualified variables.
18//
19// LLVM IR uses non-zero (so-called) specific address spaces to represent memory
20// spaces (e.g. addrspace(3) means shared memory). The Clang frontend
21// places only type-qualified variables in specific address spaces, and then
22// conservatively `addrspacecast`s each type-qualified variable to addrspace(0)
23// (so-called the generic address space) for other instructions to use.
24//
25// For example, the Clang translates the following CUDA code
26// __shared__ float a[10];
27// float v = a[i];
28// to
29// %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]*
30// %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i
31// %v = load float, float* %1 ; emits ld.f32
32// @a is in addrspace(3) since it's type-qualified, but its use from %1 is
33// redirected to %0 (the generic version of @a).
34//
35// The optimization implemented in this file propagates specific address spaces
36// from type-qualified variable declarations to its users. For example, it
37// optimizes the above IR to
38// %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i
39// %v = load float addrspace(3)* %1 ; emits ld.shared.f32
40// propagating the addrspace(3) from @a to %1. As the result, the NVPTX
41// codegen is able to emit ld.shared.f32 for %v.
42//
43// Address space inference works in two steps. First, it uses a data-flow
44// analysis to infer as many generic pointers as possible to point to only one
45// specific address space. In the above example, it can prove that %1 only
46// points to addrspace(3). This algorithm was published in
47// CUDA: Compiling and optimizing for a GPU platform
48// Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang
49// ICCS 2012
50//
51// Then, address space inference replaces all refinable generic pointers with
52// equivalent specific pointers.
53//
54// The major challenge of implementing this optimization is handling PHINodes,
55// which may create loops in the data flow graph. This brings two complications.
56//
57// First, the data flow analysis in Step 1 needs to be circular. For example,
58// %generic.input = addrspacecast float addrspace(3)* %input to float*
59// loop:
60// %y = phi [ %generic.input, %y2 ]
61// %y2 = getelementptr %y, 1
62// %v = load %y2
63// br ..., label %loop, ...
64// proving %y specific requires proving both %generic.input and %y2 specific,
65// but proving %y2 specific circles back to %y. To address this complication,
66// the data flow analysis operates on a lattice:
67// uninitialized > specific address spaces > generic.
68// All address expressions (our implementation only considers phi, bitcast,
69// addrspacecast, and getelementptr) start with the uninitialized address space.
70// The monotone transfer function moves the address space of a pointer down a
71// lattice path from uninitialized to specific and then to generic. A join
72// operation of two different specific address spaces pushes the expression down
73// to the generic address space. The analysis completes once it reaches a fixed
74// point.
75//
76// Second, IR rewriting in Step 2 also needs to be circular. For example,
77// converting %y to addrspace(3) requires the compiler to know the converted
78// %y2, but converting %y2 needs the converted %y. To address this complication,
79// we break these cycles using "poison" 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 `poison` and fix all the uses later.
82// For instance, our algorithm first converts %y to
83// %y' = phi float addrspace(3)* [ %input, poison ]
84// Then, it converts %y2 to
85// %y2' = getelementptr %y', 1
86// Finally, it fixes the poison in %y' so that
87// %y' = phi float addrspace(3)* [ %input, %y2' ]
88//
89//===----------------------------------------------------------------------===//
90
92#include "llvm/ADT/ArrayRef.h"
93#include "llvm/ADT/DenseMap.h"
94#include "llvm/ADT/DenseSet.h"
95#include "llvm/ADT/SetVector.h"
100#include "llvm/IR/Argument.h"
101#include "llvm/IR/BasicBlock.h"
102#include "llvm/IR/Constant.h"
103#include "llvm/IR/Constants.h"
104#include "llvm/IR/Dominators.h"
105#include "llvm/IR/Function.h"
106#include "llvm/IR/IRBuilder.h"
107#include "llvm/IR/InstIterator.h"
108#include "llvm/IR/Instruction.h"
109#include "llvm/IR/Instructions.h"
111#include "llvm/IR/Intrinsics.h"
112#include "llvm/IR/LLVMContext.h"
113#include "llvm/IR/Operator.h"
114#include "llvm/IR/PassManager.h"
115#include "llvm/IR/PatternMatch.h"
116#include "llvm/IR/Type.h"
117#include "llvm/IR/Use.h"
118#include "llvm/IR/User.h"
119#include "llvm/IR/Value.h"
120#include "llvm/IR/ValueHandle.h"
122#include "llvm/Pass.h"
123#include "llvm/Support/Casting.h"
125#include "llvm/Support/Debug.h"
132#include <cassert>
133#include <iterator>
134#include <limits>
135#include <optional>
136#include <utility>
137#include <vector>
138
139#define DEBUG_TYPE "infer-address-spaces"
140
141using namespace llvm;
142using namespace llvm::PatternMatch;
143
145 "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
146 cl::desc("The default address space is assumed as the flat address space. "
147 "This is mainly for test purpose."));
148
149static const unsigned UninitializedAddressSpace =
150 std::numeric_limits<unsigned>::max();
151
152namespace {
153
154using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
155// Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on
156// the *def* of a value, PredicatedAddrSpaceMapTy is map where a new
157// addrspace is inferred on the *use* of a pointer. This map is introduced to
158// infer addrspace from the addrspace predicate assumption built from assume
159// intrinsic. In that scenario, only specific uses (under valid assumption
160// context) could be inferred with a new addrspace.
161using PredicatedAddrSpaceMapTy =
163using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
164
165class InferAddressSpaces : public FunctionPass {
166 unsigned FlatAddrSpace = 0;
167
168public:
169 static char ID;
170
171 InferAddressSpaces()
172 : FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {
174 }
175 InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {
177 }
178
179 void getAnalysisUsage(AnalysisUsage &AU) const override {
180 AU.setPreservesCFG();
181 AU.addRequired<AssumptionCacheTracker>();
182 AU.addRequired<TargetTransformInfoWrapperPass>();
183 }
184
185 bool runOnFunction(Function &F) override;
186};
187
188class InferAddressSpacesImpl {
189 AssumptionCache &AC;
190 Function *F = nullptr;
191 const DominatorTree *DT = nullptr;
192 const TargetTransformInfo *TTI = nullptr;
193 const DataLayout *DL = nullptr;
194
195 /// Target specific address space which uses of should be replaced if
196 /// possible.
197 unsigned FlatAddrSpace = 0;
198 DenseMap<const Value *, Value *> PtrIntCastPairs;
199
200 // Tries to find if the inttoptr instruction is derived from an pointer have
201 // specific address space, and is safe to propagate the address space to the
202 // new pointer that inttoptr produces.
203 Value *getIntToPtrPointerOperand(const Operator *I2P) const;
204 // Tries to find if the inttoptr instruction is derived from an pointer have
205 // specific address space, and is safe to propagate the address space to the
206 // new pointer that inttoptr produces. If the old pointer is found, cache the
207 // <OldPtr, inttoptr> pairs to a map.
208 void collectIntToPtrPointerOperand();
209 // Check if an old pointer is found ahead of time. The safety has been checked
210 // when collecting the inttoptr original pointer and the result is cached in
211 // PtrIntCastPairs.
212 bool isSafeToCastIntToPtrAddrSpace(const Operator *I2P) const {
213 return PtrIntCastPairs.contains(I2P);
214 }
215 bool isAddressExpression(const Value &V, const DataLayout &DL,
216 const TargetTransformInfo *TTI) const;
217 Value *cloneConstantExprWithNewAddressSpace(
218 ConstantExpr *CE, unsigned NewAddrSpace,
219 const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
220 const TargetTransformInfo *TTI) const;
221
222 SmallVector<Value *, 2>
223 getPointerOperands(const Value &V, const DataLayout &DL,
224 const TargetTransformInfo *TTI) const;
225
226 // Try to update the address space of V. If V is updated, returns true and
227 // false otherwise.
228 bool updateAddressSpace(const Value &V,
229 ValueToAddrSpaceMapTy &InferredAddrSpace,
230 PredicatedAddrSpaceMapTy &PredicatedAS) const;
231
232 // Tries to infer the specific address space of each address expression in
233 // Postorder.
234 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
235 ValueToAddrSpaceMapTy &InferredAddrSpace,
236 PredicatedAddrSpaceMapTy &PredicatedAS) const;
237
238 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
239
240 Value *clonePtrMaskWithNewAddressSpace(
241 IntrinsicInst *I, unsigned NewAddrSpace,
242 const ValueToValueMapTy &ValueWithNewAddrSpace,
243 const PredicatedAddrSpaceMapTy &PredicatedAS,
244 SmallVectorImpl<const Use *> *PoisonUsesToFix) const;
245
246 Value *cloneInstructionWithNewAddressSpace(
247 Instruction *I, unsigned NewAddrSpace,
248 const ValueToValueMapTy &ValueWithNewAddrSpace,
249 const PredicatedAddrSpaceMapTy &PredicatedAS,
250 SmallVectorImpl<const Use *> *PoisonUsesToFix) const;
251
252 void performPointerReplacement(
253 Value *V, Value *NewV, Use &U, ValueToValueMapTy &ValueWithNewAddrSpace,
254 SmallVectorImpl<Instruction *> &DeadInstructions) const;
255
256 // Changes the flat address expressions in function F to point to specific
257 // address spaces if InferredAddrSpace says so. Postorder is the postorder of
258 // all flat expressions in the use-def graph of function F.
259 bool rewriteWithNewAddressSpaces(
260 ArrayRef<WeakTrackingVH> Postorder,
261 const ValueToAddrSpaceMapTy &InferredAddrSpace,
262 const PredicatedAddrSpaceMapTy &PredicatedAS) const;
263
264 void appendsFlatAddressExpressionToPostorderStack(
265 Value *V, PostorderStackTy &PostorderStack,
266 DenseSet<Value *> &Visited) const;
267
268 bool rewriteIntrinsicOperands(IntrinsicInst *II, Value *OldV,
269 Value *NewV) const;
270 void collectRewritableIntrinsicOperands(IntrinsicInst *II,
271 PostorderStackTy &PostorderStack,
272 DenseSet<Value *> &Visited) const;
273
274 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
275
276 Value *cloneValueWithNewAddressSpace(
277 Value *V, unsigned NewAddrSpace,
278 const ValueToValueMapTy &ValueWithNewAddrSpace,
279 const PredicatedAddrSpaceMapTy &PredicatedAS,
280 SmallVectorImpl<const Use *> *PoisonUsesToFix) const;
281 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
282
283 unsigned getPredicatedAddrSpace(const Value &PtrV,
284 const Value *UserCtx) const;
285
286public:
287 InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
288 const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
289 : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
290 bool run(Function &F);
291};
292
293} // end anonymous namespace
294
295char InferAddressSpaces::ID = 0;
296
297INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
298 false, false)
301INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
303
304static Type *getPtrOrVecOfPtrsWithNewAS(Type *Ty, unsigned NewAddrSpace) {
305 assert(Ty->isPtrOrPtrVectorTy());
306 PointerType *NPT = PointerType::get(Ty->getContext(), NewAddrSpace);
307 return Ty->getWithNewType(NPT);
308}
309
310// Check whether that's no-op pointer bitcast using a pair of
311// `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
312// different address spaces.
313static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
314 const TargetTransformInfo *TTI) {
315 assert(I2P->getOpcode() == Instruction::IntToPtr);
316 auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
317 if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
318 return false;
319 // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
320 // no-op cast. Besides checking both of them are no-op casts, as the
321 // reinterpreted pointer may be used in other pointer arithmetic, we also
322 // need to double-check that through the target-specific hook. That ensures
323 // the underlying target also agrees that's a no-op address space cast and
324 // pointer bits are preserved.
325 // The current IR spec doesn't have clear rules on address space casts,
326 // especially a clear definition for pointer bits in non-default address
327 // spaces. It would be undefined if that pointer is dereferenced after an
328 // invalid reinterpret cast. Also, due to the unclearness for the meaning of
329 // bits in non-default address spaces in the current spec, the pointer
330 // arithmetic may also be undefined after invalid pointer reinterpret cast.
331 // However, as we confirm through the target hooks that it's a no-op
332 // addrspacecast, it doesn't matter since the bits should be the same.
333 unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
334 unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
336 I2P->getOperand(0)->getType(), I2P->getType(),
337 DL) &&
339 P2I->getOperand(0)->getType(), P2I->getType(),
340 DL) &&
341 (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
342}
343
344// Returns true if V is an address expression.
345// TODO: Currently, we only consider:
346// - arguments
347// - phi, bitcast, addrspacecast, and getelementptr operators
348bool InferAddressSpacesImpl::isAddressExpression(
349 const Value &V, const DataLayout &DL,
350 const TargetTransformInfo *TTI) const {
351
352 if (const Argument *Arg = dyn_cast<Argument>(&V))
353 return Arg->getType()->isPointerTy() &&
355
356 const Operator *Op = dyn_cast<Operator>(&V);
357 if (!Op)
358 return false;
359
360 switch (Op->getOpcode()) {
361 case Instruction::PHI:
362 assert(Op->getType()->isPtrOrPtrVectorTy());
363 return true;
364 case Instruction::BitCast:
365 case Instruction::AddrSpaceCast:
366 case Instruction::GetElementPtr:
367 return true;
368 case Instruction::Select:
369 return Op->getType()->isPtrOrPtrVectorTy();
370 case Instruction::Call: {
371 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
372 return II && II->getIntrinsicID() == Intrinsic::ptrmask;
373 }
374 case Instruction::IntToPtr:
375 return isNoopPtrIntCastPair(Op, DL, TTI) ||
376 isSafeToCastIntToPtrAddrSpace(Op);
377 default:
378 // That value is an address expression if it has an assumed address space.
380 }
381}
382
383// Returns the pointer operands of V.
384//
385// Precondition: V is an address expression.
386SmallVector<Value *, 2> InferAddressSpacesImpl::getPointerOperands(
387 const Value &V, const DataLayout &DL,
388 const TargetTransformInfo *TTI) const {
389 if (isa<Argument>(&V))
390 return {};
391
392 const Operator &Op = cast<Operator>(V);
393 switch (Op.getOpcode()) {
394 case Instruction::PHI: {
395 auto IncomingValues = cast<PHINode>(Op).incoming_values();
396 return {IncomingValues.begin(), IncomingValues.end()};
397 }
398 case Instruction::BitCast:
399 case Instruction::AddrSpaceCast:
400 case Instruction::GetElementPtr:
401 return {Op.getOperand(0)};
402 case Instruction::Select:
403 return {Op.getOperand(1), Op.getOperand(2)};
404 case Instruction::Call: {
405 const IntrinsicInst &II = cast<IntrinsicInst>(Op);
406 assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
407 "unexpected intrinsic call");
408 return {II.getArgOperand(0)};
409 }
410 case Instruction::IntToPtr: {
411 if (isNoopPtrIntCastPair(&Op, DL, TTI)) {
412 auto *P2I = cast<Operator>(Op.getOperand(0));
413 return {P2I->getOperand(0)};
414 }
415 assert(isSafeToCastIntToPtrAddrSpace(&Op));
416 return {getIntToPtrPointerOperand(&Op)};
417 }
418 default:
419 llvm_unreachable("Unexpected instruction type.");
420 }
421}
422
423// Return mask. The 1 in mask indicate the bit is changed.
424// This helper function is to compute the max know changed bits for ptr1 and
425// ptr2 after the operation `ptr2 = ptr1 Op Mask`.
426static APInt computeMaxChangedPtrBits(const Operator *Op, const Value *Mask,
427 const DataLayout &DL, AssumptionCache *AC,
428 const DominatorTree *DT) {
429 KnownBits Known = computeKnownBits(Mask, DL, AC, nullptr, DT);
430 switch (Op->getOpcode()) {
431 case Instruction::Xor:
432 case Instruction::Or:
433 return ~Known.Zero;
434 case Instruction::And:
435 return ~Known.One;
436 default:
437 return APInt::getAllOnes(Known.getBitWidth());
438 }
439}
440
441Value *
442InferAddressSpacesImpl::getIntToPtrPointerOperand(const Operator *I2P) const {
443 assert(I2P->getOpcode() == Instruction::IntToPtr);
444 if (I2P->getType()->isVectorTy())
445 return nullptr;
446
447 // If I2P has been accessed and has the corresponding old pointer value, just
448 // return true.
449 if (auto *OldPtr = PtrIntCastPairs.lookup(I2P))
450 return OldPtr;
451
452 Value *LogicalOp = I2P->getOperand(0);
453 Value *OldPtr, *Mask;
454 if (!match(LogicalOp,
455 m_c_BitwiseLogic(m_PtrToInt(m_Value(OldPtr)), m_Value(Mask))))
456 return nullptr;
457
459 if (!AsCast)
460 return nullptr;
461
462 unsigned SrcAS = I2P->getType()->getPointerAddressSpace();
463 unsigned DstAS = AsCast->getOperand(0)->getType()->getPointerAddressSpace();
464 APInt PreservedPtrMask = TTI->getAddrSpaceCastPreservedPtrMask(SrcAS, DstAS);
465 if (PreservedPtrMask.isZero())
466 return nullptr;
467 APInt ChangedPtrBits =
468 computeMaxChangedPtrBits(cast<Operator>(LogicalOp), Mask, *DL, &AC, DT);
469 // Check if the address bits change is within the preserved mask. If the bits
470 // change is not preserved, it is not safe to perform address space cast.
471 // The following pattern is not safe to cast address space.
472 // %1 = ptrtoint ptr addrspace(3) %sp to i32
473 // %2 = zext i32 %1 to i64
474 // %gp = inttoptr i64 %2 to ptr
475 assert(ChangedPtrBits.getBitWidth() == PreservedPtrMask.getBitWidth());
476 if (ChangedPtrBits.isSubsetOf(PreservedPtrMask))
477 return OldPtr;
478
479 return nullptr;
480}
481
482void InferAddressSpacesImpl::collectIntToPtrPointerOperand() {
483 // Only collect inttoptr instruction.
484 // TODO: We need to collect inttoptr constant expression as well.
485 for (Instruction &I : instructions(F)) {
487 continue;
488 if (auto *OldPtr = getIntToPtrPointerOperand(cast<Operator>(&I)))
489 PtrIntCastPairs.insert({&I, OldPtr});
490 }
491}
492
493bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
494 Value *OldV,
495 Value *NewV) const {
496 Module *M = II->getParent()->getParent()->getParent();
497 Intrinsic::ID IID = II->getIntrinsicID();
498 switch (IID) {
499 case Intrinsic::objectsize:
500 case Intrinsic::masked_load: {
501 Type *DestTy = II->getType();
502 Type *SrcTy = NewV->getType();
503 Function *NewDecl =
504 Intrinsic::getOrInsertDeclaration(M, IID, {DestTy, SrcTy});
505 II->setArgOperand(0, NewV);
506 II->setCalledFunction(NewDecl);
507 return true;
508 }
509 case Intrinsic::ptrmask:
510 // This is handled as an address expression, not as a use memory operation.
511 return false;
512 case Intrinsic::masked_gather: {
513 Type *RetTy = II->getType();
514 Type *NewPtrTy = NewV->getType();
515 Function *NewDecl =
516 Intrinsic::getOrInsertDeclaration(M, IID, {RetTy, NewPtrTy});
517 II->setArgOperand(0, NewV);
518 II->setCalledFunction(NewDecl);
519 return true;
520 }
521 case Intrinsic::masked_store:
522 case Intrinsic::masked_scatter: {
523 Type *ValueTy = II->getOperand(0)->getType();
524 Type *NewPtrTy = NewV->getType();
526 M, II->getIntrinsicID(), {ValueTy, NewPtrTy});
527 II->setArgOperand(1, NewV);
528 II->setCalledFunction(NewDecl);
529 return true;
530 }
531 case Intrinsic::prefetch:
532 case Intrinsic::is_constant: {
534 M, II->getIntrinsicID(), {NewV->getType()});
535 II->setArgOperand(0, NewV);
536 II->setCalledFunction(NewDecl);
537 return true;
538 }
539 case Intrinsic::fake_use: {
540 II->replaceUsesOfWith(OldV, NewV);
541 return true;
542 }
543 case Intrinsic::lifetime_start:
544 case Intrinsic::lifetime_end: {
545 // Always force lifetime markers to work directly on the alloca.
546 NewV = NewV->stripPointerCasts();
548 M, II->getIntrinsicID(), {NewV->getType()});
549 II->setArgOperand(0, NewV);
550 II->setCalledFunction(NewDecl);
551 return true;
552 }
553 default: {
554 Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
555 if (!Rewrite)
556 return false;
557 if (Rewrite != II)
558 II->replaceAllUsesWith(Rewrite);
559 return true;
560 }
561 }
562}
563
564void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
565 IntrinsicInst *II, PostorderStackTy &PostorderStack,
566 DenseSet<Value *> &Visited) const {
567 auto IID = II->getIntrinsicID();
568 switch (IID) {
569 case Intrinsic::ptrmask:
570 case Intrinsic::objectsize:
571 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
572 PostorderStack, Visited);
573 break;
574 case Intrinsic::is_constant: {
575 Value *Ptr = II->getArgOperand(0);
576 if (Ptr->getType()->isPtrOrPtrVectorTy()) {
577 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
578 Visited);
579 }
580
581 break;
582 }
583 case Intrinsic::masked_load:
584 case Intrinsic::masked_gather:
585 case Intrinsic::prefetch:
586 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
587 PostorderStack, Visited);
588 break;
589 case Intrinsic::masked_store:
590 case Intrinsic::masked_scatter:
591 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(1),
592 PostorderStack, Visited);
593 break;
594 case Intrinsic::fake_use: {
595 for (Value *Op : II->operands()) {
596 if (Op->getType()->isPtrOrPtrVectorTy()) {
597 appendsFlatAddressExpressionToPostorderStack(Op, PostorderStack,
598 Visited);
599 }
600 }
601
602 break;
603 }
604 case Intrinsic::lifetime_start:
605 case Intrinsic::lifetime_end: {
606 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
607 PostorderStack, Visited);
608 break;
609 }
610 default:
611 SmallVector<int, 2> OpIndexes;
612 if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
613 for (int Idx : OpIndexes) {
614 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
615 PostorderStack, Visited);
616 }
617 }
618 break;
619 }
620}
621
622// Returns all flat address expressions in function F. The elements are
623// If V is an unvisited flat address expression, appends V to PostorderStack
624// and marks it as visited.
625void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
626 Value *V, PostorderStackTy &PostorderStack,
627 DenseSet<Value *> &Visited) const {
628 assert(V->getType()->isPtrOrPtrVectorTy());
629
630 // Generic addressing expressions may be hidden in nested constant
631 // expressions.
632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
633 // TODO: Look in non-address parts, like icmp operands.
634 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
635 PostorderStack.emplace_back(CE, false);
636
637 return;
638 }
639
640 if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
641 isAddressExpression(*V, *DL, TTI)) {
642 if (Visited.insert(V).second) {
643 PostorderStack.emplace_back(V, false);
644
645 if (auto *Op = dyn_cast<Operator>(V))
646 for (auto &O : Op->operands())
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(O))
648 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
649 PostorderStack.emplace_back(CE, false);
650 }
651 }
652}
653
654// Returns all flat address expressions in function F. The elements are ordered
655// in postorder.
656std::vector<WeakTrackingVH>
657InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
658 // This function implements a non-recursive postorder traversal of a partial
659 // use-def graph of function F.
660 PostorderStackTy PostorderStack;
661 // The set of visited expressions.
662 DenseSet<Value *> Visited;
663
664 auto PushPtrOperand = [&](Value *Ptr) {
665 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack, Visited);
666 };
667
668 // Look at operations that may be interesting accelerate by moving to a known
669 // address space. We aim at generating after loads and stores, but pure
670 // addressing calculations may also be faster.
671 for (Instruction &I : instructions(F)) {
672 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
673 PushPtrOperand(GEP->getPointerOperand());
674 } else if (auto *LI = dyn_cast<LoadInst>(&I))
675 PushPtrOperand(LI->getPointerOperand());
676 else if (auto *SI = dyn_cast<StoreInst>(&I))
677 PushPtrOperand(SI->getPointerOperand());
678 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
679 PushPtrOperand(RMW->getPointerOperand());
680 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
681 PushPtrOperand(CmpX->getPointerOperand());
682 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
683 // For memset/memcpy/memmove, any pointer operand can be replaced.
684 PushPtrOperand(MI->getRawDest());
685
686 // Handle 2nd operand for memcpy/memmove.
687 if (auto *MTI = dyn_cast<MemTransferInst>(MI))
688 PushPtrOperand(MTI->getRawSource());
689 } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
690 collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
691 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
692 if (Cmp->getOperand(0)->getType()->isPtrOrPtrVectorTy()) {
693 PushPtrOperand(Cmp->getOperand(0));
694 PushPtrOperand(Cmp->getOperand(1));
695 }
696 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
697 PushPtrOperand(ASC->getPointerOperand());
698 } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
700 PushPtrOperand(cast<Operator>(I2P->getOperand(0))->getOperand(0));
701 else if (isSafeToCastIntToPtrAddrSpace(cast<Operator>(I2P)))
702 PushPtrOperand(getIntToPtrPointerOperand(cast<Operator>(I2P)));
703 } else if (auto *RI = dyn_cast<ReturnInst>(&I)) {
704 if (auto *RV = RI->getReturnValue();
705 RV && RV->getType()->isPtrOrPtrVectorTy())
706 PushPtrOperand(RV);
707 }
708 }
709
710 std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
711 while (!PostorderStack.empty()) {
712 Value *TopVal = PostorderStack.back().getPointer();
713 // If the operands of the expression on the top are already explored,
714 // adds that expression to the resultant postorder.
715 if (PostorderStack.back().getInt()) {
716 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
717 Postorder.push_back(TopVal);
718 PostorderStack.pop_back();
719 continue;
720 }
721 // Otherwise, adds its operands to the stack and explores them.
722 PostorderStack.back().setInt(true);
723 // Skip values with an assumed address space.
725 for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
726 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
727 Visited);
728 }
729 }
730 }
731 return Postorder;
732}
733
734// Inserts an addrspacecast for a phi node operand, handling the proper
735// insertion position based on the operand type.
737 Value *Operand) {
738 auto InsertBefore = [NewI](auto It) {
739 NewI->insertBefore(It);
740 NewI->setDebugLoc(It->getDebugLoc());
741 return NewI;
742 };
743
744 if (auto *Arg = dyn_cast<Argument>(Operand)) {
745 // For arguments, insert the cast at the beginning of entry block.
746 // Consider inserting at the dominating block for better placement.
747 Function *F = Arg->getParent();
748 auto InsertI = F->getEntryBlock().getFirstNonPHIIt();
749 return InsertBefore(InsertI);
750 }
751
752 // No check for Constant here, as constants are already handled.
753 assert(isa<Instruction>(Operand));
754
755 Instruction *OpInst = cast<Instruction>(Operand);
756 if (LLVM_UNLIKELY(OpInst->getOpcode() == Instruction::PHI)) {
757 // If the operand is defined by another PHI node, insert after the first
758 // non-PHI instruction at the corresponding basic block.
759 auto InsertI = OpInst->getParent()->getFirstNonPHIIt();
760 return InsertBefore(InsertI);
761 }
762
763 // Otherwise, insert immediately after the operand definition.
764 NewI->insertAfter(OpInst->getIterator());
765 NewI->setDebugLoc(OpInst->getDebugLoc());
766 return NewI;
767}
768
769// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
770// of OperandUse.get() in the new address space. If the clone is not ready yet,
771// returns poison in the new address space as a placeholder.
773 const Use &OperandUse, unsigned NewAddrSpace,
774 const ValueToValueMapTy &ValueWithNewAddrSpace,
775 const PredicatedAddrSpaceMapTy &PredicatedAS,
776 SmallVectorImpl<const Use *> *PoisonUsesToFix) {
777 Value *Operand = OperandUse.get();
778
779 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAddrSpace);
780
781 if (Constant *C = dyn_cast<Constant>(Operand))
782 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
783
784 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
785 return NewOperand;
786
787 Instruction *Inst = cast<Instruction>(OperandUse.getUser());
788 auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
789 if (I != PredicatedAS.end()) {
790 // Insert an addrspacecast on that operand before the user.
791 unsigned NewAS = I->second;
792 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAS);
793 auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
794
795 if (LLVM_UNLIKELY(Inst->getOpcode() == Instruction::PHI))
796 return phiNodeOperandWithNewAddressSpace(NewI, Operand);
797
798 NewI->insertBefore(Inst->getIterator());
799 NewI->setDebugLoc(Inst->getDebugLoc());
800 return NewI;
801 }
802
803 PoisonUsesToFix->push_back(&OperandUse);
804 return PoisonValue::get(NewPtrTy);
805}
806
807// A helper function for cloneInstructionWithNewAddressSpace. Handles the
808// conversion of a ptrmask intrinsic instruction.
809Value *InferAddressSpacesImpl::clonePtrMaskWithNewAddressSpace(
810 IntrinsicInst *I, unsigned NewAddrSpace,
811 const ValueToValueMapTy &ValueWithNewAddrSpace,
812 const PredicatedAddrSpaceMapTy &PredicatedAS,
813 SmallVectorImpl<const Use *> *PoisonUsesToFix) const {
814 const Use &PtrOpUse = I->getArgOperandUse(0);
815 unsigned OldAddrSpace = PtrOpUse->getType()->getPointerAddressSpace();
816 Value *MaskOp = I->getArgOperand(1);
817 Type *MaskTy = MaskOp->getType();
818
819 KnownBits OldPtrBits{DL->getPointerSizeInBits(OldAddrSpace)};
820 KnownBits NewPtrBits{DL->getPointerSizeInBits(NewAddrSpace)};
821 if (!TTI->isNoopAddrSpaceCast(OldAddrSpace, NewAddrSpace)) {
822 std::tie(OldPtrBits, NewPtrBits) =
823 TTI->computeKnownBitsAddrSpaceCast(NewAddrSpace, *PtrOpUse.get());
824 }
825
826 // If the pointers in both addrspaces have a bitwise representation and if the
827 // representation of the new pointer is smaller (fewer bits) than the old one,
828 // check if the mask is applicable to the ptr in the new addrspace. Any
829 // masking only clearing the low bits will also apply in the new addrspace
830 // Note: checking if the mask clears high bits is not sufficient as those
831 // might have already been 0 in the old ptr.
832 if (OldPtrBits.getBitWidth() > NewPtrBits.getBitWidth()) {
833 KnownBits MaskBits =
834 computeKnownBits(MaskOp, *DL, /*AssumptionCache=*/nullptr, I);
835 // Set all unknown bits of the old ptr to 1, so that we are conservative in
836 // checking which bits are cleared by the mask.
837 OldPtrBits.One |= ~OldPtrBits.Zero;
838 // Check which bits are cleared by the mask in the old ptr.
839 KnownBits ClearedBits = KnownBits::sub(OldPtrBits, OldPtrBits & MaskBits);
840
841 // If the mask isn't applicable to the new ptr, leave the ptrmask as-is and
842 // insert an addrspacecast after it.
843 if (ClearedBits.countMaxActiveBits() > NewPtrBits.countMaxActiveBits()) {
844 std::optional<BasicBlock::iterator> InsertPoint =
845 I->getInsertionPointAfterDef();
846 assert(InsertPoint && "insertion after ptrmask should be possible");
847 Type *NewPtrType = getPtrOrVecOfPtrsWithNewAS(I->getType(), NewAddrSpace);
848 Instruction *AddrSpaceCast =
849 new AddrSpaceCastInst(I, NewPtrType, "", *InsertPoint);
850 AddrSpaceCast->setDebugLoc(I->getDebugLoc());
851 return AddrSpaceCast;
852 }
853 }
854
855 IRBuilder<> B(I);
856 if (NewPtrBits.getBitWidth() < MaskTy->getScalarSizeInBits()) {
857 MaskTy = MaskTy->getWithNewBitWidth(NewPtrBits.getBitWidth());
858 MaskOp = B.CreateTrunc(MaskOp, MaskTy);
859 }
861 PtrOpUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
862 PoisonUsesToFix);
863 return B.CreateIntrinsic(Intrinsic::ptrmask, {NewPtr->getType(), MaskTy},
864 {NewPtr, MaskOp});
865}
866
867// Returns a clone of `I` with its operands converted to those specified in
868// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
869// operand whose address space needs to be modified might not exist in
870// ValueWithNewAddrSpace. In that case, uses poison as a placeholder operand and
871// adds that operand use to PoisonUsesToFix so that caller can fix them later.
872//
873// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
874// from a pointer whose type already matches. Therefore, this function returns a
875// Value* instead of an Instruction*.
876Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
877 Instruction *I, unsigned NewAddrSpace,
878 const ValueToValueMapTy &ValueWithNewAddrSpace,
879 const PredicatedAddrSpaceMapTy &PredicatedAS,
880 SmallVectorImpl<const Use *> *PoisonUsesToFix) const {
881 Type *NewPtrType = getPtrOrVecOfPtrsWithNewAS(I->getType(), NewAddrSpace);
882
883 if (I->getOpcode() == Instruction::AddrSpaceCast) {
884 Value *Src = I->getOperand(0);
885 // Because `I` is flat, the source address space must be specific.
886 // Therefore, the inferred address space must be the source space, according
887 // to our algorithm.
888 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
889 return Src;
890 }
891
892 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
893 // Technically the intrinsic ID is a pointer typed argument, so specially
894 // handle calls early.
895 assert(II->getIntrinsicID() == Intrinsic::ptrmask);
896 return clonePtrMaskWithNewAddressSpace(
897 II, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, PoisonUsesToFix);
898 }
899
900 unsigned AS = TTI->getAssumedAddrSpace(I);
901 if (AS != UninitializedAddressSpace) {
902 // For the assumed address space, insert an `addrspacecast` to make that
903 // explicit.
904 Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(I->getType(), AS);
905 auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
906 NewI->insertAfter(I->getIterator());
907 NewI->setDebugLoc(I->getDebugLoc());
908 return NewI;
909 }
910
911 // Computes the converted pointer operands.
912 SmallVector<Value *, 4> NewPointerOperands;
913 for (const Use &OperandUse : I->operands()) {
914 if (!OperandUse.get()->getType()->isPtrOrPtrVectorTy())
915 NewPointerOperands.push_back(nullptr);
916 else
918 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
919 PoisonUsesToFix));
920 }
921
922 switch (I->getOpcode()) {
923 case Instruction::BitCast:
924 return new BitCastInst(NewPointerOperands[0], NewPtrType);
925 case Instruction::PHI: {
926 assert(I->getType()->isPtrOrPtrVectorTy());
927 PHINode *PHI = cast<PHINode>(I);
928 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
929 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
930 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
931 NewPHI->addIncoming(NewPointerOperands[OperandNo],
932 PHI->getIncomingBlock(Index));
933 }
934 return NewPHI;
935 }
936 case Instruction::GetElementPtr: {
937 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
938 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
939 GEP->getSourceElementType(), NewPointerOperands[0],
940 SmallVector<Value *, 4>(GEP->indices()));
941 NewGEP->setIsInBounds(GEP->isInBounds());
942 return NewGEP;
943 }
944 case Instruction::Select:
945 assert(I->getType()->isPtrOrPtrVectorTy());
946 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
947 NewPointerOperands[2], "", nullptr, I);
948 case Instruction::IntToPtr: {
950 Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
951 if (Src->getType() == NewPtrType)
952 return Src;
953
954 // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
955 // source address space from a generic pointer source need to insert a
956 // cast back.
957 return new AddrSpaceCastInst(Src, NewPtrType);
958 }
959 assert(isSafeToCastIntToPtrAddrSpace(cast<Operator>(I)));
960 AddrSpaceCastInst *AsCast = new AddrSpaceCastInst(I, NewPtrType);
961 AsCast->insertAfter(I);
962 return AsCast;
963 }
964 default:
965 llvm_unreachable("Unexpected opcode");
966 }
967}
968
969// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
970// constant expression `CE` with its operands replaced as specified in
971// ValueWithNewAddrSpace.
972Value *InferAddressSpacesImpl::cloneConstantExprWithNewAddressSpace(
973 ConstantExpr *CE, unsigned NewAddrSpace,
974 const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
975 const TargetTransformInfo *TTI) const {
976 Type *TargetType =
977 CE->getType()->isPtrOrPtrVectorTy()
978 ? getPtrOrVecOfPtrsWithNewAS(CE->getType(), NewAddrSpace)
979 : CE->getType();
980
981 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
982 // Because CE is flat, the source address space must be specific.
983 // Therefore, the inferred address space must be the source space according
984 // to our algorithm.
985 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
986 NewAddrSpace);
987 return CE->getOperand(0);
988 }
989
990 if (CE->getOpcode() == Instruction::BitCast) {
991 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
992 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
993 return ConstantExpr::getAddrSpaceCast(CE, TargetType);
994 }
995
996 if (CE->getOpcode() == Instruction::IntToPtr) {
997 if (isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI)) {
998 Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
999 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
1000 return Src;
1001 }
1002 assert(isSafeToCastIntToPtrAddrSpace(cast<Operator>(CE)));
1003 return ConstantExpr::getAddrSpaceCast(CE, TargetType);
1004 }
1005
1006 // Computes the operands of the new constant expression.
1007 bool IsNew = false;
1008 SmallVector<Constant *, 4> NewOperands;
1009 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
1010 Constant *Operand = CE->getOperand(Index);
1011 // If the address space of `Operand` needs to be modified, the new operand
1012 // with the new address space should already be in ValueWithNewAddrSpace
1013 // because (1) the constant expressions we consider (i.e. addrspacecast,
1014 // bitcast, and getelementptr) do not incur cycles in the data flow graph
1015 // and (2) this function is called on constant expressions in postorder.
1016 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
1017 IsNew = true;
1018 NewOperands.push_back(cast<Constant>(NewOperand));
1019 continue;
1020 }
1021 if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
1022 if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
1023 CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
1024 IsNew = true;
1025 NewOperands.push_back(cast<Constant>(NewOperand));
1026 continue;
1027 }
1028 // Otherwise, reuses the old operand.
1029 NewOperands.push_back(Operand);
1030 }
1031
1032 // If !IsNew, we will replace the Value with itself. However, replaced values
1033 // are assumed to wrapped in an addrspacecast cast later so drop it now.
1034 if (!IsNew)
1035 return nullptr;
1036
1037 if (CE->getOpcode() == Instruction::GetElementPtr) {
1038 // Needs to specify the source type while constructing a getelementptr
1039 // constant expression.
1040 return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
1041 cast<GEPOperator>(CE)->getSourceElementType());
1042 }
1043
1044 return CE->getWithOperands(NewOperands, TargetType);
1045}
1046
1047// Returns a clone of the value `V`, with its operands replaced as specified in
1048// ValueWithNewAddrSpace. This function is called on every flat address
1049// expression whose address space needs to be modified, in postorder.
1050//
1051// See cloneInstructionWithNewAddressSpace for the meaning of PoisonUsesToFix.
1052Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
1053 Value *V, unsigned NewAddrSpace,
1054 const ValueToValueMapTy &ValueWithNewAddrSpace,
1055 const PredicatedAddrSpaceMapTy &PredicatedAS,
1056 SmallVectorImpl<const Use *> *PoisonUsesToFix) const {
1057 // All values in Postorder are flat address expressions.
1058 assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
1059 isAddressExpression(*V, *DL, TTI));
1060
1061 if (auto *Arg = dyn_cast<Argument>(V)) {
1062 // Arguments are address space casted in the function body, as we do not
1063 // want to change the function signature.
1064 Function *F = Arg->getParent();
1065 BasicBlock::iterator Insert = F->getEntryBlock().getFirstNonPHIIt();
1066
1067 Type *NewPtrTy = PointerType::get(Arg->getContext(), NewAddrSpace);
1068 auto *NewI = new AddrSpaceCastInst(Arg, NewPtrTy);
1069 NewI->insertBefore(Insert);
1070 return NewI;
1071 }
1072
1073 if (Instruction *I = dyn_cast<Instruction>(V)) {
1074 Value *NewV = cloneInstructionWithNewAddressSpace(
1075 I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, PoisonUsesToFix);
1076 if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
1077 if (NewI->getParent() == nullptr) {
1078 NewI->insertBefore(I->getIterator());
1079 NewI->takeName(I);
1080 NewI->setDebugLoc(I->getDebugLoc());
1081 }
1082 }
1083 return NewV;
1084 }
1085
1086 return cloneConstantExprWithNewAddressSpace(
1087 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
1088}
1089
1090// Defines the join operation on the address space lattice (see the file header
1091// comments).
1092unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
1093 unsigned AS2) const {
1094 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
1095 return FlatAddrSpace;
1096
1097 if (AS1 == UninitializedAddressSpace)
1098 return AS2;
1099 if (AS2 == UninitializedAddressSpace)
1100 return AS1;
1101
1102 // The join of two different specific address spaces is flat.
1103 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
1104}
1105
1106bool InferAddressSpacesImpl::run(Function &CurFn) {
1107 F = &CurFn;
1108 DL = &F->getDataLayout();
1109 PtrIntCastPairs.clear();
1110
1112 FlatAddrSpace = 0;
1113
1114 if (FlatAddrSpace == UninitializedAddressSpace) {
1116 if (FlatAddrSpace == UninitializedAddressSpace)
1117 return false;
1118 }
1119
1120 collectIntToPtrPointerOperand();
1121 // Collects all flat address expressions in postorder.
1122 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(*F);
1123
1124 // Runs a data-flow analysis to refine the address spaces of every expression
1125 // in Postorder.
1126 ValueToAddrSpaceMapTy InferredAddrSpace;
1127 PredicatedAddrSpaceMapTy PredicatedAS;
1128 inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
1129
1130 // Changes the address spaces of the flat address expressions who are inferred
1131 // to point to a specific address space.
1132 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace,
1133 PredicatedAS);
1134}
1135
1136// Constants need to be tracked through RAUW to handle cases with nested
1137// constant expressions, so wrap values in WeakTrackingVH.
1138void InferAddressSpacesImpl::inferAddressSpaces(
1139 ArrayRef<WeakTrackingVH> Postorder,
1140 ValueToAddrSpaceMapTy &InferredAddrSpace,
1141 PredicatedAddrSpaceMapTy &PredicatedAS) const {
1142 SetVector<Value *> Worklist(llvm::from_range, Postorder);
1143 // Initially, all expressions are in the uninitialized address space.
1144 for (Value *V : Postorder)
1145 InferredAddrSpace[V] = UninitializedAddressSpace;
1146
1147 while (!Worklist.empty()) {
1148 Value *V = Worklist.pop_back_val();
1149
1150 // Try to update the address space of the stack top according to the
1151 // address spaces of its operands.
1152 if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
1153 continue;
1154
1155 for (Value *User : V->users()) {
1156 // Skip if User is already in the worklist.
1157 if (Worklist.count(User))
1158 continue;
1159
1160 auto Pos = InferredAddrSpace.find(User);
1161 // Our algorithm only updates the address spaces of flat address
1162 // expressions, which are those in InferredAddrSpace.
1163 if (Pos == InferredAddrSpace.end())
1164 continue;
1165
1166 // Function updateAddressSpace moves the address space down a lattice
1167 // path. Therefore, nothing to do if User is already inferred as flat (the
1168 // bottom element in the lattice).
1169 if (Pos->second == FlatAddrSpace)
1170 continue;
1171
1172 Worklist.insert(User);
1173 }
1174 }
1175}
1176
1177unsigned
1178InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &Ptr,
1179 const Value *UserCtx) const {
1180 const Instruction *UserCtxI = dyn_cast<Instruction>(UserCtx);
1181 if (!UserCtxI)
1183
1184 const Value *StrippedPtr = Ptr.stripInBoundsOffsets();
1185 for (auto &AssumeVH : AC.assumptionsFor(StrippedPtr)) {
1186 if (!AssumeVH)
1187 continue;
1188 CallInst *CI = cast<CallInst>(AssumeVH);
1189 if (!isValidAssumeForContext(CI, UserCtxI, DT))
1190 continue;
1191
1192 const Value *Ptr;
1193 unsigned AS;
1194 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
1195 if (Ptr)
1196 return AS;
1197 }
1198
1200}
1201
1202bool InferAddressSpacesImpl::updateAddressSpace(
1203 const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
1204 PredicatedAddrSpaceMapTy &PredicatedAS) const {
1205 assert(InferredAddrSpace.count(&V));
1206
1207 LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n');
1208
1209 // The new inferred address space equals the join of the address spaces
1210 // of all its pointer operands.
1211 unsigned NewAS = UninitializedAddressSpace;
1212
1213 // isAddressExpression should guarantee that V is an operator or an argument.
1215
1216 unsigned AS = TTI->getAssumedAddrSpace(&V);
1217 if (AS != UninitializedAddressSpace) {
1218 // Use the assumed address space directly.
1219 NewAS = AS;
1220 } else {
1221 // Otherwise, infer the address space from its pointer operands.
1222 SmallVector<Constant *, 2> ConstantPtrOps;
1223 SmallVector<Value *, 2> PtrOps = getPointerOperands(V, *DL, TTI);
1224 for (Value *PtrOperand : PtrOps) {
1225 auto I = InferredAddrSpace.find(PtrOperand);
1226 unsigned OperandAS;
1227 if (I == InferredAddrSpace.end()) {
1228 OperandAS = PtrOperand->getType()->getPointerAddressSpace();
1229 if (auto *C = dyn_cast<Constant>(PtrOperand);
1230 C && OperandAS == FlatAddrSpace) {
1231 // Defer joining the address space of constant pointer operands.
1232 ConstantPtrOps.push_back(C);
1233 continue;
1234 }
1235 if (OperandAS == FlatAddrSpace) {
1236 // Check AC for assumption dominating V.
1237 unsigned AS = getPredicatedAddrSpace(*PtrOperand, &V);
1238 if (AS != UninitializedAddressSpace) {
1240 << " deduce operand AS from the predicate addrspace "
1241 << AS << '\n');
1242 OperandAS = AS;
1243 // Record this use with the predicated AS.
1244 PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
1245 }
1246 }
1247 } else
1248 OperandAS = I->second;
1249
1250 // join(flat, *) = flat. So we can break if NewAS is already flat.
1251 NewAS = joinAddressSpaces(NewAS, OperandAS);
1252 if (NewAS == FlatAddrSpace)
1253 break;
1254 }
1255
1256 if (NewAS != FlatAddrSpace && NewAS != UninitializedAddressSpace) {
1257 if (any_of(ConstantPtrOps, [=](Constant *C) {
1258 return !isSafeToCastConstAddrSpace(C, NewAS);
1259 }))
1260 NewAS = FlatAddrSpace;
1261 }
1262
1263 // operator(flat const, flat const, ...) -> flat
1264 if (NewAS == UninitializedAddressSpace &&
1265 PtrOps.size() == ConstantPtrOps.size())
1266 NewAS = FlatAddrSpace;
1267 }
1268
1269 unsigned OldAS = InferredAddrSpace.lookup(&V);
1270 assert(OldAS != FlatAddrSpace);
1271 if (OldAS == NewAS)
1272 return false;
1273
1274 // If any updates are made, grabs its users to the worklist because
1275 // their address spaces can also be possibly updated.
1276 LLVM_DEBUG(dbgs() << " to " << NewAS << '\n');
1277 InferredAddrSpace[&V] = NewAS;
1278 return true;
1279}
1280
1281/// Replace operand \p OpIdx in \p Inst, if the value is the same as \p OldVal
1282/// with \p NewVal.
1283static bool replaceOperandIfSame(Instruction *Inst, unsigned OpIdx,
1284 Value *OldVal, Value *NewVal) {
1285 Use &U = Inst->getOperandUse(OpIdx);
1286 if (U.get() == OldVal) {
1287 U.set(NewVal);
1288 return true;
1289 }
1290
1291 return false;
1292}
1293
1294template <typename InstrType>
1296 InstrType *MemInstr, unsigned AddrSpace,
1297 Value *OldV, Value *NewV) {
1298 if (!MemInstr->isVolatile() || TTI.hasVolatileVariant(MemInstr, AddrSpace)) {
1299 return replaceOperandIfSame(MemInstr, InstrType::getPointerOperandIndex(),
1300 OldV, NewV);
1301 }
1302
1303 return false;
1304}
1305
1306/// If \p OldV is used as the pointer operand of a compatible memory operation
1307/// \p Inst, replaces the pointer operand with NewV.
1308///
1309/// This covers memory instructions with a single pointer operand that can have
1310/// its address space changed by simply mutating the use to a new value.
1311///
1312/// \p returns true the user replacement was made.
1314 User *Inst, unsigned AddrSpace,
1315 Value *OldV, Value *NewV) {
1316 if (auto *LI = dyn_cast<LoadInst>(Inst))
1317 return replaceSimplePointerUse(TTI, LI, AddrSpace, OldV, NewV);
1318
1319 if (auto *SI = dyn_cast<StoreInst>(Inst))
1320 return replaceSimplePointerUse(TTI, SI, AddrSpace, OldV, NewV);
1321
1322 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
1323 return replaceSimplePointerUse(TTI, RMW, AddrSpace, OldV, NewV);
1324
1325 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
1326 return replaceSimplePointerUse(TTI, CmpX, AddrSpace, OldV, NewV);
1327
1328 return false;
1329}
1330
1331/// Update memory intrinsic uses that require more complex processing than
1332/// simple memory instructions. These require re-mangling and may have multiple
1333/// pointer operands.
1335 Value *NewV) {
1336 IRBuilder<> B(MI);
1337 if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
1338 B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
1339 false, // isVolatile
1340 MI->getAAMetadata());
1341 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
1342 Value *Src = MTI->getRawSource();
1343 Value *Dest = MTI->getRawDest();
1344
1345 // Be careful in case this is a self-to-self copy.
1346 if (Src == OldV)
1347 Src = NewV;
1348
1349 if (Dest == OldV)
1350 Dest = NewV;
1351
1352 if (auto *MCI = dyn_cast<MemCpyInst>(MTI)) {
1353 if (MCI->isForceInlined())
1354 B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
1355 MTI->getSourceAlign(), MTI->getLength(),
1356 false, // isVolatile
1357 MI->getAAMetadata());
1358 else
1359 B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1360 MTI->getLength(),
1361 false, // isVolatile
1362 MI->getAAMetadata());
1363 } else {
1365 B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1366 MTI->getLength(),
1367 false, // isVolatile
1368 MI->getAAMetadata());
1369 }
1370 } else
1371 llvm_unreachable("unhandled MemIntrinsic");
1372
1373 MI->eraseFromParent();
1374 return true;
1375}
1376
1377// \p returns true if it is OK to change the address space of constant \p C with
1378// a ConstantExpr addrspacecast.
1379bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
1380 unsigned NewAS) const {
1382
1383 unsigned SrcAS = C->getType()->getPointerAddressSpace();
1384 if (SrcAS == NewAS || isa<UndefValue>(C))
1385 return true;
1386
1387 // Prevent illegal casts between different non-flat address spaces.
1388 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
1389 return false;
1390
1392 return true;
1393
1394 if (auto *Op = dyn_cast<Operator>(C)) {
1395 // If we already have a constant addrspacecast, it should be safe to cast it
1396 // off.
1397 if (Op->getOpcode() == Instruction::AddrSpaceCast)
1398 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)),
1399 NewAS);
1400
1401 if (Op->getOpcode() == Instruction::IntToPtr &&
1402 Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
1403 return true;
1404 }
1405
1406 return false;
1407}
1408
1410 Value::use_iterator End) {
1411 User *CurUser = I->getUser();
1412 ++I;
1413
1414 while (I != End && I->getUser() == CurUser)
1415 ++I;
1416
1417 return I;
1418}
1419
1420void InferAddressSpacesImpl::performPointerReplacement(
1421 Value *V, Value *NewV, Use &U, ValueToValueMapTy &ValueWithNewAddrSpace,
1422 SmallVectorImpl<Instruction *> &DeadInstructions) const {
1423
1424 User *CurUser = U.getUser();
1425
1426 unsigned AddrSpace = V->getType()->getPointerAddressSpace();
1427 if (replaceIfSimplePointerUse(*TTI, CurUser, AddrSpace, V, NewV))
1428 return;
1429
1430 // Skip if the current user is the new value itself.
1431 if (CurUser == NewV)
1432 return;
1433
1434 auto *CurUserI = dyn_cast<Instruction>(CurUser);
1435 if (!CurUserI || CurUserI->getFunction() != F)
1436 return;
1437
1438 // Handle more complex cases like intrinsic that need to be remangled.
1439 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
1440 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
1441 return;
1442 }
1443
1444 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
1445 if (rewriteIntrinsicOperands(II, V, NewV))
1446 return;
1447 }
1448
1449 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUserI)) {
1450 // If we can infer that both pointers are in the same addrspace,
1451 // transform e.g.
1452 // %cmp = icmp eq float* %p, %q
1453 // into
1454 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
1455
1456 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1457 int SrcIdx = U.getOperandNo();
1458 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
1459 Value *OtherSrc = Cmp->getOperand(OtherIdx);
1460
1461 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
1462 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
1463 Cmp->setOperand(OtherIdx, OtherNewV);
1464 Cmp->setOperand(SrcIdx, NewV);
1465 return;
1466 }
1467 }
1468
1469 // Even if the type mismatches, we can cast the constant.
1470 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
1471 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
1472 Cmp->setOperand(SrcIdx, NewV);
1473 Cmp->setOperand(OtherIdx, ConstantExpr::getAddrSpaceCast(
1474 KOtherSrc, NewV->getType()));
1475 return;
1476 }
1477 }
1478 }
1479
1480 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUserI)) {
1481 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1482 if (ASC->getDestAddressSpace() == NewAS) {
1483 ASC->replaceAllUsesWith(NewV);
1484 DeadInstructions.push_back(ASC);
1485 return;
1486 }
1487 }
1488
1489 // Otherwise, replaces the use with flat(NewV).
1490 if (isa<Instruction>(V) || isa<Instruction>(NewV)) {
1491 // Don't create a copy of the original addrspacecast.
1492 if (U == V && isa<AddrSpaceCastInst>(V))
1493 return;
1494
1495 // Insert the addrspacecast after NewV.
1496 BasicBlock::iterator InsertPos;
1497 if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1498 InsertPos = std::next(NewVInst->getIterator());
1499 else
1500 InsertPos = std::next(cast<Instruction>(V)->getIterator());
1501
1502 while (isa<PHINode>(InsertPos))
1503 ++InsertPos;
1504 // This instruction may contain multiple uses of V, update them all.
1505 CurUser->replaceUsesOfWith(
1506 V, new AddrSpaceCastInst(NewV, V->getType(), "", InsertPos));
1507 } else {
1508 CurUserI->replaceUsesOfWith(
1509 V, ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), V->getType()));
1510 }
1511}
1512
1513bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
1514 ArrayRef<WeakTrackingVH> Postorder,
1515 const ValueToAddrSpaceMapTy &InferredAddrSpace,
1516 const PredicatedAddrSpaceMapTy &PredicatedAS) const {
1517 // For each address expression to be modified, creates a clone of it with its
1518 // pointer operands converted to the new address space. Since the pointer
1519 // operands are converted, the clone is naturally in the new address space by
1520 // construction.
1521 ValueToValueMapTy ValueWithNewAddrSpace;
1522 SmallVector<const Use *, 32> PoisonUsesToFix;
1523 for (Value *V : Postorder) {
1524 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
1525
1526 // In some degenerate cases (e.g. invalid IR in unreachable code), we may
1527 // not even infer the value to have its original address space.
1528 if (NewAddrSpace == UninitializedAddressSpace)
1529 continue;
1530
1531 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1532 Value *New =
1533 cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
1534 PredicatedAS, &PoisonUsesToFix);
1535 if (New)
1536 ValueWithNewAddrSpace[V] = New;
1537 }
1538 }
1539
1540 if (ValueWithNewAddrSpace.empty())
1541 return false;
1542
1543 // Fixes all the poison uses generated by cloneInstructionWithNewAddressSpace.
1544 for (const Use *PoisonUse : PoisonUsesToFix) {
1545 User *V = PoisonUse->getUser();
1546 User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1547 if (!NewV)
1548 continue;
1549
1550 unsigned OperandNo = PoisonUse->getOperandNo();
1551 assert(isa<PoisonValue>(NewV->getOperand(OperandNo)));
1552 WeakTrackingVH NewOp = ValueWithNewAddrSpace.lookup(PoisonUse->get());
1553 assert(NewOp &&
1554 "poison replacements in ValueWithNewAddrSpace shouldn't be null");
1555 NewV->setOperand(OperandNo, NewOp);
1556 }
1557
1558 SmallVector<Instruction *, 16> DeadInstructions;
1559 ValueToValueMapTy VMap;
1560 ValueMapper VMapper(VMap, RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1561
1562 // Replaces the uses of the old address expressions with the new ones.
1563 for (const WeakTrackingVH &WVH : Postorder) {
1564 assert(WVH && "value was unexpectedly deleted");
1565 Value *V = WVH;
1566 Value *NewV = ValueWithNewAddrSpace.lookup(V);
1567 if (NewV == nullptr)
1568 continue;
1569
1570 LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n "
1571 << *NewV << '\n');
1572
1573 if (Constant *C = dyn_cast<Constant>(V)) {
1574 Constant *Replace =
1576 if (C != Replace) {
1577 LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
1578 << ": " << *Replace << '\n');
1579 SmallVector<User *, 16> WorkList;
1580 for (User *U : make_early_inc_range(C->users())) {
1581 if (auto *I = dyn_cast<Instruction>(U)) {
1582 if (I->getFunction() == F)
1583 I->replaceUsesOfWith(C, Replace);
1584 } else {
1585 WorkList.append(U->user_begin(), U->user_end());
1586 }
1587 }
1588 if (!WorkList.empty()) {
1589 VMap[C] = Replace;
1590 DenseSet<User *> Visited{WorkList.begin(), WorkList.end()};
1591 while (!WorkList.empty()) {
1592 User *U = WorkList.pop_back_val();
1593 if (auto *I = dyn_cast<Instruction>(U)) {
1594 if (I->getFunction() == F)
1595 VMapper.remapInstruction(*I);
1596 continue;
1597 }
1598 for (User *U2 : U->users())
1599 if (Visited.insert(U2).second)
1600 WorkList.push_back(U2);
1601 }
1602 }
1603 V = Replace;
1604 }
1605 }
1606
1607 Value::use_iterator I, E, Next;
1608 for (I = V->use_begin(), E = V->use_end(); I != E;) {
1609 Use &U = *I;
1610
1611 // Some users may see the same pointer operand in multiple operands. Skip
1612 // to the next instruction.
1613 I = skipToNextUser(I, E);
1614
1615 performPointerReplacement(V, NewV, U, ValueWithNewAddrSpace,
1616 DeadInstructions);
1617 }
1618
1619 if (V->use_empty()) {
1620 if (Instruction *I = dyn_cast<Instruction>(V))
1621 DeadInstructions.push_back(I);
1622 }
1623 }
1624
1625 for (Instruction *I : DeadInstructions)
1627
1628 return true;
1629}
1630
1631bool InferAddressSpaces::runOnFunction(Function &F) {
1632 if (skipFunction(F))
1633 return false;
1634
1635 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1636 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1637 return InferAddressSpacesImpl(
1638 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
1639 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1640 FlatAddrSpace)
1641 .run(F);
1642}
1643
1645 return new InferAddressSpaces(AddressSpace);
1646}
1647
1652
1655 bool Changed =
1656 InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
1658 &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
1659 .run(F);
1660 if (Changed) {
1663 return PA;
1664 }
1665 return PreservedAnalyses::all();
1666}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:344
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool replaceIfSimplePointerUse(const TargetTransformInfo &TTI, User *Inst, unsigned AddrSpace, Value *OldV, Value *NewV)
If OldV is used as the pointer operand of a compatible memory operation Inst, replaces the pointer op...
static bool replaceOperandIfSame(Instruction *Inst, unsigned OpIdx, Value *OldVal, Value *NewVal)
Replace operand OpIdx in Inst, if the value is the same as OldVal with NewVal.
static cl::opt< bool > AssumeDefaultIsFlatAddressSpace("assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden, cl::desc("The default address space is assumed as the flat address space. " "This is mainly for test purpose."))
static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL, const TargetTransformInfo *TTI)
static Value * phiNodeOperandWithNewAddressSpace(AddrSpaceCastInst *NewI, Value *Operand)
static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, Value *NewV)
Update memory intrinsic uses that require more complex processing than simple memory instructions.
static Value * operandWithNewAddressSpaceOrCreatePoison(const Use &OperandUse, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace, const PredicatedAddrSpaceMapTy &PredicatedAS, SmallVectorImpl< const Use * > *PoisonUsesToFix)
static Value::use_iterator skipToNextUser(Value::use_iterator I, Value::use_iterator End)
Infer address static false Type * getPtrOrVecOfPtrsWithNewAS(Type *Ty, unsigned NewAddrSpace)
static APInt computeMaxChangedPtrBits(const Operator *Op, const Value *Mask, const DataLayout &DL, AssumptionCache *AC, const DominatorTree *DT)
static bool replaceSimplePointerUse(const TargetTransformInfo &TTI, InstrType *MemInstr, unsigned AddrSpace, Value *OldV, Value *NewV)
static const unsigned UninitializedAddressSpace
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
This class represents a conversion between pointers from one address space to another.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
static LLVM_ABI bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
This is the common base class for memset/memcpy/memmove.
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static unsigned getOperandNumForIncomingValue(unsigned i)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const
LLVM_ABI std::pair< KnownBits, KnownBits > computeKnownBitsAddrSpaceCast(unsigned ToAS, const Value &PtrOp) const
LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
LLVM_ABI std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const
LLVM_ABI bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const
Return any intrinsic address operand indexes which may be rewritten if they use a flat address space ...
LLVM_ABI Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const
Rewrite intrinsic call II such that OldV will be replaced with NewV, which has a different address sp...
LLVM_ABI unsigned getFlatAddressSpace() const
Returns the address space ID for a target's 'flat' address space.
LLVM_ABI APInt getAddrSpaceCastPreservedPtrMask(unsigned SrcAS, unsigned DstAS) const
Returns a mask indicating which bits of a pointer remain unchanged when casting between address space...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * get() const
Definition Use.h:55
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
bool empty() const
Definition ValueMap.h:143
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:828
use_iterator_impl< Use > use_iterator
Definition Value.h:353
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:535
@ Known
Known to have no common set bits.
LLVM_ABI void initializeInferAddressSpacesPass(PassRegistry &)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376