1 //===- BasicAliasAnalysis.h - Stateless, local Alias Analysis ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This is the interface for LLVM's primary stateless and local alias analysis.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_BASICALIASANALYSIS_H
15 #define LLVM_ANALYSIS_BASICALIASANALYSIS_H
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/Support/ErrorHandling.h"
30 class AssumptionCache;
34 /// This is the AA result object for the basic, local, and stateless alias
35 /// analysis. It implements the AA query interface in an entirely stateless
36 /// manner. As one consequence, it is never invalidated. While it does retain
37 /// some storage, that is used as an optimization and not to preserve
38 /// information from query to query.
39 class BasicAAResult : public AAResultBase<BasicAAResult> {
40 friend AAResultBase<BasicAAResult>;
48 static const Function *getParent(const Value *V) {
49 if (const Instruction *inst = dyn_cast<Instruction>(V))
50 return inst->getParent()->getParent();
52 if (const Argument *arg = dyn_cast<Argument>(V))
53 return arg->getParent();
58 static bool notDifferentParent(const Value *O1, const Value *O2) {
60 const Function *F1 = getParent(O1);
61 const Function *F2 = getParent(O2);
63 return !F1 || !F2 || F1 == F2;
68 BasicAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI,
69 AssumptionCache &AC, DominatorTree *DT = nullptr,
70 LoopInfo *LI = nullptr)
71 : AAResultBase(TLI), DL(DL), AC(AC), DT(DT), LI(LI) {}
73 BasicAAResult(const BasicAAResult &Arg)
74 : AAResultBase(Arg), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI) {}
75 BasicAAResult(BasicAAResult &&Arg)
76 : AAResultBase(std::move(Arg)), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT),
79 /// Handle invalidation events from the new pass manager.
81 /// By definition, this result is stateless and so remains valid.
82 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
84 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
85 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
86 "BasicAliasAnalysis doesn't support interprocedural queries.");
88 // If we have a directly cached entry for these locations, we have recursed
89 // through this once, so just return the cached results. Notably, when this
90 // happens, we don't clear the cache.
91 auto CacheIt = AliasCache.find(LocPair(LocA, LocB));
92 if (CacheIt != AliasCache.end())
93 return CacheIt->second;
95 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
96 LocB.Size, LocB.AATags);
97 // AliasCache rarely has more than 1 or 2 elements, always use
98 // shrink_and_clear so it quickly returns to the inline capacity of the
99 // SmallDenseMap if it ever grows larger.
100 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
101 AliasCache.shrink_and_clear();
102 VisitedPhiBBs.clear();
106 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
108 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
110 /// Chases pointers until we find a (constant global) or not.
111 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
113 /// Get the location associated with a pointer argument of a callsite.
114 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
116 /// Returns the behavior when calling the given call site.
117 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
119 /// Returns the behavior when calling the given function. For use when the
120 /// call site is not known.
121 FunctionModRefBehavior getModRefBehavior(const Function *F);
124 // A linear transformation of a Value; this class represents ZExt(SExt(V,
125 // SExtBits), ZExtBits) * Scale + Offset.
126 struct VariableGEPIndex {
128 // An opaque Value - we can't decompose this further.
131 // We need to track what extensions we've done as we consider the same Value
132 // with different extensions as different variables in a GEP's linear
134 // e.g.: if V == -1, then sext(x) != zext(x).
140 bool operator==(const VariableGEPIndex &Other) const {
141 return V == Other.V && ZExtBits == Other.ZExtBits &&
142 SExtBits == Other.SExtBits && Scale == Other.Scale;
145 bool operator!=(const VariableGEPIndex &Other) const {
146 return !operator==(Other);
150 /// Track alias queries to guard against recursion.
151 typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
152 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
153 AliasCacheTy AliasCache;
155 /// Tracks phi nodes we have visited.
157 /// When interpret "Value" pointer equality as value equality we need to make
158 /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
159 /// come from different "iterations" of a cycle and see different values for
160 /// the same "Value" pointer.
162 /// The following example shows the problem:
163 /// %p = phi(%alloca1, %addr2)
165 /// %addr1 = gep, %alloca2, 0, %l
166 /// %addr2 = gep %alloca2, 0, (%l + 1)
167 /// alias(%p, %addr1) -> MayAlias !
169 SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
171 /// Tracks instructions visited by pointsToConstantMemory.
172 SmallPtrSet<const Value *, 16> Visited;
175 GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
176 unsigned &ZExtBits, unsigned &SExtBits,
177 const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
178 DominatorTree *DT, bool &NSW, bool &NUW);
181 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
182 SmallVectorImpl<VariableGEPIndex> &VarIndices,
183 bool &MaxLookupReached, const DataLayout &DL,
184 AssumptionCache *AC, DominatorTree *DT);
185 /// \brief A Heuristic for aliasGEP that searches for a constant offset
186 /// between the variables.
188 /// GetLinearExpression has some limitations, as generally zext(%x + 1)
189 /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
190 /// will therefore conservatively refuse to decompose these expressions.
191 /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
192 /// the addition overflows.
194 constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
195 uint64_t V1Size, uint64_t V2Size, int64_t BaseOffset,
196 AssumptionCache *AC, DominatorTree *DT);
198 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
200 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
201 const SmallVectorImpl<VariableGEPIndex> &Src);
203 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
204 const AAMDNodes &V1AAInfo, const Value *V2,
205 uint64_t V2Size, const AAMDNodes &V2AAInfo,
206 const Value *UnderlyingV1, const Value *UnderlyingV2);
208 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
209 const AAMDNodes &PNAAInfo, const Value *V2,
210 uint64_t V2Size, const AAMDNodes &V2AAInfo);
212 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
213 const AAMDNodes &SIAAInfo, const Value *V2,
214 uint64_t V2Size, const AAMDNodes &V2AAInfo);
216 AliasResult aliasCheck(const Value *V1, uint64_t V1Size, AAMDNodes V1AATag,
217 const Value *V2, uint64_t V2Size, AAMDNodes V2AATag);
220 /// Analysis pass providing a never-invalidated alias analysis result.
223 typedef BasicAAResult Result;
225 /// \brief Opaque, unique identifier for this analysis pass.
226 static void *ID() { return (void *)&PassID; }
228 BasicAAResult run(Function &F, AnalysisManager<Function> *AM);
230 /// \brief Provide access to a name for this pass for debugging purposes.
231 static StringRef name() { return "BasicAliasAnalysis"; }
237 /// Legacy wrapper pass to provide the BasicAAResult object.
238 class BasicAAWrapperPass : public FunctionPass {
239 std::unique_ptr<BasicAAResult> Result;
241 virtual void anchor();
246 BasicAAWrapperPass() : FunctionPass(ID) {}
248 BasicAAResult &getResult() { return *Result; }
249 const BasicAAResult &getResult() const { return *Result; }
251 bool runOnFunction(Function &F) override;
252 void getAnalysisUsage(AnalysisUsage &AU) const override;
255 FunctionPass *createBasicAAWrapperPass();
257 /// A helper for the legacy pass manager to create a \c BasicAAResult object
258 /// populated to the best of our ability for a particular function when inside
259 /// of a \c ModulePass or a \c CallGraphSCCPass.
260 BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);