• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the primary stateless implementation of the
11 // Alias Analysis interface that implements identities (two different
12 // globals cannot alias, etc), but does no stateful analysis.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/Passes.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/CaptureTracking.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
45 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
46 /// careful with value equivalence. We use reachability to make sure a value
47 /// cannot be involved in a cycle.
48 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
49 
50 // The max limit of the search depth in DecomposeGEPExpression() and
51 // GetUnderlyingObject(), both functions need to use the same search
52 // depth otherwise the algorithm in aliasGEP will assert.
53 static const unsigned MaxLookupSearchDepth = 6;
54 
55 //===----------------------------------------------------------------------===//
56 // Useful predicates
57 //===----------------------------------------------------------------------===//
58 
59 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60 /// object that never escapes from the function.
isNonEscapingLocalObject(const Value * V)61 static bool isNonEscapingLocalObject(const Value *V) {
62   // If this is a local allocation, check to see if it escapes.
63   if (isa<AllocaInst>(V) || isNoAliasCall(V))
64     // Set StoreCaptures to True so that we can assume in our callers that the
65     // pointer is not the result of a load instruction. Currently
66     // PointerMayBeCaptured doesn't have any special analysis for the
67     // StoreCaptures=false case; if it did, our callers could be refined to be
68     // more precise.
69     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
70 
71   // If this is an argument that corresponds to a byval or noalias argument,
72   // then it has not escaped before entering the function.  Check if it escapes
73   // inside the function.
74   if (const Argument *A = dyn_cast<Argument>(V))
75     if (A->hasByValAttr() || A->hasNoAliasAttr())
76       // Note even if the argument is marked nocapture we still need to check
77       // for copies made inside the function. The nocapture attribute only
78       // specifies that there are no copies made that outlive the function.
79       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
80 
81   return false;
82 }
83 
84 /// isEscapeSource - Return true if the pointer is one which would have
85 /// been considered an escape by isNonEscapingLocalObject.
isEscapeSource(const Value * V)86 static bool isEscapeSource(const Value *V) {
87   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
88     return true;
89 
90   // The load case works because isNonEscapingLocalObject considers all
91   // stores to be escapes (it passes true for the StoreCaptures argument
92   // to PointerMayBeCaptured).
93   if (isa<LoadInst>(V))
94     return true;
95 
96   return false;
97 }
98 
99 /// getObjectSize - Return the size of the object specified by V, or
100 /// UnknownSize if unknown.
getObjectSize(const Value * V,const DataLayout & DL,const TargetLibraryInfo & TLI,bool RoundToAlign=false)101 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
102                               const TargetLibraryInfo &TLI,
103                               bool RoundToAlign = false) {
104   uint64_t Size;
105   if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
106     return Size;
107   return AliasAnalysis::UnknownSize;
108 }
109 
110 /// isObjectSmallerThan - Return true if we can prove that the object specified
111 /// by V is smaller than Size.
isObjectSmallerThan(const Value * V,uint64_t Size,const DataLayout & DL,const TargetLibraryInfo & TLI)112 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
113                                 const DataLayout &DL,
114                                 const TargetLibraryInfo &TLI) {
115   // Note that the meanings of the "object" are slightly different in the
116   // following contexts:
117   //    c1: llvm::getObjectSize()
118   //    c2: llvm.objectsize() intrinsic
119   //    c3: isObjectSmallerThan()
120   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
121   // refers to the "entire object".
122   //
123   //  Consider this example:
124   //     char *p = (char*)malloc(100)
125   //     char *q = p+80;
126   //
127   //  In the context of c1 and c2, the "object" pointed by q refers to the
128   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
129   //
130   //  However, in the context of c3, the "object" refers to the chunk of memory
131   // being allocated. So, the "object" has 100 bytes, and q points to the middle
132   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
133   // parameter, before the llvm::getObjectSize() is called to get the size of
134   // entire object, we should:
135   //    - either rewind the pointer q to the base-address of the object in
136   //      question (in this case rewind to p), or
137   //    - just give up. It is up to caller to make sure the pointer is pointing
138   //      to the base address the object.
139   //
140   // We go for 2nd option for simplicity.
141   if (!isIdentifiedObject(V))
142     return false;
143 
144   // This function needs to use the aligned object size because we allow
145   // reads a bit past the end given sufficient alignment.
146   uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
147 
148   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
149 }
150 
151 /// isObjectSize - Return true if we can prove that the object specified
152 /// by V has size Size.
isObjectSize(const Value * V,uint64_t Size,const DataLayout & DL,const TargetLibraryInfo & TLI)153 static bool isObjectSize(const Value *V, uint64_t Size,
154                          const DataLayout &DL, const TargetLibraryInfo &TLI) {
155   uint64_t ObjectSize = getObjectSize(V, DL, TLI);
156   return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
157 }
158 
159 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
160 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
161 /// Further, an IdentifiedFunctionLocal can not alias with any function
162 /// arguments other than itself, which is not necessarily true for
163 /// IdentifiedObjects.
isIdentifiedFunctionLocal(const Value * V)164 static bool isIdentifiedFunctionLocal(const Value *V)
165 {
166   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
167 }
168 
169 
170 //===----------------------------------------------------------------------===//
171 // GetElementPtr Instruction Decomposition and Analysis
172 //===----------------------------------------------------------------------===//
173 
174 namespace {
175   enum ExtensionKind {
176     EK_NotExtended,
177     EK_SignExt,
178     EK_ZeroExt
179   };
180 
181   struct VariableGEPIndex {
182     const Value *V;
183     ExtensionKind Extension;
184     int64_t Scale;
185 
operator ==__anon3da0788c0111::VariableGEPIndex186     bool operator==(const VariableGEPIndex &Other) const {
187       return V == Other.V && Extension == Other.Extension &&
188         Scale == Other.Scale;
189     }
190 
operator !=__anon3da0788c0111::VariableGEPIndex191     bool operator!=(const VariableGEPIndex &Other) const {
192       return !operator==(Other);
193     }
194   };
195 }
196 
197 
198 /// GetLinearExpression - Analyze the specified value as a linear expression:
199 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
200 /// values as APInts and return V as a Value*, and return whether we looked
201 /// through any sign or zero extends.  The incoming Value is known to have
202 /// IntegerType and it may already be sign or zero extended.
203 ///
204 /// Note that this looks through extends, so the high bits may not be
205 /// represented in the result.
GetLinearExpression(Value * V,APInt & Scale,APInt & Offset,ExtensionKind & Extension,const DataLayout & DL,unsigned Depth)206 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
207                                   ExtensionKind &Extension,
208                                   const DataLayout &DL, unsigned Depth) {
209   assert(V->getType()->isIntegerTy() && "Not an integer value");
210 
211   // Limit our recursion depth.
212   if (Depth == 6) {
213     Scale = 1;
214     Offset = 0;
215     return V;
216   }
217 
218   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
219     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
220       switch (BOp->getOpcode()) {
221       default: break;
222       case Instruction::Or:
223         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
224         // analyze it.
225         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL))
226           break;
227         // FALL THROUGH.
228       case Instruction::Add:
229         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
230                                 DL, Depth+1);
231         Offset += RHSC->getValue();
232         return V;
233       case Instruction::Mul:
234         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
235                                 DL, Depth+1);
236         Offset *= RHSC->getValue();
237         Scale *= RHSC->getValue();
238         return V;
239       case Instruction::Shl:
240         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
241                                 DL, Depth+1);
242         Offset <<= RHSC->getValue().getLimitedValue();
243         Scale <<= RHSC->getValue().getLimitedValue();
244         return V;
245       }
246     }
247   }
248 
249   // Since GEP indices are sign extended anyway, we don't care about the high
250   // bits of a sign or zero extended value - just scales and offsets.  The
251   // extensions have to be consistent though.
252   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
254     Value *CastOp = cast<CastInst>(V)->getOperand(0);
255     unsigned OldWidth = Scale.getBitWidth();
256     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
257     Scale = Scale.trunc(SmallWidth);
258     Offset = Offset.trunc(SmallWidth);
259     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
260 
261     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
262                                         DL, Depth+1);
263     Scale = Scale.zext(OldWidth);
264     Offset = Offset.zext(OldWidth);
265 
266     return Result;
267   }
268 
269   Scale = 1;
270   Offset = 0;
271   return V;
272 }
273 
274 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
275 /// into a base pointer with a constant offset and a number of scaled symbolic
276 /// offsets.
277 ///
278 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
279 /// the VarIndices vector) are Value*'s that are known to be scaled by the
280 /// specified amount, but which may have other unrepresented high bits. As such,
281 /// the gep cannot necessarily be reconstructed from its decomposed form.
282 ///
283 /// When DataLayout is around, this function is capable of analyzing everything
284 /// that GetUnderlyingObject can look through. To be able to do that
285 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
286 /// depth (MaxLookupSearchDepth).
287 /// When DataLayout not is around, it just looks through pointer casts.
288 ///
289 static const Value *
DecomposeGEPExpression(const Value * V,int64_t & BaseOffs,SmallVectorImpl<VariableGEPIndex> & VarIndices,bool & MaxLookupReached,const DataLayout * DL)290 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
291                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
292                        bool &MaxLookupReached, const DataLayout *DL) {
293   // Limit recursion depth to limit compile time in crazy cases.
294   unsigned MaxLookup = MaxLookupSearchDepth;
295   MaxLookupReached = false;
296 
297   BaseOffs = 0;
298   do {
299     // See if this is a bitcast or GEP.
300     const Operator *Op = dyn_cast<Operator>(V);
301     if (!Op) {
302       // The only non-operator case we can handle are GlobalAliases.
303       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
304         if (!GA->mayBeOverridden()) {
305           V = GA->getAliasee();
306           continue;
307         }
308       }
309       return V;
310     }
311 
312     if (Op->getOpcode() == Instruction::BitCast) {
313       V = Op->getOperand(0);
314       continue;
315     }
316 
317     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
318     if (!GEPOp) {
319       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
320       // can come up with something. This matches what GetUnderlyingObject does.
321       if (const Instruction *I = dyn_cast<Instruction>(V))
322         // TODO: Get a DominatorTree and use it here.
323         if (const Value *Simplified =
324               SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
325           V = Simplified;
326           continue;
327         }
328 
329       return V;
330     }
331 
332     // Don't attempt to analyze GEPs over unsized objects.
333     if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
334       return V;
335 
336     // If we are lacking DataLayout information, we can't compute the offets of
337     // elements computed by GEPs.  However, we can handle bitcast equivalent
338     // GEPs.
339     if (!DL) {
340       if (!GEPOp->hasAllZeroIndices())
341         return V;
342       V = GEPOp->getOperand(0);
343       continue;
344     }
345 
346     unsigned AS = GEPOp->getPointerAddressSpace();
347     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
348     gep_type_iterator GTI = gep_type_begin(GEPOp);
349     for (User::const_op_iterator I = GEPOp->op_begin()+1,
350          E = GEPOp->op_end(); I != E; ++I) {
351       Value *Index = *I;
352       // Compute the (potentially symbolic) offset in bytes for this index.
353       if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
354         // For a struct, add the member offset.
355         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
356         if (FieldNo == 0) continue;
357 
358         BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
359         continue;
360       }
361 
362       // For an array/pointer, add the element offset, explicitly scaled.
363       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
364         if (CIdx->isZero()) continue;
365         BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
366         continue;
367       }
368 
369       uint64_t Scale = DL->getTypeAllocSize(*GTI);
370       ExtensionKind Extension = EK_NotExtended;
371 
372       // If the integer type is smaller than the pointer size, it is implicitly
373       // sign extended to pointer size.
374       unsigned Width = Index->getType()->getIntegerBitWidth();
375       if (DL->getPointerSizeInBits(AS) > Width)
376         Extension = EK_SignExt;
377 
378       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
379       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
380       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
381                                   *DL, 0);
382 
383       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
384       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
385       BaseOffs += IndexOffset.getSExtValue()*Scale;
386       Scale *= IndexScale.getSExtValue();
387 
388       // If we already had an occurrence of this index variable, merge this
389       // scale into it.  For example, we want to handle:
390       //   A[x][x] -> x*16 + x*4 -> x*20
391       // This also ensures that 'x' only appears in the index list once.
392       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
393         if (VarIndices[i].V == Index &&
394             VarIndices[i].Extension == Extension) {
395           Scale += VarIndices[i].Scale;
396           VarIndices.erase(VarIndices.begin()+i);
397           break;
398         }
399       }
400 
401       // Make sure that we have a scale that makes sense for this target's
402       // pointer size.
403       if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
404         Scale <<= ShiftBits;
405         Scale = (int64_t)Scale >> ShiftBits;
406       }
407 
408       if (Scale) {
409         VariableGEPIndex Entry = {Index, Extension,
410                                   static_cast<int64_t>(Scale)};
411         VarIndices.push_back(Entry);
412       }
413     }
414 
415     // Analyze the base pointer next.
416     V = GEPOp->getOperand(0);
417   } while (--MaxLookup);
418 
419   // If the chain of expressions is too deep, just return early.
420   MaxLookupReached = true;
421   return V;
422 }
423 
424 //===----------------------------------------------------------------------===//
425 // BasicAliasAnalysis Pass
426 //===----------------------------------------------------------------------===//
427 
428 #ifndef NDEBUG
getParent(const Value * V)429 static const Function *getParent(const Value *V) {
430   if (const Instruction *inst = dyn_cast<Instruction>(V))
431     return inst->getParent()->getParent();
432 
433   if (const Argument *arg = dyn_cast<Argument>(V))
434     return arg->getParent();
435 
436   return nullptr;
437 }
438 
notDifferentParent(const Value * O1,const Value * O2)439 static bool notDifferentParent(const Value *O1, const Value *O2) {
440 
441   const Function *F1 = getParent(O1);
442   const Function *F2 = getParent(O2);
443 
444   return !F1 || !F2 || F1 == F2;
445 }
446 #endif
447 
448 namespace {
449   /// BasicAliasAnalysis - This is the primary alias analysis implementation.
450   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
451     static char ID; // Class identification, replacement for typeinfo
BasicAliasAnalysis__anon3da0788c0211::BasicAliasAnalysis452     BasicAliasAnalysis() : ImmutablePass(ID) {
453       initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
454     }
455 
initializePass__anon3da0788c0211::BasicAliasAnalysis456     void initializePass() override {
457       InitializeAliasAnalysis(this);
458     }
459 
getAnalysisUsage__anon3da0788c0211::BasicAliasAnalysis460     void getAnalysisUsage(AnalysisUsage &AU) const override {
461       AU.addRequired<AliasAnalysis>();
462       AU.addRequired<TargetLibraryInfo>();
463     }
464 
alias__anon3da0788c0211::BasicAliasAnalysis465     AliasResult alias(const Location &LocA, const Location &LocB) override {
466       assert(AliasCache.empty() && "AliasCache must be cleared after use!");
467       assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
468              "BasicAliasAnalysis doesn't support interprocedural queries.");
469       AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
470                                      LocB.Ptr, LocB.Size, LocB.TBAATag);
471       // AliasCache rarely has more than 1 or 2 elements, always use
472       // shrink_and_clear so it quickly returns to the inline capacity of the
473       // SmallDenseMap if it ever grows larger.
474       // FIXME: This should really be shrink_to_inline_capacity_and_clear().
475       AliasCache.shrink_and_clear();
476       VisitedPhiBBs.clear();
477       return Alias;
478     }
479 
480     ModRefResult getModRefInfo(ImmutableCallSite CS,
481                                const Location &Loc) override;
482 
getModRefInfo__anon3da0788c0211::BasicAliasAnalysis483     ModRefResult getModRefInfo(ImmutableCallSite CS1,
484                                ImmutableCallSite CS2) override {
485       // The AliasAnalysis base class has some smarts, lets use them.
486       return AliasAnalysis::getModRefInfo(CS1, CS2);
487     }
488 
489     /// pointsToConstantMemory - Chase pointers until we find a (constant
490     /// global) or not.
491     bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
492 
493     /// Get the location associated with a pointer argument of a callsite.
494     Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
495                             ModRefResult &Mask) override;
496 
497     /// getModRefBehavior - Return the behavior when calling the given
498     /// call site.
499     ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
500 
501     /// getModRefBehavior - Return the behavior when calling the given function.
502     /// For use when the call site is not known.
503     ModRefBehavior getModRefBehavior(const Function *F) override;
504 
505     /// getAdjustedAnalysisPointer - This method is used when a pass implements
506     /// an analysis interface through multiple inheritance.  If needed, it
507     /// should override this to adjust the this pointer as needed for the
508     /// specified pass info.
getAdjustedAnalysisPointer__anon3da0788c0211::BasicAliasAnalysis509     void *getAdjustedAnalysisPointer(const void *ID) override {
510       if (ID == &AliasAnalysis::ID)
511         return (AliasAnalysis*)this;
512       return this;
513     }
514 
515   private:
516     // AliasCache - Track alias queries to guard against recursion.
517     typedef std::pair<Location, Location> LocPair;
518     typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
519     AliasCacheTy AliasCache;
520 
521     /// \brief Track phi nodes we have visited. When interpret "Value" pointer
522     /// equality as value equality we need to make sure that the "Value" is not
523     /// part of a cycle. Otherwise, two uses could come from different
524     /// "iterations" of a cycle and see different values for the same "Value"
525     /// pointer.
526     /// The following example shows the problem:
527     ///   %p = phi(%alloca1, %addr2)
528     ///   %l = load %ptr
529     ///   %addr1 = gep, %alloca2, 0, %l
530     ///   %addr2 = gep  %alloca2, 0, (%l + 1)
531     ///      alias(%p, %addr1) -> MayAlias !
532     ///   store %l, ...
533     SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
534 
535     // Visited - Track instructions visited by pointsToConstantMemory.
536     SmallPtrSet<const Value*, 16> Visited;
537 
538     /// \brief Check whether two Values can be considered equivalent.
539     ///
540     /// In addition to pointer equivalence of \p V1 and \p V2 this checks
541     /// whether they can not be part of a cycle in the value graph by looking at
542     /// all visited phi nodes an making sure that the phis cannot reach the
543     /// value. We have to do this because we are looking through phi nodes (That
544     /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
545     bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
546 
547     /// \brief Dest and Src are the variable indices from two decomposed
548     /// GetElementPtr instructions GEP1 and GEP2 which have common base
549     /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
550     /// difference between the two pointers.
551     void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
552                             const SmallVectorImpl<VariableGEPIndex> &Src);
553 
554     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
555     // instruction against another.
556     AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
557                          const MDNode *V1TBAAInfo,
558                          const Value *V2, uint64_t V2Size,
559                          const MDNode *V2TBAAInfo,
560                          const Value *UnderlyingV1, const Value *UnderlyingV2);
561 
562     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
563     // instruction against another.
564     AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
565                          const MDNode *PNTBAAInfo,
566                          const Value *V2, uint64_t V2Size,
567                          const MDNode *V2TBAAInfo);
568 
569     /// aliasSelect - Disambiguate a Select instruction against another value.
570     AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
571                             const MDNode *SITBAAInfo,
572                             const Value *V2, uint64_t V2Size,
573                             const MDNode *V2TBAAInfo);
574 
575     AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
576                            const MDNode *V1TBAATag,
577                            const Value *V2, uint64_t V2Size,
578                            const MDNode *V2TBAATag);
579   };
580 }  // End of anonymous namespace
581 
582 // Register this pass...
583 char BasicAliasAnalysis::ID = 0;
584 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
585                    "Basic Alias Analysis (stateless AA impl)",
586                    false, true, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)587 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
588 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
589                    "Basic Alias Analysis (stateless AA impl)",
590                    false, true, false)
591 
592 
593 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
594   return new BasicAliasAnalysis();
595 }
596 
597 /// pointsToConstantMemory - Returns whether the given pointer value
598 /// points to memory that is local to the function, with global constants being
599 /// considered local to all functions.
600 bool
pointsToConstantMemory(const Location & Loc,bool OrLocal)601 BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
602   assert(Visited.empty() && "Visited must be cleared after use!");
603 
604   unsigned MaxLookup = 8;
605   SmallVector<const Value *, 16> Worklist;
606   Worklist.push_back(Loc.Ptr);
607   do {
608     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
609     if (!Visited.insert(V)) {
610       Visited.clear();
611       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
612     }
613 
614     // An alloca instruction defines local memory.
615     if (OrLocal && isa<AllocaInst>(V))
616       continue;
617 
618     // A global constant counts as local memory for our purposes.
619     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
620       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
621       // global to be marked constant in some modules and non-constant in
622       // others.  GV may even be a declaration, not a definition.
623       if (!GV->isConstant()) {
624         Visited.clear();
625         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
626       }
627       continue;
628     }
629 
630     // If both select values point to local memory, then so does the select.
631     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
632       Worklist.push_back(SI->getTrueValue());
633       Worklist.push_back(SI->getFalseValue());
634       continue;
635     }
636 
637     // If all values incoming to a phi node point to local memory, then so does
638     // the phi.
639     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
640       // Don't bother inspecting phi nodes with many operands.
641       if (PN->getNumIncomingValues() > MaxLookup) {
642         Visited.clear();
643         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
644       }
645       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
646         Worklist.push_back(PN->getIncomingValue(i));
647       continue;
648     }
649 
650     // Otherwise be conservative.
651     Visited.clear();
652     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
653 
654   } while (!Worklist.empty() && --MaxLookup);
655 
656   Visited.clear();
657   return Worklist.empty();
658 }
659 
isMemsetPattern16(const Function * MS,const TargetLibraryInfo & TLI)660 static bool isMemsetPattern16(const Function *MS,
661                               const TargetLibraryInfo &TLI) {
662   if (TLI.has(LibFunc::memset_pattern16) &&
663       MS->getName() == "memset_pattern16") {
664     FunctionType *MemsetType = MS->getFunctionType();
665     if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
666         isa<PointerType>(MemsetType->getParamType(0)) &&
667         isa<PointerType>(MemsetType->getParamType(1)) &&
668         isa<IntegerType>(MemsetType->getParamType(2)))
669       return true;
670   }
671 
672   return false;
673 }
674 
675 /// getModRefBehavior - Return the behavior when calling the given call site.
676 AliasAnalysis::ModRefBehavior
getModRefBehavior(ImmutableCallSite CS)677 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
678   if (CS.doesNotAccessMemory())
679     // Can't do better than this.
680     return DoesNotAccessMemory;
681 
682   ModRefBehavior Min = UnknownModRefBehavior;
683 
684   // If the callsite knows it only reads memory, don't return worse
685   // than that.
686   if (CS.onlyReadsMemory())
687     Min = OnlyReadsMemory;
688 
689   // The AliasAnalysis base class has some smarts, lets use them.
690   return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
691 }
692 
693 /// getModRefBehavior - Return the behavior when calling the given function.
694 /// For use when the call site is not known.
695 AliasAnalysis::ModRefBehavior
getModRefBehavior(const Function * F)696 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
697   // If the function declares it doesn't access memory, we can't do better.
698   if (F->doesNotAccessMemory())
699     return DoesNotAccessMemory;
700 
701   // For intrinsics, we can check the table.
702   if (unsigned iid = F->getIntrinsicID()) {
703 #define GET_INTRINSIC_MODREF_BEHAVIOR
704 #include "llvm/IR/Intrinsics.gen"
705 #undef GET_INTRINSIC_MODREF_BEHAVIOR
706   }
707 
708   ModRefBehavior Min = UnknownModRefBehavior;
709 
710   // If the function declares it only reads memory, go with that.
711   if (F->onlyReadsMemory())
712     Min = OnlyReadsMemory;
713 
714   const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
715   if (isMemsetPattern16(F, TLI))
716     Min = OnlyAccessesArgumentPointees;
717 
718   // Otherwise be conservative.
719   return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
720 }
721 
722 AliasAnalysis::Location
getArgLocation(ImmutableCallSite CS,unsigned ArgIdx,ModRefResult & Mask)723 BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
724                                    ModRefResult &Mask) {
725   Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
726   const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
727   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
728   if (II != nullptr)
729     switch (II->getIntrinsicID()) {
730     default: break;
731     case Intrinsic::memset:
732     case Intrinsic::memcpy:
733     case Intrinsic::memmove: {
734       assert((ArgIdx == 0 || ArgIdx == 1) &&
735              "Invalid argument index for memory intrinsic");
736       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
737         Loc.Size = LenCI->getZExtValue();
738       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
739              "Memory intrinsic location pointer not argument?");
740       Mask = ArgIdx ? Ref : Mod;
741       break;
742     }
743     case Intrinsic::lifetime_start:
744     case Intrinsic::lifetime_end:
745     case Intrinsic::invariant_start: {
746       assert(ArgIdx == 1 && "Invalid argument index");
747       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
748              "Intrinsic location pointer not argument?");
749       Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
750       break;
751     }
752     case Intrinsic::invariant_end: {
753       assert(ArgIdx == 2 && "Invalid argument index");
754       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
755              "Intrinsic location pointer not argument?");
756       Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
757       break;
758     }
759     case Intrinsic::arm_neon_vld1: {
760       assert(ArgIdx == 0 && "Invalid argument index");
761       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
762              "Intrinsic location pointer not argument?");
763       // LLVM's vld1 and vst1 intrinsics currently only support a single
764       // vector register.
765       if (DL)
766         Loc.Size = DL->getTypeStoreSize(II->getType());
767       break;
768     }
769     case Intrinsic::arm_neon_vst1: {
770       assert(ArgIdx == 0 && "Invalid argument index");
771       assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
772              "Intrinsic location pointer not argument?");
773       if (DL)
774         Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
775       break;
776     }
777     }
778 
779   // We can bound the aliasing properties of memset_pattern16 just as we can
780   // for memcpy/memset.  This is particularly important because the
781   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
782   // whenever possible.
783   else if (CS.getCalledFunction() &&
784            isMemsetPattern16(CS.getCalledFunction(), TLI)) {
785     assert((ArgIdx == 0 || ArgIdx == 1) &&
786            "Invalid argument index for memset_pattern16");
787     if (ArgIdx == 1)
788       Loc.Size = 16;
789     else if (const ConstantInt *LenCI =
790              dyn_cast<ConstantInt>(CS.getArgument(2)))
791       Loc.Size = LenCI->getZExtValue();
792     assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
793            "memset_pattern16 location pointer not argument?");
794     Mask = ArgIdx ? Ref : Mod;
795   }
796   // FIXME: Handle memset_pattern4 and memset_pattern8 also.
797 
798   return Loc;
799 }
800 
801 /// getModRefInfo - Check to see if the specified callsite can clobber the
802 /// specified memory object.  Since we only look at local properties of this
803 /// function, we really can't say much about this query.  We do, however, use
804 /// simple "address taken" analysis on local objects.
805 AliasAnalysis::ModRefResult
getModRefInfo(ImmutableCallSite CS,const Location & Loc)806 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
807                                   const Location &Loc) {
808   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
809          "AliasAnalysis query involving multiple functions!");
810 
811   const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
812 
813   // If this is a tail call and Loc.Ptr points to a stack location, we know that
814   // the tail call cannot access or modify the local stack.
815   // We cannot exclude byval arguments here; these belong to the caller of
816   // the current function not to the current function, and a tail callee
817   // may reference them.
818   if (isa<AllocaInst>(Object))
819     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
820       if (CI->isTailCall())
821         return NoModRef;
822 
823   // If the pointer is to a locally allocated object that does not escape,
824   // then the call can not mod/ref the pointer unless the call takes the pointer
825   // as an argument, and itself doesn't capture it.
826   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
827       isNonEscapingLocalObject(Object)) {
828     bool PassedAsArg = false;
829     unsigned ArgNo = 0;
830     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
831          CI != CE; ++CI, ++ArgNo) {
832       // Only look at the no-capture or byval pointer arguments.  If this
833       // pointer were passed to arguments that were neither of these, then it
834       // couldn't be no-capture.
835       if (!(*CI)->getType()->isPointerTy() ||
836           (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
837         continue;
838 
839       // If this is a no-capture pointer argument, see if we can tell that it
840       // is impossible to alias the pointer we're checking.  If not, we have to
841       // assume that the call could touch the pointer, even though it doesn't
842       // escape.
843       if (!isNoAlias(Location(*CI), Location(Object))) {
844         PassedAsArg = true;
845         break;
846       }
847     }
848 
849     if (!PassedAsArg)
850       return NoModRef;
851   }
852 
853   // The AliasAnalysis base class has some smarts, lets use them.
854   return AliasAnalysis::getModRefInfo(CS, Loc);
855 }
856 
857 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
858 /// against another pointer.  We know that V1 is a GEP, but we don't know
859 /// anything about V2.  UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
860 /// UnderlyingV2 is the same for V2.
861 ///
862 AliasAnalysis::AliasResult
aliasGEP(const GEPOperator * GEP1,uint64_t V1Size,const MDNode * V1TBAAInfo,const Value * V2,uint64_t V2Size,const MDNode * V2TBAAInfo,const Value * UnderlyingV1,const Value * UnderlyingV2)863 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
864                              const MDNode *V1TBAAInfo,
865                              const Value *V2, uint64_t V2Size,
866                              const MDNode *V2TBAAInfo,
867                              const Value *UnderlyingV1,
868                              const Value *UnderlyingV2) {
869   int64_t GEP1BaseOffset;
870   bool GEP1MaxLookupReached;
871   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
872 
873   // If we have two gep instructions with must-alias or not-alias'ing base
874   // pointers, figure out if the indexes to the GEP tell us anything about the
875   // derived pointer.
876   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
877     // Do the base pointers alias?
878     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
879                                        UnderlyingV2, UnknownSize, nullptr);
880 
881     // Check for geps of non-aliasing underlying pointers where the offsets are
882     // identical.
883     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
884       // Do the base pointers alias assuming type and size.
885       AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
886                                                 V1TBAAInfo, UnderlyingV2,
887                                                 V2Size, V2TBAAInfo);
888       if (PreciseBaseAlias == NoAlias) {
889         // See if the computed offset from the common pointer tells us about the
890         // relation of the resulting pointer.
891         int64_t GEP2BaseOffset;
892         bool GEP2MaxLookupReached;
893         SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
894         const Value *GEP2BasePtr =
895           DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
896                                  GEP2MaxLookupReached, DL);
897         const Value *GEP1BasePtr =
898           DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
899                                  GEP1MaxLookupReached, DL);
900         // DecomposeGEPExpression and GetUnderlyingObject should return the
901         // same result except when DecomposeGEPExpression has no DataLayout.
902         if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
903           assert(!DL &&
904                  "DecomposeGEPExpression and GetUnderlyingObject disagree!");
905           return MayAlias;
906         }
907         // If the max search depth is reached the result is undefined
908         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
909           return MayAlias;
910 
911         // Same offsets.
912         if (GEP1BaseOffset == GEP2BaseOffset &&
913             GEP1VariableIndices == GEP2VariableIndices)
914           return NoAlias;
915         GEP1VariableIndices.clear();
916       }
917     }
918 
919     // If we get a No or May, then return it immediately, no amount of analysis
920     // will improve this situation.
921     if (BaseAlias != MustAlias) return BaseAlias;
922 
923     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
924     // exactly, see if the computed offset from the common pointer tells us
925     // about the relation of the resulting pointer.
926     const Value *GEP1BasePtr =
927       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
928                              GEP1MaxLookupReached, DL);
929 
930     int64_t GEP2BaseOffset;
931     bool GEP2MaxLookupReached;
932     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
933     const Value *GEP2BasePtr =
934       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
935                              GEP2MaxLookupReached, DL);
936 
937     // DecomposeGEPExpression and GetUnderlyingObject should return the
938     // same result except when DecomposeGEPExpression has no DataLayout.
939     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
940       assert(!DL &&
941              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
942       return MayAlias;
943     }
944     // If the max search depth is reached the result is undefined
945     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
946       return MayAlias;
947 
948     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
949     // symbolic difference.
950     GEP1BaseOffset -= GEP2BaseOffset;
951     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
952 
953   } else {
954     // Check to see if these two pointers are related by the getelementptr
955     // instruction.  If one pointer is a GEP with a non-zero index of the other
956     // pointer, we know they cannot alias.
957 
958     // If both accesses are unknown size, we can't do anything useful here.
959     if (V1Size == UnknownSize && V2Size == UnknownSize)
960       return MayAlias;
961 
962     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
963                                V2, V2Size, V2TBAAInfo);
964     if (R != MustAlias)
965       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
966       // If V2 is known not to alias GEP base pointer, then the two values
967       // cannot alias per GEP semantics: "A pointer value formed from a
968       // getelementptr instruction is associated with the addresses associated
969       // with the first operand of the getelementptr".
970       return R;
971 
972     const Value *GEP1BasePtr =
973       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
974                              GEP1MaxLookupReached, DL);
975 
976     // DecomposeGEPExpression and GetUnderlyingObject should return the
977     // same result except when DecomposeGEPExpression has no DataLayout.
978     if (GEP1BasePtr != UnderlyingV1) {
979       assert(!DL &&
980              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
981       return MayAlias;
982     }
983     // If the max search depth is reached the result is undefined
984     if (GEP1MaxLookupReached)
985       return MayAlias;
986   }
987 
988   // In the two GEP Case, if there is no difference in the offsets of the
989   // computed pointers, the resultant pointers are a must alias.  This
990   // hapens when we have two lexically identical GEP's (for example).
991   //
992   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
993   // must aliases the GEP, the end result is a must alias also.
994   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
995     return MustAlias;
996 
997   // If there is a constant difference between the pointers, but the difference
998   // is less than the size of the associated memory object, then we know
999   // that the objects are partially overlapping.  If the difference is
1000   // greater, we know they do not overlap.
1001   if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
1002     if (GEP1BaseOffset >= 0) {
1003       if (V2Size != UnknownSize) {
1004         if ((uint64_t)GEP1BaseOffset < V2Size)
1005           return PartialAlias;
1006         return NoAlias;
1007       }
1008     } else {
1009       // We have the situation where:
1010       // +                +
1011       // | BaseOffset     |
1012       // ---------------->|
1013       // |-->V1Size       |-------> V2Size
1014       // GEP1             V2
1015       // We need to know that V2Size is not unknown, otherwise we might have
1016       // stripped a gep with negative index ('gep <ptr>, -1, ...).
1017       if (V1Size != UnknownSize && V2Size != UnknownSize) {
1018         if (-(uint64_t)GEP1BaseOffset < V1Size)
1019           return PartialAlias;
1020         return NoAlias;
1021       }
1022     }
1023   }
1024 
1025   // Try to distinguish something like &A[i][1] against &A[42][0].
1026   // Grab the least significant bit set in any of the scales.
1027   if (!GEP1VariableIndices.empty()) {
1028     uint64_t Modulo = 0;
1029     for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1030       Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1031     Modulo = Modulo ^ (Modulo & (Modulo - 1));
1032 
1033     // We can compute the difference between the two addresses
1034     // mod Modulo. Check whether that difference guarantees that the
1035     // two locations do not alias.
1036     uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1037     if (V1Size != UnknownSize && V2Size != UnknownSize &&
1038         ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1039       return NoAlias;
1040   }
1041 
1042   // Statically, we can see that the base objects are the same, but the
1043   // pointers have dynamic offsets which we can't resolve. And none of our
1044   // little tricks above worked.
1045   //
1046   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1047   // practical effect of this is protecting TBAA in the case of dynamic
1048   // indices into arrays of unions or malloc'd memory.
1049   return PartialAlias;
1050 }
1051 
1052 static AliasAnalysis::AliasResult
MergeAliasResults(AliasAnalysis::AliasResult A,AliasAnalysis::AliasResult B)1053 MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1054   // If the results agree, take it.
1055   if (A == B)
1056     return A;
1057   // A mix of PartialAlias and MustAlias is PartialAlias.
1058   if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1059       (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1060     return AliasAnalysis::PartialAlias;
1061   // Otherwise, we don't know anything.
1062   return AliasAnalysis::MayAlias;
1063 }
1064 
1065 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1066 /// instruction against another.
1067 AliasAnalysis::AliasResult
aliasSelect(const SelectInst * SI,uint64_t SISize,const MDNode * SITBAAInfo,const Value * V2,uint64_t V2Size,const MDNode * V2TBAAInfo)1068 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
1069                                 const MDNode *SITBAAInfo,
1070                                 const Value *V2, uint64_t V2Size,
1071                                 const MDNode *V2TBAAInfo) {
1072   // If the values are Selects with the same condition, we can do a more precise
1073   // check: just check for aliases between the values on corresponding arms.
1074   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1075     if (SI->getCondition() == SI2->getCondition()) {
1076       AliasResult Alias =
1077         aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
1078                    SI2->getTrueValue(), V2Size, V2TBAAInfo);
1079       if (Alias == MayAlias)
1080         return MayAlias;
1081       AliasResult ThisAlias =
1082         aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
1083                    SI2->getFalseValue(), V2Size, V2TBAAInfo);
1084       return MergeAliasResults(ThisAlias, Alias);
1085     }
1086 
1087   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1088   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1089   AliasResult Alias =
1090     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
1091   if (Alias == MayAlias)
1092     return MayAlias;
1093 
1094   AliasResult ThisAlias =
1095     aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
1096   return MergeAliasResults(ThisAlias, Alias);
1097 }
1098 
1099 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1100 // against another.
1101 AliasAnalysis::AliasResult
aliasPHI(const PHINode * PN,uint64_t PNSize,const MDNode * PNTBAAInfo,const Value * V2,uint64_t V2Size,const MDNode * V2TBAAInfo)1102 BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1103                              const MDNode *PNTBAAInfo,
1104                              const Value *V2, uint64_t V2Size,
1105                              const MDNode *V2TBAAInfo) {
1106   // Track phi nodes we have visited. We use this information when we determine
1107   // value equivalence.
1108   VisitedPhiBBs.insert(PN->getParent());
1109 
1110   // If the values are PHIs in the same block, we can do a more precise
1111   // as well as efficient check: just check for aliases between the values
1112   // on corresponding edges.
1113   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1114     if (PN2->getParent() == PN->getParent()) {
1115       LocPair Locs(Location(PN, PNSize, PNTBAAInfo),
1116                    Location(V2, V2Size, V2TBAAInfo));
1117       if (PN > V2)
1118         std::swap(Locs.first, Locs.second);
1119       // Analyse the PHIs' inputs under the assumption that the PHIs are
1120       // NoAlias.
1121       // If the PHIs are May/MustAlias there must be (recursively) an input
1122       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1123       // there must be an operation on the PHIs within the PHIs' value cycle
1124       // that causes a MayAlias.
1125       // Pretend the phis do not alias.
1126       AliasResult Alias = NoAlias;
1127       assert(AliasCache.count(Locs) &&
1128              "There must exist an entry for the phi node");
1129       AliasResult OrigAliasResult = AliasCache[Locs];
1130       AliasCache[Locs] = NoAlias;
1131 
1132       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1133         AliasResult ThisAlias =
1134           aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
1135                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1136                      V2Size, V2TBAAInfo);
1137         Alias = MergeAliasResults(ThisAlias, Alias);
1138         if (Alias == MayAlias)
1139           break;
1140       }
1141 
1142       // Reset if speculation failed.
1143       if (Alias != NoAlias)
1144         AliasCache[Locs] = OrigAliasResult;
1145 
1146       return Alias;
1147     }
1148 
1149   SmallPtrSet<Value*, 4> UniqueSrc;
1150   SmallVector<Value*, 4> V1Srcs;
1151   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1152     Value *PV1 = PN->getIncomingValue(i);
1153     if (isa<PHINode>(PV1))
1154       // If any of the source itself is a PHI, return MayAlias conservatively
1155       // to avoid compile time explosion. The worst possible case is if both
1156       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1157       // and 'n' are the number of PHI sources.
1158       return MayAlias;
1159     if (UniqueSrc.insert(PV1))
1160       V1Srcs.push_back(PV1);
1161   }
1162 
1163   AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
1164                                  V1Srcs[0], PNSize, PNTBAAInfo);
1165   // Early exit if the check of the first PHI source against V2 is MayAlias.
1166   // Other results are not possible.
1167   if (Alias == MayAlias)
1168     return MayAlias;
1169 
1170   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1171   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1172   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1173     Value *V = V1Srcs[i];
1174 
1175     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
1176                                        V, PNSize, PNTBAAInfo);
1177     Alias = MergeAliasResults(ThisAlias, Alias);
1178     if (Alias == MayAlias)
1179       break;
1180   }
1181 
1182   return Alias;
1183 }
1184 
1185 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1186 // such as array references.
1187 //
1188 AliasAnalysis::AliasResult
aliasCheck(const Value * V1,uint64_t V1Size,const MDNode * V1TBAAInfo,const Value * V2,uint64_t V2Size,const MDNode * V2TBAAInfo)1189 BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1190                                const MDNode *V1TBAAInfo,
1191                                const Value *V2, uint64_t V2Size,
1192                                const MDNode *V2TBAAInfo) {
1193   // If either of the memory references is empty, it doesn't matter what the
1194   // pointer values are.
1195   if (V1Size == 0 || V2Size == 0)
1196     return NoAlias;
1197 
1198   // Strip off any casts if they exist.
1199   V1 = V1->stripPointerCasts();
1200   V2 = V2->stripPointerCasts();
1201 
1202   // Are we checking for alias of the same value?
1203   // Because we look 'through' phi nodes we could look at "Value" pointers from
1204   // different iterations. We must therefore make sure that this is not the
1205   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1206   // happen by looking at the visited phi nodes and making sure they cannot
1207   // reach the value.
1208   if (isValueEqualInPotentialCycles(V1, V2))
1209     return MustAlias;
1210 
1211   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1212     return NoAlias;  // Scalars cannot alias each other
1213 
1214   // Figure out what objects these things are pointing to if we can.
1215   const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1216   const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1217 
1218   // Null values in the default address space don't point to any object, so they
1219   // don't alias any other pointer.
1220   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1221     if (CPN->getType()->getAddressSpace() == 0)
1222       return NoAlias;
1223   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1224     if (CPN->getType()->getAddressSpace() == 0)
1225       return NoAlias;
1226 
1227   if (O1 != O2) {
1228     // If V1/V2 point to two different objects we know that we have no alias.
1229     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1230       return NoAlias;
1231 
1232     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1233     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1234         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1235       return NoAlias;
1236 
1237     // Function arguments can't alias with things that are known to be
1238     // unambigously identified at the function level.
1239     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1240         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1241       return NoAlias;
1242 
1243     // Most objects can't alias null.
1244     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1245         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1246       return NoAlias;
1247 
1248     // If one pointer is the result of a call/invoke or load and the other is a
1249     // non-escaping local object within the same function, then we know the
1250     // object couldn't escape to a point where the call could return it.
1251     //
1252     // Note that if the pointers are in different functions, there are a
1253     // variety of complications. A call with a nocapture argument may still
1254     // temporary store the nocapture argument's value in a temporary memory
1255     // location if that memory location doesn't escape. Or it may pass a
1256     // nocapture value to other functions as long as they don't capture it.
1257     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1258       return NoAlias;
1259     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1260       return NoAlias;
1261   }
1262 
1263   // If the size of one access is larger than the entire object on the other
1264   // side, then we know such behavior is undefined and can assume no alias.
1265   if (DL)
1266     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1267         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1268       return NoAlias;
1269 
1270   // Check the cache before climbing up use-def chains. This also terminates
1271   // otherwise infinitely recursive queries.
1272   LocPair Locs(Location(V1, V1Size, V1TBAAInfo),
1273                Location(V2, V2Size, V2TBAAInfo));
1274   if (V1 > V2)
1275     std::swap(Locs.first, Locs.second);
1276   std::pair<AliasCacheTy::iterator, bool> Pair =
1277     AliasCache.insert(std::make_pair(Locs, MayAlias));
1278   if (!Pair.second)
1279     return Pair.first->second;
1280 
1281   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1282   // GEP can't simplify, we don't even look at the PHI cases.
1283   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1284     std::swap(V1, V2);
1285     std::swap(V1Size, V2Size);
1286     std::swap(O1, O2);
1287     std::swap(V1TBAAInfo, V2TBAAInfo);
1288   }
1289   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1290     AliasResult Result = aliasGEP(GV1, V1Size, V1TBAAInfo, V2, V2Size, V2TBAAInfo, O1, O2);
1291     if (Result != MayAlias) return AliasCache[Locs] = Result;
1292   }
1293 
1294   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1295     std::swap(V1, V2);
1296     std::swap(V1Size, V2Size);
1297     std::swap(V1TBAAInfo, V2TBAAInfo);
1298   }
1299   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1300     AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1301                                   V2, V2Size, V2TBAAInfo);
1302     if (Result != MayAlias) return AliasCache[Locs] = Result;
1303   }
1304 
1305   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1306     std::swap(V1, V2);
1307     std::swap(V1Size, V2Size);
1308     std::swap(V1TBAAInfo, V2TBAAInfo);
1309   }
1310   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1311     AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1312                                      V2, V2Size, V2TBAAInfo);
1313     if (Result != MayAlias) return AliasCache[Locs] = Result;
1314   }
1315 
1316   // If both pointers are pointing into the same object and one of them
1317   // accesses is accessing the entire object, then the accesses must
1318   // overlap in some way.
1319   if (DL && O1 == O2)
1320     if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1321         (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
1322       return AliasCache[Locs] = PartialAlias;
1323 
1324   AliasResult Result =
1325     AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1326                          Location(V2, V2Size, V2TBAAInfo));
1327   return AliasCache[Locs] = Result;
1328 }
1329 
isValueEqualInPotentialCycles(const Value * V,const Value * V2)1330 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1331                                                        const Value *V2) {
1332   if (V != V2)
1333     return false;
1334 
1335   const Instruction *Inst = dyn_cast<Instruction>(V);
1336   if (!Inst)
1337     return true;
1338 
1339   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1340     return false;
1341 
1342   // Use dominance or loop info if available.
1343   DominatorTreeWrapperPass *DTWP =
1344       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1345   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1346   LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1347 
1348   // Make sure that the visited phis cannot reach the Value. This ensures that
1349   // the Values cannot come from different iterations of a potential cycle the
1350   // phi nodes could be involved in.
1351   for (SmallPtrSet<const BasicBlock *, 8>::iterator PI = VisitedPhiBBs.begin(),
1352                                                     PE = VisitedPhiBBs.end();
1353        PI != PE; ++PI)
1354     if (isPotentiallyReachable((*PI)->begin(), Inst, DT, LI))
1355       return false;
1356 
1357   return true;
1358 }
1359 
1360 /// GetIndexDifference - Dest and Src are the variable indices from two
1361 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1362 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
1363 /// difference between the two pointers.
GetIndexDifference(SmallVectorImpl<VariableGEPIndex> & Dest,const SmallVectorImpl<VariableGEPIndex> & Src)1364 void BasicAliasAnalysis::GetIndexDifference(
1365     SmallVectorImpl<VariableGEPIndex> &Dest,
1366     const SmallVectorImpl<VariableGEPIndex> &Src) {
1367   if (Src.empty())
1368     return;
1369 
1370   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1371     const Value *V = Src[i].V;
1372     ExtensionKind Extension = Src[i].Extension;
1373     int64_t Scale = Src[i].Scale;
1374 
1375     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1376     // than a few variable indexes.
1377     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1378       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1379           Dest[j].Extension != Extension)
1380         continue;
1381 
1382       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1383       // goes to zero, remove the entry.
1384       if (Dest[j].Scale != Scale)
1385         Dest[j].Scale -= Scale;
1386       else
1387         Dest.erase(Dest.begin() + j);
1388       Scale = 0;
1389       break;
1390     }
1391 
1392     // If we didn't consume this entry, add it to the end of the Dest list.
1393     if (Scale) {
1394       VariableGEPIndex Entry = { V, Extension, -Scale };
1395       Dest.push_back(Entry);
1396     }
1397   }
1398 }
1399