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