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