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