xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/ScalarEvolutionAliasAnalysis.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===- ScalarEvolutionAliasAnalysis.cpp - SCEV-based Alias Analysis -------===//
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 // This file defines the ScalarEvolutionAliasAnalysis pass, which implements a
10 // simple alias analysis implemented in terms of ScalarEvolution queries.
11 //
12 // This differs from traditional loop dependence analysis in that it tests
13 // for dependencies within a single iteration of a loop, rather than
14 // dependencies between different iterations.
15 //
16 // ScalarEvolution has a more complete understanding of pointer arithmetic
17 // than BasicAliasAnalysis' collection of ad-hoc analyses.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/InitializePasses.h"
24 using namespace llvm;
25 
26 static bool canComputePointerDiff(ScalarEvolution &SE,
27                                   const SCEV *A, const SCEV *B) {
28   if (SE.getEffectiveSCEVType(A->getType()) !=
29       SE.getEffectiveSCEVType(B->getType()))
30     return false;
31 
32   return SE.instructionCouldExistWitthOperands(A, B);
33 }
34 
35 AliasResult SCEVAAResult::alias(const MemoryLocation &LocA,
36                                 const MemoryLocation &LocB, AAQueryInfo &AAQI) {
37   // If either of the memory references is empty, it doesn't matter what the
38   // pointer values are. This allows the code below to ignore this special
39   // case.
40   if (LocA.Size.isZero() || LocB.Size.isZero())
41     return AliasResult::NoAlias;
42 
43   // This is SCEVAAResult. Get the SCEVs!
44   const SCEV *AS = SE.getSCEV(const_cast<Value *>(LocA.Ptr));
45   const SCEV *BS = SE.getSCEV(const_cast<Value *>(LocB.Ptr));
46 
47   // If they evaluate to the same expression, it's a MustAlias.
48   if (AS == BS)
49     return AliasResult::MustAlias;
50 
51   // If something is known about the difference between the two addresses,
52   // see if it's enough to prove a NoAlias.
53   if (canComputePointerDiff(SE, AS, BS)) {
54     unsigned BitWidth = SE.getTypeSizeInBits(AS->getType());
55     APInt ASizeInt(BitWidth, LocA.Size.hasValue()
56                                  ? LocA.Size.getValue()
57                                  : MemoryLocation::UnknownSize);
58     APInt BSizeInt(BitWidth, LocB.Size.hasValue()
59                                  ? LocB.Size.getValue()
60                                  : MemoryLocation::UnknownSize);
61 
62     // Compute the difference between the two pointers.
63     const SCEV *BA = SE.getMinusSCEV(BS, AS);
64 
65     // Test whether the difference is known to be great enough that memory of
66     // the given sizes don't overlap. This assumes that ASizeInt and BSizeInt
67     // are non-zero, which is special-cased above.
68     if (!isa<SCEVCouldNotCompute>(BA) &&
69         ASizeInt.ule(SE.getUnsignedRange(BA).getUnsignedMin()) &&
70         (-BSizeInt).uge(SE.getUnsignedRange(BA).getUnsignedMax()))
71       return AliasResult::NoAlias;
72 
73     // Folding the subtraction while preserving range information can be tricky
74     // (because of INT_MIN, etc.); if the prior test failed, swap AS and BS
75     // and try again to see if things fold better that way.
76 
77     // Compute the difference between the two pointers.
78     const SCEV *AB = SE.getMinusSCEV(AS, BS);
79 
80     // Test whether the difference is known to be great enough that memory of
81     // the given sizes don't overlap. This assumes that ASizeInt and BSizeInt
82     // are non-zero, which is special-cased above.
83     if (!isa<SCEVCouldNotCompute>(AB) &&
84         BSizeInt.ule(SE.getUnsignedRange(AB).getUnsignedMin()) &&
85         (-ASizeInt).uge(SE.getUnsignedRange(AB).getUnsignedMax()))
86       return AliasResult::NoAlias;
87   }
88 
89   // If ScalarEvolution can find an underlying object, form a new query.
90   // The correctness of this depends on ScalarEvolution not recognizing
91   // inttoptr and ptrtoint operators.
92   Value *AO = GetBaseValue(AS);
93   Value *BO = GetBaseValue(BS);
94   if ((AO && AO != LocA.Ptr) || (BO && BO != LocB.Ptr))
95     if (alias(MemoryLocation(AO ? AO : LocA.Ptr,
96                              AO ? LocationSize::beforeOrAfterPointer()
97                                 : LocA.Size,
98                              AO ? AAMDNodes() : LocA.AATags),
99               MemoryLocation(BO ? BO : LocB.Ptr,
100                              BO ? LocationSize::beforeOrAfterPointer()
101                                 : LocB.Size,
102                              BO ? AAMDNodes() : LocB.AATags),
103               AAQI) == AliasResult::NoAlias)
104       return AliasResult::NoAlias;
105 
106   // Forward the query to the next analysis.
107   return AAResultBase::alias(LocA, LocB, AAQI);
108 }
109 
110 /// Given an expression, try to find a base value.
111 ///
112 /// Returns null if none was found.
113 Value *SCEVAAResult::GetBaseValue(const SCEV *S) {
114   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
115     // In an addrec, assume that the base will be in the start, rather
116     // than the step.
117     return GetBaseValue(AR->getStart());
118   } else if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
119     // If there's a pointer operand, it'll be sorted at the end of the list.
120     const SCEV *Last = A->getOperand(A->getNumOperands() - 1);
121     if (Last->getType()->isPointerTy())
122       return GetBaseValue(Last);
123   } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
124     // This is a leaf node.
125     return U->getValue();
126   }
127   // No Identified object found.
128   return nullptr;
129 }
130 
131 bool SCEVAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
132                               FunctionAnalysisManager::Invalidator &Inv) {
133   // We don't care if this analysis itself is preserved, it has no state. But
134   // we need to check that the analyses it depends on have been.
135   return Inv.invalidate<ScalarEvolutionAnalysis>(Fn, PA);
136 }
137 
138 AnalysisKey SCEVAA::Key;
139 
140 SCEVAAResult SCEVAA::run(Function &F, FunctionAnalysisManager &AM) {
141   return SCEVAAResult(AM.getResult<ScalarEvolutionAnalysis>(F));
142 }
143 
144 char SCEVAAWrapperPass::ID = 0;
145 INITIALIZE_PASS_BEGIN(SCEVAAWrapperPass, "scev-aa",
146                       "ScalarEvolution-based Alias Analysis", false, true)
147 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
148 INITIALIZE_PASS_END(SCEVAAWrapperPass, "scev-aa",
149                     "ScalarEvolution-based Alias Analysis", false, true)
150 
151 FunctionPass *llvm::createSCEVAAWrapperPass() {
152   return new SCEVAAWrapperPass();
153 }
154 
155 SCEVAAWrapperPass::SCEVAAWrapperPass() : FunctionPass(ID) {
156   initializeSCEVAAWrapperPassPass(*PassRegistry::getPassRegistry());
157 }
158 
159 bool SCEVAAWrapperPass::runOnFunction(Function &F) {
160   Result.reset(
161       new SCEVAAResult(getAnalysis<ScalarEvolutionWrapperPass>().getSE()));
162   return false;
163 }
164 
165 void SCEVAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
166   AU.setPreservesAll();
167   AU.addRequired<ScalarEvolutionWrapperPass>();
168 }
169