1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the primary stateless implementation of the
10 // Alias Analysis interface that implements identities (two different
11 // globals cannot alias, etc), but does no stateful analysis.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/Analysis/PhiValues.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/ConstantRange.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GetElementPtrTypeIterator.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/InstrTypes.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Operator.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/User.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/InitializePasses.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/KnownBits.h"
57 #include <cassert>
58 #include <cstdint>
59 #include <cstdlib>
60 #include <utility>
61 
62 #define DEBUG_TYPE "basicaa"
63 
64 using namespace llvm;
65 
66 /// Enable analysis of recursive PHI nodes.
67 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
68                                           cl::init(true));
69 
70 /// SearchLimitReached / SearchTimes shows how often the limit of
71 /// to decompose GEPs is reached. It will affect the precision
72 /// of basic alias analysis.
73 STATISTIC(SearchLimitReached, "Number of times the limit to "
74                               "decompose GEPs is reached");
75 STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
76 
77 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
78 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
79 /// careful with value equivalence. We use reachability to make sure a value
80 /// cannot be involved in a cycle.
81 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
82 
83 // The max limit of the search depth in DecomposeGEPExpression() and
84 // getUnderlyingObject().
85 static const unsigned MaxLookupSearchDepth = 6;
86 
87 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
88                                FunctionAnalysisManager::Invalidator &Inv) {
89   // We don't care if this analysis itself is preserved, it has no state. But
90   // we need to check that the analyses it depends on have been. Note that we
91   // may be created without handles to some analyses and in that case don't
92   // depend on them.
93   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
94       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
95       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
96     return true;
97 
98   // Otherwise this analysis result remains valid.
99   return false;
100 }
101 
102 //===----------------------------------------------------------------------===//
103 // Useful predicates
104 //===----------------------------------------------------------------------===//
105 
106 /// Returns the size of the object specified by V or UnknownSize if unknown.
107 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
108                               const TargetLibraryInfo &TLI,
109                               bool NullIsValidLoc,
110                               bool RoundToAlign = false) {
111   uint64_t Size;
112   ObjectSizeOpts Opts;
113   Opts.RoundToAlign = RoundToAlign;
114   Opts.NullIsUnknownSize = NullIsValidLoc;
115   if (getObjectSize(V, Size, DL, &TLI, Opts))
116     return Size;
117   return MemoryLocation::UnknownSize;
118 }
119 
120 /// Returns true if we can prove that the object specified by V is smaller than
121 /// Size.
122 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
123                                 const DataLayout &DL,
124                                 const TargetLibraryInfo &TLI,
125                                 bool NullIsValidLoc) {
126   // Note that the meanings of the "object" are slightly different in the
127   // following contexts:
128   //    c1: llvm::getObjectSize()
129   //    c2: llvm.objectsize() intrinsic
130   //    c3: isObjectSmallerThan()
131   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
132   // refers to the "entire object".
133   //
134   //  Consider this example:
135   //     char *p = (char*)malloc(100)
136   //     char *q = p+80;
137   //
138   //  In the context of c1 and c2, the "object" pointed by q refers to the
139   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
140   //
141   //  However, in the context of c3, the "object" refers to the chunk of memory
142   // being allocated. So, the "object" has 100 bytes, and q points to the middle
143   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
144   // parameter, before the llvm::getObjectSize() is called to get the size of
145   // entire object, we should:
146   //    - either rewind the pointer q to the base-address of the object in
147   //      question (in this case rewind to p), or
148   //    - just give up. It is up to caller to make sure the pointer is pointing
149   //      to the base address the object.
150   //
151   // We go for 2nd option for simplicity.
152   if (!isIdentifiedObject(V))
153     return false;
154 
155   // This function needs to use the aligned object size because we allow
156   // reads a bit past the end given sufficient alignment.
157   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
158                                       /*RoundToAlign*/ true);
159 
160   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
161 }
162 
163 /// Return the minimal extent from \p V to the end of the underlying object,
164 /// assuming the result is used in an aliasing query. E.g., we do use the query
165 /// location size and the fact that null pointers cannot alias here.
166 static uint64_t getMinimalExtentFrom(const Value &V,
167                                      const LocationSize &LocSize,
168                                      const DataLayout &DL,
169                                      bool NullIsValidLoc) {
170   // If we have dereferenceability information we know a lower bound for the
171   // extent as accesses for a lower offset would be valid. We need to exclude
172   // the "or null" part if null is a valid pointer. We can ignore frees, as an
173   // access after free would be undefined behavior.
174   bool CanBeNull, CanBeFreed;
175   uint64_t DerefBytes =
176     V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
177   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
178   // If queried with a precise location size, we assume that location size to be
179   // accessed, thus valid.
180   if (LocSize.isPrecise())
181     DerefBytes = std::max(DerefBytes, LocSize.getValue());
182   return DerefBytes;
183 }
184 
185 /// Returns true if we can prove that the object specified by V has size Size.
186 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
187                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
188   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
189   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
190 }
191 
192 //===----------------------------------------------------------------------===//
193 // CaptureInfo implementations
194 //===----------------------------------------------------------------------===//
195 
196 CaptureInfo::~CaptureInfo() = default;
197 
198 bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object,
199                                                 const Instruction *I) {
200   return isNonEscapingLocalObject(Object, &IsCapturedCache);
201 }
202 
203 bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object,
204                                                  const Instruction *I) {
205   if (!isIdentifiedFunctionLocal(Object))
206     return false;
207 
208   auto Iter = EarliestEscapes.insert({Object, nullptr});
209   if (Iter.second) {
210     Instruction *EarliestCapture = FindEarliestCapture(
211         Object, *const_cast<Function *>(I->getFunction()),
212         /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT, EphValues);
213     if (EarliestCapture) {
214       auto Ins = Inst2Obj.insert({EarliestCapture, {}});
215       Ins.first->second.push_back(Object);
216     }
217     Iter.first->second = EarliestCapture;
218   }
219 
220   // No capturing instruction.
221   if (!Iter.first->second)
222     return true;
223 
224   return I != Iter.first->second &&
225          !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI);
226 }
227 
228 void EarliestEscapeInfo::removeInstruction(Instruction *I) {
229   auto Iter = Inst2Obj.find(I);
230   if (Iter != Inst2Obj.end()) {
231     for (const Value *Obj : Iter->second)
232       EarliestEscapes.erase(Obj);
233     Inst2Obj.erase(I);
234   }
235 }
236 
237 //===----------------------------------------------------------------------===//
238 // GetElementPtr Instruction Decomposition and Analysis
239 //===----------------------------------------------------------------------===//
240 
241 namespace {
242 /// Represents zext(sext(trunc(V))).
243 struct CastedValue {
244   const Value *V;
245   unsigned ZExtBits = 0;
246   unsigned SExtBits = 0;
247   unsigned TruncBits = 0;
248 
249   explicit CastedValue(const Value *V) : V(V) {}
250   explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
251                        unsigned TruncBits)
252       : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits) {}
253 
254   unsigned getBitWidth() const {
255     return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
256            SExtBits;
257   }
258 
259   CastedValue withValue(const Value *NewV) const {
260     return CastedValue(NewV, ZExtBits, SExtBits, TruncBits);
261   }
262 
263   /// Replace V with zext(NewV)
264   CastedValue withZExtOfValue(const Value *NewV) const {
265     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
266                         NewV->getType()->getPrimitiveSizeInBits();
267     if (ExtendBy <= TruncBits)
268       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
269 
270     // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
271     ExtendBy -= TruncBits;
272     return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0);
273   }
274 
275   /// Replace V with sext(NewV)
276   CastedValue withSExtOfValue(const Value *NewV) const {
277     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
278                         NewV->getType()->getPrimitiveSizeInBits();
279     if (ExtendBy <= TruncBits)
280       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
281 
282     // zext(sext(sext(NewV)))
283     ExtendBy -= TruncBits;
284     return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0);
285   }
286 
287   APInt evaluateWith(APInt N) const {
288     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
289            "Incompatible bit width");
290     if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);
291     if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
292     if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);
293     return N;
294   }
295 
296   ConstantRange evaluateWith(ConstantRange N) const {
297     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
298            "Incompatible bit width");
299     if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);
300     if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
301     if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);
302     return N;
303   }
304 
305   bool canDistributeOver(bool NUW, bool NSW) const {
306     // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
307     // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
308     // trunc(x op y) == trunc(x) op trunc(y)
309     return (!ZExtBits || NUW) && (!SExtBits || NSW);
310   }
311 
312   bool hasSameCastsAs(const CastedValue &Other) const {
313     return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
314            TruncBits == Other.TruncBits;
315   }
316 };
317 
318 /// Represents zext(sext(trunc(V))) * Scale + Offset.
319 struct LinearExpression {
320   CastedValue Val;
321   APInt Scale;
322   APInt Offset;
323 
324   /// True if all operations in this expression are NSW.
325   bool IsNSW;
326 
327   LinearExpression(const CastedValue &Val, const APInt &Scale,
328                    const APInt &Offset, bool IsNSW)
329       : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {}
330 
331   LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) {
332     unsigned BitWidth = Val.getBitWidth();
333     Scale = APInt(BitWidth, 1);
334     Offset = APInt(BitWidth, 0);
335   }
336 
337   LinearExpression mul(const APInt &Other, bool MulIsNSW) const {
338     // The check for zero offset is necessary, because generally
339     // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
340     bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
341     return LinearExpression(Val, Scale * Other, Offset * Other, NSW);
342   }
343 };
344 }
345 
346 /// Analyzes the specified value as a linear expression: "A*V + B", where A and
347 /// B are constant integers.
348 static LinearExpression GetLinearExpression(
349     const CastedValue &Val,  const DataLayout &DL, unsigned Depth,
350     AssumptionCache *AC, DominatorTree *DT) {
351   // Limit our recursion depth.
352   if (Depth == 6)
353     return Val;
354 
355   if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
356     return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
357                             Val.evaluateWith(Const->getValue()), true);
358 
359   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
360     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
361       APInt RHS = Val.evaluateWith(RHSC->getValue());
362       // The only non-OBO case we deal with is or, and only limited to the
363       // case where it is both nuw and nsw.
364       bool NUW = true, NSW = true;
365       if (isa<OverflowingBinaryOperator>(BOp)) {
366         NUW &= BOp->hasNoUnsignedWrap();
367         NSW &= BOp->hasNoSignedWrap();
368       }
369       if (!Val.canDistributeOver(NUW, NSW))
370         return Val;
371 
372       // While we can distribute over trunc, we cannot preserve nowrap flags
373       // in that case.
374       if (Val.TruncBits)
375         NUW = NSW = false;
376 
377       LinearExpression E(Val);
378       switch (BOp->getOpcode()) {
379       default:
380         // We don't understand this instruction, so we can't decompose it any
381         // further.
382         return Val;
383       case Instruction::Or:
384         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
385         // analyze it.
386         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
387                                BOp, DT))
388           return Val;
389 
390         LLVM_FALLTHROUGH;
391       case Instruction::Add: {
392         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
393                                 Depth + 1, AC, DT);
394         E.Offset += RHS;
395         E.IsNSW &= NSW;
396         break;
397       }
398       case Instruction::Sub: {
399         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
400                                 Depth + 1, AC, DT);
401         E.Offset -= RHS;
402         E.IsNSW &= NSW;
403         break;
404       }
405       case Instruction::Mul:
406         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
407                                 Depth + 1, AC, DT)
408                 .mul(RHS, NSW);
409         break;
410       case Instruction::Shl:
411         // We're trying to linearize an expression of the kind:
412         //   shl i8 -128, 36
413         // where the shift count exceeds the bitwidth of the type.
414         // We can't decompose this further (the expression would return
415         // a poison value).
416         if (RHS.getLimitedValue() > Val.getBitWidth())
417           return Val;
418 
419         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
420                                 Depth + 1, AC, DT);
421         E.Offset <<= RHS.getLimitedValue();
422         E.Scale <<= RHS.getLimitedValue();
423         E.IsNSW &= NSW;
424         break;
425       }
426       return E;
427     }
428   }
429 
430   if (isa<ZExtInst>(Val.V))
431     return GetLinearExpression(
432         Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
433         DL, Depth + 1, AC, DT);
434 
435   if (isa<SExtInst>(Val.V))
436     return GetLinearExpression(
437         Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
438         DL, Depth + 1, AC, DT);
439 
440   return Val;
441 }
442 
443 /// To ensure a pointer offset fits in an integer of size IndexSize
444 /// (in bits) when that size is smaller than the maximum index size. This is
445 /// an issue, for example, in particular for 32b pointers with negative indices
446 /// that rely on two's complement wrap-arounds for precise alias information
447 /// where the maximum index size is 64b.
448 static APInt adjustToIndexSize(const APInt &Offset, unsigned IndexSize) {
449   assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!");
450   unsigned ShiftBits = Offset.getBitWidth() - IndexSize;
451   return (Offset << ShiftBits).ashr(ShiftBits);
452 }
453 
454 namespace {
455 // A linear transformation of a Value; this class represents
456 // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
457 struct VariableGEPIndex {
458   CastedValue Val;
459   APInt Scale;
460 
461   // Context instruction to use when querying information about this index.
462   const Instruction *CxtI;
463 
464   /// True if all operations in this expression are NSW.
465   bool IsNSW;
466 
467   void dump() const {
468     print(dbgs());
469     dbgs() << "\n";
470   }
471   void print(raw_ostream &OS) const {
472     OS << "(V=" << Val.V->getName()
473        << ", zextbits=" << Val.ZExtBits
474        << ", sextbits=" << Val.SExtBits
475        << ", truncbits=" << Val.TruncBits
476        << ", scale=" << Scale << ")";
477   }
478 };
479 }
480 
481 // Represents the internal structure of a GEP, decomposed into a base pointer,
482 // constant offsets, and variable scaled indices.
483 struct BasicAAResult::DecomposedGEP {
484   // Base pointer of the GEP
485   const Value *Base;
486   // Total constant offset from base.
487   APInt Offset;
488   // Scaled variable (non-constant) indices.
489   SmallVector<VariableGEPIndex, 4> VarIndices;
490   // Are all operations inbounds GEPs or non-indexing operations?
491   // (None iff expression doesn't involve any geps)
492   Optional<bool> InBounds;
493 
494   void dump() const {
495     print(dbgs());
496     dbgs() << "\n";
497   }
498   void print(raw_ostream &OS) const {
499     OS << "(DecomposedGEP Base=" << Base->getName()
500        << ", Offset=" << Offset
501        << ", VarIndices=[";
502     for (size_t i = 0; i < VarIndices.size(); i++) {
503       if (i != 0)
504         OS << ", ";
505       VarIndices[i].print(OS);
506     }
507     OS << "])";
508   }
509 };
510 
511 
512 /// If V is a symbolic pointer expression, decompose it into a base pointer
513 /// with a constant offset and a number of scaled symbolic offsets.
514 ///
515 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
516 /// in the VarIndices vector) are Value*'s that are known to be scaled by the
517 /// specified amount, but which may have other unrepresented high bits. As
518 /// such, the gep cannot necessarily be reconstructed from its decomposed form.
519 BasicAAResult::DecomposedGEP
520 BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
521                                       AssumptionCache *AC, DominatorTree *DT) {
522   // Limit recursion depth to limit compile time in crazy cases.
523   unsigned MaxLookup = MaxLookupSearchDepth;
524   SearchTimes++;
525   const Instruction *CxtI = dyn_cast<Instruction>(V);
526 
527   unsigned MaxIndexSize = DL.getMaxIndexSizeInBits();
528   DecomposedGEP Decomposed;
529   Decomposed.Offset = APInt(MaxIndexSize, 0);
530   do {
531     // See if this is a bitcast or GEP.
532     const Operator *Op = dyn_cast<Operator>(V);
533     if (!Op) {
534       // The only non-operator case we can handle are GlobalAliases.
535       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
536         if (!GA->isInterposable()) {
537           V = GA->getAliasee();
538           continue;
539         }
540       }
541       Decomposed.Base = V;
542       return Decomposed;
543     }
544 
545     if (Op->getOpcode() == Instruction::BitCast ||
546         Op->getOpcode() == Instruction::AddrSpaceCast) {
547       V = Op->getOperand(0);
548       continue;
549     }
550 
551     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
552     if (!GEPOp) {
553       if (const auto *PHI = dyn_cast<PHINode>(V)) {
554         // Look through single-arg phi nodes created by LCSSA.
555         if (PHI->getNumIncomingValues() == 1) {
556           V = PHI->getIncomingValue(0);
557           continue;
558         }
559       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
560         // CaptureTracking can know about special capturing properties of some
561         // intrinsics like launder.invariant.group, that can't be expressed with
562         // the attributes, but have properties like returning aliasing pointer.
563         // Because some analysis may assume that nocaptured pointer is not
564         // returned from some special intrinsic (because function would have to
565         // be marked with returns attribute), it is crucial to use this function
566         // because it should be in sync with CaptureTracking. Not using it may
567         // cause weird miscompilations where 2 aliasing pointers are assumed to
568         // noalias.
569         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
570           V = RP;
571           continue;
572         }
573       }
574 
575       Decomposed.Base = V;
576       return Decomposed;
577     }
578 
579     // Track whether we've seen at least one in bounds gep, and if so, whether
580     // all geps parsed were in bounds.
581     if (Decomposed.InBounds == None)
582       Decomposed.InBounds = GEPOp->isInBounds();
583     else if (!GEPOp->isInBounds())
584       Decomposed.InBounds = false;
585 
586     assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
587 
588     // Don't attempt to analyze GEPs if index scale is not a compile-time
589     // constant.
590     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
591       Decomposed.Base = V;
592       return Decomposed;
593     }
594 
595     unsigned AS = GEPOp->getPointerAddressSpace();
596     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
597     gep_type_iterator GTI = gep_type_begin(GEPOp);
598     unsigned IndexSize = DL.getIndexSizeInBits(AS);
599     // Assume all GEP operands are constants until proven otherwise.
600     bool GepHasConstantOffset = true;
601     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
602          I != E; ++I, ++GTI) {
603       const Value *Index = *I;
604       // Compute the (potentially symbolic) offset in bytes for this index.
605       if (StructType *STy = GTI.getStructTypeOrNull()) {
606         // For a struct, add the member offset.
607         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
608         if (FieldNo == 0)
609           continue;
610 
611         Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
612         continue;
613       }
614 
615       // For an array/pointer, add the element offset, explicitly scaled.
616       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
617         if (CIdx->isZero())
618           continue;
619         Decomposed.Offset +=
620             DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
621             CIdx->getValue().sextOrTrunc(MaxIndexSize);
622         continue;
623       }
624 
625       GepHasConstantOffset = false;
626 
627       // If the integer type is smaller than the index size, it is implicitly
628       // sign extended or truncated to index size.
629       unsigned Width = Index->getType()->getIntegerBitWidth();
630       unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
631       unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
632       LinearExpression LE = GetLinearExpression(
633           CastedValue(Index, 0, SExtBits, TruncBits), DL, 0, AC, DT);
634 
635       // Scale by the type size.
636       unsigned TypeSize =
637           DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize();
638       LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds());
639       Decomposed.Offset += LE.Offset.sext(MaxIndexSize);
640       APInt Scale = LE.Scale.sext(MaxIndexSize);
641 
642       // If we already had an occurrence of this index variable, merge this
643       // scale into it.  For example, we want to handle:
644       //   A[x][x] -> x*16 + x*4 -> x*20
645       // This also ensures that 'x' only appears in the index list once.
646       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
647         if (Decomposed.VarIndices[i].Val.V == LE.Val.V &&
648             Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {
649           Scale += Decomposed.VarIndices[i].Scale;
650           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
651           break;
652         }
653       }
654 
655       // Make sure that we have a scale that makes sense for this target's
656       // index size.
657       Scale = adjustToIndexSize(Scale, IndexSize);
658 
659       if (!!Scale) {
660         VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW};
661         Decomposed.VarIndices.push_back(Entry);
662       }
663     }
664 
665     // Take care of wrap-arounds
666     if (GepHasConstantOffset)
667       Decomposed.Offset = adjustToIndexSize(Decomposed.Offset, IndexSize);
668 
669     // Analyze the base pointer next.
670     V = GEPOp->getOperand(0);
671   } while (--MaxLookup);
672 
673   // If the chain of expressions is too deep, just return early.
674   Decomposed.Base = V;
675   SearchLimitReached++;
676   return Decomposed;
677 }
678 
679 /// Returns whether the given pointer value points to memory that is local to
680 /// the function, with global constants being considered local to all
681 /// functions.
682 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
683                                            AAQueryInfo &AAQI, bool OrLocal) {
684   assert(Visited.empty() && "Visited must be cleared after use!");
685 
686   unsigned MaxLookup = 8;
687   SmallVector<const Value *, 16> Worklist;
688   Worklist.push_back(Loc.Ptr);
689   do {
690     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
691     if (!Visited.insert(V).second) {
692       Visited.clear();
693       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
694     }
695 
696     // An alloca instruction defines local memory.
697     if (OrLocal && isa<AllocaInst>(V))
698       continue;
699 
700     // A global constant counts as local memory for our purposes.
701     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
702       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
703       // global to be marked constant in some modules and non-constant in
704       // others.  GV may even be a declaration, not a definition.
705       if (!GV->isConstant()) {
706         Visited.clear();
707         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
708       }
709       continue;
710     }
711 
712     // If both select values point to local memory, then so does the select.
713     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
714       Worklist.push_back(SI->getTrueValue());
715       Worklist.push_back(SI->getFalseValue());
716       continue;
717     }
718 
719     // If all values incoming to a phi node point to local memory, then so does
720     // the phi.
721     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
722       // Don't bother inspecting phi nodes with many operands.
723       if (PN->getNumIncomingValues() > MaxLookup) {
724         Visited.clear();
725         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
726       }
727       append_range(Worklist, PN->incoming_values());
728       continue;
729     }
730 
731     // Otherwise be conservative.
732     Visited.clear();
733     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
734   } while (!Worklist.empty() && --MaxLookup);
735 
736   Visited.clear();
737   return Worklist.empty();
738 }
739 
740 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
741   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
742   return II && II->getIntrinsicID() == IID;
743 }
744 
745 /// Returns the behavior when calling the given call site.
746 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
747   if (Call->doesNotAccessMemory())
748     // Can't do better than this.
749     return FMRB_DoesNotAccessMemory;
750 
751   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
752 
753   // If the callsite knows it only reads memory, don't return worse
754   // than that.
755   if (Call->onlyReadsMemory())
756     Min = FMRB_OnlyReadsMemory;
757   else if (Call->onlyWritesMemory())
758     Min = FMRB_OnlyWritesMemory;
759 
760   if (Call->onlyAccessesArgMemory())
761     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
762   else if (Call->onlyAccessesInaccessibleMemory())
763     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
764   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
765     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
766 
767   // If the call has operand bundles then aliasing attributes from the function
768   // it calls do not directly apply to the call.  This can be made more precise
769   // in the future.
770   //
771   // If the call lives in a presplit coroutine, the readnone, writeonly,
772   // inaccessiblememonly and inaccessiblemem_or_argmemonly attribute from the
773   // function might not directly apply to the call.
774   if (!Call->hasOperandBundles() && !Call->getFunction()->isPresplitCoroutine())
775     if (const Function *F = Call->getCalledFunction())
776       Min =
777           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
778 
779   return Min;
780 }
781 
782 /// Returns the behavior when calling the given function. For use when the call
783 /// site is not known.
784 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
785   // If the function declares it doesn't access memory, we can't do better.
786   if (F->doesNotAccessMemory())
787     return FMRB_DoesNotAccessMemory;
788 
789   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
790 
791   // If the function declares it only reads memory, go with that.
792   if (F->onlyReadsMemory())
793     Min = FMRB_OnlyReadsMemory;
794   else if (F->onlyWritesMemory())
795     Min = FMRB_OnlyWritesMemory;
796 
797   if (F->onlyAccessesArgMemory())
798     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
799   else if (F->onlyAccessesInaccessibleMemory())
800     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
801   else if (F->onlyAccessesInaccessibleMemOrArgMem())
802     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
803 
804   return Min;
805 }
806 
807 /// Returns true if this is a writeonly (i.e Mod only) parameter.
808 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
809                              const TargetLibraryInfo &TLI) {
810   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
811     return true;
812 
813   // We can bound the aliasing properties of memset_pattern16 just as we can
814   // for memcpy/memset.  This is particularly important because the
815   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
816   // whenever possible.
817   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
818   // attributes.
819   LibFunc F;
820   if (Call->getCalledFunction() &&
821       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
822       F == LibFunc_memset_pattern16 && TLI.has(F))
823     if (ArgIdx == 0)
824       return true;
825 
826   // TODO: memset_pattern4, memset_pattern8
827   // TODO: _chk variants
828   // TODO: strcmp, strcpy
829 
830   return false;
831 }
832 
833 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
834                                            unsigned ArgIdx) {
835   // Checking for known builtin intrinsics and target library functions.
836   if (isWriteOnlyParam(Call, ArgIdx, TLI))
837     return ModRefInfo::Mod;
838 
839   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
840     return ModRefInfo::Ref;
841 
842   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
843     return ModRefInfo::NoModRef;
844 
845   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
846 }
847 
848 #ifndef NDEBUG
849 static const Function *getParent(const Value *V) {
850   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
851     if (!inst->getParent())
852       return nullptr;
853     return inst->getParent()->getParent();
854   }
855 
856   if (const Argument *arg = dyn_cast<Argument>(V))
857     return arg->getParent();
858 
859   return nullptr;
860 }
861 
862 static bool notDifferentParent(const Value *O1, const Value *O2) {
863 
864   const Function *F1 = getParent(O1);
865   const Function *F2 = getParent(O2);
866 
867   return !F1 || !F2 || F1 == F2;
868 }
869 #endif
870 
871 AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
872                                  const MemoryLocation &LocB,
873                                  AAQueryInfo &AAQI) {
874   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
875          "BasicAliasAnalysis doesn't support interprocedural queries.");
876   return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI);
877 }
878 
879 /// Checks to see if the specified callsite can clobber the specified memory
880 /// object.
881 ///
882 /// Since we only look at local properties of this function, we really can't
883 /// say much about this query.  We do, however, use simple "address taken"
884 /// analysis on local objects.
885 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
886                                         const MemoryLocation &Loc,
887                                         AAQueryInfo &AAQI) {
888   assert(notDifferentParent(Call, Loc.Ptr) &&
889          "AliasAnalysis query involving multiple functions!");
890 
891   const Value *Object = getUnderlyingObject(Loc.Ptr);
892 
893   // Calls marked 'tail' cannot read or write allocas from the current frame
894   // because the current frame might be destroyed by the time they run. However,
895   // a tail call may use an alloca with byval. Calling with byval copies the
896   // contents of the alloca into argument registers or stack slots, so there is
897   // no lifetime issue.
898   if (isa<AllocaInst>(Object))
899     if (const CallInst *CI = dyn_cast<CallInst>(Call))
900       if (CI->isTailCall() &&
901           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
902         return ModRefInfo::NoModRef;
903 
904   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
905   // modify them even though the alloca is not escaped.
906   if (auto *AI = dyn_cast<AllocaInst>(Object))
907     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
908       return ModRefInfo::Mod;
909 
910   // If the pointer is to a locally allocated object that does not escape,
911   // then the call can not mod/ref the pointer unless the call takes the pointer
912   // as an argument, and itself doesn't capture it.
913   if (!isa<Constant>(Object) && Call != Object &&
914       AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) {
915 
916     // Optimistically assume that call doesn't touch Object and check this
917     // assumption in the following loop.
918     ModRefInfo Result = ModRefInfo::NoModRef;
919     bool IsMustAlias = true;
920 
921     unsigned OperandNo = 0;
922     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
923          CI != CE; ++CI, ++OperandNo) {
924       // Only look at the no-capture or byval pointer arguments.  If this
925       // pointer were passed to arguments that were neither of these, then it
926       // couldn't be no-capture.
927       if (!(*CI)->getType()->isPointerTy() ||
928           (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() &&
929            !Call->isByValArgument(OperandNo)))
930         continue;
931 
932       // Call doesn't access memory through this operand, so we don't care
933       // if it aliases with Object.
934       if (Call->doesNotAccessMemory(OperandNo))
935         continue;
936 
937       // If this is a no-capture pointer argument, see if we can tell that it
938       // is impossible to alias the pointer we're checking.
939       AliasResult AR = getBestAAResults().alias(
940           MemoryLocation::getBeforeOrAfter(*CI),
941           MemoryLocation::getBeforeOrAfter(Object), AAQI);
942       if (AR != AliasResult::MustAlias)
943         IsMustAlias = false;
944       // Operand doesn't alias 'Object', continue looking for other aliases
945       if (AR == AliasResult::NoAlias)
946         continue;
947       // Operand aliases 'Object', but call doesn't modify it. Strengthen
948       // initial assumption and keep looking in case if there are more aliases.
949       if (Call->onlyReadsMemory(OperandNo)) {
950         Result = setRef(Result);
951         continue;
952       }
953       // Operand aliases 'Object' but call only writes into it.
954       if (Call->onlyWritesMemory(OperandNo)) {
955         Result = setMod(Result);
956         continue;
957       }
958       // This operand aliases 'Object' and call reads and writes into it.
959       // Setting ModRef will not yield an early return below, MustAlias is not
960       // used further.
961       Result = ModRefInfo::ModRef;
962       break;
963     }
964 
965     // No operand aliases, reset Must bit. Add below if at least one aliases
966     // and all aliases found are MustAlias.
967     if (isNoModRef(Result))
968       IsMustAlias = false;
969 
970     // Early return if we improved mod ref information
971     if (!isModAndRefSet(Result)) {
972       if (isNoModRef(Result))
973         return ModRefInfo::NoModRef;
974       return IsMustAlias ? setMust(Result) : clearMust(Result);
975     }
976   }
977 
978   // If the call is malloc/calloc like, we can assume that it doesn't
979   // modify any IR visible value.  This is only valid because we assume these
980   // routines do not read values visible in the IR.  TODO: Consider special
981   // casing realloc and strdup routines which access only their arguments as
982   // well.  Or alternatively, replace all of this with inaccessiblememonly once
983   // that's implemented fully.
984   if (isMallocOrCallocLikeFn(Call, &TLI)) {
985     // Be conservative if the accessed pointer may alias the allocation -
986     // fallback to the generic handling below.
987     if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc,
988                                  AAQI) == AliasResult::NoAlias)
989       return ModRefInfo::NoModRef;
990   }
991 
992   // Ideally, there should be no need to special case for memcpy/memove
993   // intrinsics here since general machinery (based on memory attributes) should
994   // already handle it just fine. Unfortunately, it doesn't due to deficiency in
995   // operand bundles support. At the moment it's not clear if complexity behind
996   // enhancing general mechanism worths it.
997   // TODO: Consider improving operand bundles support in general mechanism.
998   if (auto *Inst = dyn_cast<AnyMemTransferInst>(Call)) {
999     AliasResult SrcAA =
1000         getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI);
1001     AliasResult DestAA =
1002         getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI);
1003     // It's also possible for Loc to alias both src and dest, or neither.
1004     ModRefInfo rv = ModRefInfo::NoModRef;
1005     if (SrcAA != AliasResult::NoAlias || Call->hasReadingOperandBundles())
1006       rv = setRef(rv);
1007     if (DestAA != AliasResult::NoAlias || Call->hasClobberingOperandBundles())
1008       rv = setMod(rv);
1009     return rv;
1010   }
1011 
1012   // Guard intrinsics are marked as arbitrarily writing so that proper control
1013   // dependencies are maintained but they never mods any particular memory
1014   // location.
1015   //
1016   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1017   // heap state at the point the guard is issued needs to be consistent in case
1018   // the guard invokes the "deopt" continuation.
1019   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
1020     return ModRefInfo::Ref;
1021   // The same applies to deoptimize which is essentially a guard(false).
1022   if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize))
1023     return ModRefInfo::Ref;
1024 
1025   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
1026   // writing so that proper control dependencies are maintained but they never
1027   // mod any particular memory location visible to the IR.
1028   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
1029   // intrinsic is now modeled as reading memory. This prevents hoisting the
1030   // invariant.start intrinsic over stores. Consider:
1031   // *ptr = 40;
1032   // *ptr = 50;
1033   // invariant_start(ptr)
1034   // int val = *ptr;
1035   // print(val);
1036   //
1037   // This cannot be transformed to:
1038   //
1039   // *ptr = 40;
1040   // invariant_start(ptr)
1041   // *ptr = 50;
1042   // int val = *ptr;
1043   // print(val);
1044   //
1045   // The transformation will cause the second store to be ignored (based on
1046   // rules of invariant.start)  and print 40, while the first program always
1047   // prints 50.
1048   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
1049     return ModRefInfo::Ref;
1050 
1051   // The AAResultBase base class has some smarts, lets use them.
1052   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
1053 }
1054 
1055 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
1056                                         const CallBase *Call2,
1057                                         AAQueryInfo &AAQI) {
1058   // Guard intrinsics are marked as arbitrarily writing so that proper control
1059   // dependencies are maintained but they never mods any particular memory
1060   // location.
1061   //
1062   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1063   // heap state at the point the guard is issued needs to be consistent in case
1064   // the guard invokes the "deopt" continuation.
1065 
1066   // NB! This function is *not* commutative, so we special case two
1067   // possibilities for guard intrinsics.
1068 
1069   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
1070     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
1071                ? ModRefInfo::Ref
1072                : ModRefInfo::NoModRef;
1073 
1074   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1075     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
1076                ? ModRefInfo::Mod
1077                : ModRefInfo::NoModRef;
1078 
1079   // The AAResultBase base class has some smarts, lets use them.
1080   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
1081 }
1082 
1083 /// Return true if we know V to the base address of the corresponding memory
1084 /// object.  This implies that any address less than V must be out of bounds
1085 /// for the underlying object.  Note that just being isIdentifiedObject() is
1086 /// not enough - For example, a negative offset from a noalias argument or call
1087 /// can be inbounds w.r.t the actual underlying object.
1088 static bool isBaseOfObject(const Value *V) {
1089   // TODO: We can handle other cases here
1090   // 1) For GC languages, arguments to functions are often required to be
1091   //    base pointers.
1092   // 2) Result of allocation routines are often base pointers.  Leverage TLI.
1093   return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
1094 }
1095 
1096 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1097 /// another pointer.
1098 ///
1099 /// We know that V1 is a GEP, but we don't know anything about V2.
1100 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1101 /// V2.
1102 AliasResult BasicAAResult::aliasGEP(
1103     const GEPOperator *GEP1, LocationSize V1Size,
1104     const Value *V2, LocationSize V2Size,
1105     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1106   if (!V1Size.hasValue() && !V2Size.hasValue()) {
1107     // TODO: This limitation exists for compile-time reasons. Relax it if we
1108     // can avoid exponential pathological cases.
1109     if (!isa<GEPOperator>(V2))
1110       return AliasResult::MayAlias;
1111 
1112     // If both accesses have unknown size, we can only check whether the base
1113     // objects don't alias.
1114     AliasResult BaseAlias = getBestAAResults().alias(
1115         MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1116         MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1117     return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1118                                              : AliasResult::MayAlias;
1119   }
1120 
1121   DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1122   DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
1123 
1124   // Bail if we were not able to decompose anything.
1125   if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1126     return AliasResult::MayAlias;
1127 
1128   // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1129   // symbolic difference.
1130   subtractDecomposedGEPs(DecompGEP1, DecompGEP2);
1131 
1132   // If an inbounds GEP would have to start from an out of bounds address
1133   // for the two to alias, then we can assume noalias.
1134   if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() &&
1135       V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) &&
1136       isBaseOfObject(DecompGEP2.Base))
1137     return AliasResult::NoAlias;
1138 
1139   if (isa<GEPOperator>(V2)) {
1140     // Symmetric case to above.
1141     if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() &&
1142         V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) &&
1143         isBaseOfObject(DecompGEP1.Base))
1144       return AliasResult::NoAlias;
1145   }
1146 
1147   // For GEPs with identical offsets, we can preserve the size and AAInfo
1148   // when performing the alias check on the underlying objects.
1149   if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1150     return getBestAAResults().alias(MemoryLocation(DecompGEP1.Base, V1Size),
1151                                     MemoryLocation(DecompGEP2.Base, V2Size),
1152                                     AAQI);
1153 
1154   // Do the base pointers alias?
1155   AliasResult BaseAlias = getBestAAResults().alias(
1156       MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1157       MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);
1158 
1159   // If we get a No or May, then return it immediately, no amount of analysis
1160   // will improve this situation.
1161   if (BaseAlias != AliasResult::MustAlias) {
1162     assert(BaseAlias == AliasResult::NoAlias ||
1163            BaseAlias == AliasResult::MayAlias);
1164     return BaseAlias;
1165   }
1166 
1167   // If there is a constant difference between the pointers, but the difference
1168   // is less than the size of the associated memory object, then we know
1169   // that the objects are partially overlapping.  If the difference is
1170   // greater, we know they do not overlap.
1171   if (DecompGEP1.VarIndices.empty()) {
1172     APInt &Off = DecompGEP1.Offset;
1173 
1174     // Initialize for Off >= 0 (V2 <= GEP1) case.
1175     const Value *LeftPtr = V2;
1176     const Value *RightPtr = GEP1;
1177     LocationSize VLeftSize = V2Size;
1178     LocationSize VRightSize = V1Size;
1179     const bool Swapped = Off.isNegative();
1180 
1181     if (Swapped) {
1182       // Swap if we have the situation where:
1183       // +                +
1184       // | BaseOffset     |
1185       // ---------------->|
1186       // |-->V1Size       |-------> V2Size
1187       // GEP1             V2
1188       std::swap(LeftPtr, RightPtr);
1189       std::swap(VLeftSize, VRightSize);
1190       Off = -Off;
1191     }
1192 
1193     if (!VLeftSize.hasValue())
1194       return AliasResult::MayAlias;
1195 
1196     const uint64_t LSize = VLeftSize.getValue();
1197     if (Off.ult(LSize)) {
1198       // Conservatively drop processing if a phi was visited and/or offset is
1199       // too big.
1200       AliasResult AR = AliasResult::PartialAlias;
1201       if (VRightSize.hasValue() && Off.ule(INT32_MAX) &&
1202           (Off + VRightSize.getValue()).ule(LSize)) {
1203         // Memory referenced by right pointer is nested. Save the offset in
1204         // cache. Note that originally offset estimated as GEP1-V2, but
1205         // AliasResult contains the shift that represents GEP1+Offset=V2.
1206         AR.setOffset(-Off.getSExtValue());
1207         AR.swap(Swapped);
1208       }
1209       return AR;
1210     }
1211     return AliasResult::NoAlias;
1212   }
1213 
1214   // We need to know both acess sizes for all the following heuristics.
1215   if (!V1Size.hasValue() || !V2Size.hasValue())
1216     return AliasResult::MayAlias;
1217 
1218   APInt GCD;
1219   ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset);
1220   for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1221     const VariableGEPIndex &Index = DecompGEP1.VarIndices[i];
1222     const APInt &Scale = Index.Scale;
1223     APInt ScaleForGCD = Scale;
1224     if (!Index.IsNSW)
1225       ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(),
1226                                         Scale.countTrailingZeros());
1227 
1228     if (i == 0)
1229       GCD = ScaleForGCD.abs();
1230     else
1231       GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
1232 
1233     ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false,
1234                                             true, &AC, Index.CxtI);
1235     KnownBits Known =
1236         computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT);
1237     CR = CR.intersectWith(
1238         ConstantRange::fromKnownBits(Known, /* Signed */ true),
1239         ConstantRange::Signed);
1240     CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());
1241 
1242     assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
1243            "Bit widths are normalized to MaxIndexSize");
1244     if (Index.IsNSW)
1245       OffsetRange = OffsetRange.add(CR.smul_sat(ConstantRange(Scale)));
1246     else
1247       OffsetRange = OffsetRange.add(CR.smul_fast(ConstantRange(Scale)));
1248   }
1249 
1250   // We now have accesses at two offsets from the same base:
1251   //  1. (...)*GCD + DecompGEP1.Offset with size V1Size
1252   //  2. 0 with size V2Size
1253   // Using arithmetic modulo GCD, the accesses are at
1254   // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1255   // into the range [V2Size..GCD), then we know they cannot overlap.
1256   APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1257   if (ModOffset.isNegative())
1258     ModOffset += GCD; // We want mod, not rem.
1259   if (ModOffset.uge(V2Size.getValue()) &&
1260       (GCD - ModOffset).uge(V1Size.getValue()))
1261     return AliasResult::NoAlias;
1262 
1263   // Compute ranges of potentially accessed bytes for both accesses. If the
1264   // interseciton is empty, there can be no overlap.
1265   unsigned BW = OffsetRange.getBitWidth();
1266   ConstantRange Range1 = OffsetRange.add(
1267       ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1268   ConstantRange Range2 =
1269       ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1270   if (Range1.intersectWith(Range2).isEmptySet())
1271     return AliasResult::NoAlias;
1272 
1273   // Try to determine the range of values for VarIndex such that
1274   // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex.
1275   Optional<APInt> MinAbsVarIndex;
1276   if (DecompGEP1.VarIndices.size() == 1) {
1277     // VarIndex = Scale*V.
1278     const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];
1279     if (Var.Val.TruncBits == 0 &&
1280         isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) {
1281       // If V != 0, then abs(VarIndex) > 0.
1282       MinAbsVarIndex = APInt(Var.Scale.getBitWidth(), 1);
1283 
1284       // Check if abs(V*Scale) >= abs(Scale) holds in the presence of
1285       // potentially wrapping math.
1286       auto MultiplyByScaleNoWrap = [](const VariableGEPIndex &Var) {
1287         if (Var.IsNSW)
1288           return true;
1289 
1290         int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits();
1291         // If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds.
1292         // The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a
1293         // constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap.
1294         int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW;
1295         if (MaxScaleValueBW <= 0)
1296           return false;
1297         return Var.Scale.ule(
1298             APInt::getMaxValue(MaxScaleValueBW).zext(Var.Scale.getBitWidth()));
1299       };
1300       // Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the
1301       // presence of potentially wrapping math.
1302       if (MultiplyByScaleNoWrap(Var)) {
1303         // If V != 0 then abs(VarIndex) >= abs(Scale).
1304         MinAbsVarIndex = Var.Scale.abs();
1305       }
1306     }
1307   } else if (DecompGEP1.VarIndices.size() == 2) {
1308     // VarIndex = Scale*V0 + (-Scale)*V1.
1309     // If V0 != V1 then abs(VarIndex) >= abs(Scale).
1310     // Check that VisitedPhiBBs is empty, to avoid reasoning about
1311     // inequality of values across loop iterations.
1312     const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];
1313     const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];
1314     if (Var0.Scale == -Var1.Scale && Var0.Val.TruncBits == 0 &&
1315         Var0.Val.hasSameCastsAs(Var1.Val) && VisitedPhiBBs.empty() &&
1316         isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr,
1317                         DT))
1318       MinAbsVarIndex = Var0.Scale.abs();
1319   }
1320 
1321   if (MinAbsVarIndex) {
1322     // The constant offset will have added at least +/-MinAbsVarIndex to it.
1323     APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1324     APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1325     // We know that Offset <= OffsetLo || Offset >= OffsetHi
1326     if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1327         OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1328       return AliasResult::NoAlias;
1329   }
1330 
1331   if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT))
1332     return AliasResult::NoAlias;
1333 
1334   // Statically, we can see that the base objects are the same, but the
1335   // pointers have dynamic offsets which we can't resolve. And none of our
1336   // little tricks above worked.
1337   return AliasResult::MayAlias;
1338 }
1339 
1340 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1341   // If the results agree, take it.
1342   if (A == B)
1343     return A;
1344   // A mix of PartialAlias and MustAlias is PartialAlias.
1345   if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||
1346       (B == AliasResult::PartialAlias && A == AliasResult::MustAlias))
1347     return AliasResult::PartialAlias;
1348   // Otherwise, we don't know anything.
1349   return AliasResult::MayAlias;
1350 }
1351 
1352 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1353 /// against another.
1354 AliasResult
1355 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1356                            const Value *V2, LocationSize V2Size,
1357                            AAQueryInfo &AAQI) {
1358   // If the values are Selects with the same condition, we can do a more precise
1359   // check: just check for aliases between the values on corresponding arms.
1360   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1361     if (SI->getCondition() == SI2->getCondition()) {
1362       AliasResult Alias = getBestAAResults().alias(
1363           MemoryLocation(SI->getTrueValue(), SISize),
1364           MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1365       if (Alias == AliasResult::MayAlias)
1366         return AliasResult::MayAlias;
1367       AliasResult ThisAlias = getBestAAResults().alias(
1368           MemoryLocation(SI->getFalseValue(), SISize),
1369           MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
1370       return MergeAliasResults(ThisAlias, Alias);
1371     }
1372 
1373   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1374   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1375   AliasResult Alias =
1376       getBestAAResults().alias(MemoryLocation(SI->getTrueValue(), SISize),
1377                                MemoryLocation(V2, V2Size), AAQI);
1378   if (Alias == AliasResult::MayAlias)
1379     return AliasResult::MayAlias;
1380 
1381   AliasResult ThisAlias =
1382       getBestAAResults().alias(MemoryLocation(SI->getFalseValue(), SISize),
1383                                MemoryLocation(V2, V2Size), AAQI);
1384   return MergeAliasResults(ThisAlias, Alias);
1385 }
1386 
1387 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1388 /// another.
1389 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1390                                     const Value *V2, LocationSize V2Size,
1391                                     AAQueryInfo &AAQI) {
1392   if (!PN->getNumIncomingValues())
1393     return AliasResult::NoAlias;
1394   // If the values are PHIs in the same block, we can do a more precise
1395   // as well as efficient check: just check for aliases between the values
1396   // on corresponding edges.
1397   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1398     if (PN2->getParent() == PN->getParent()) {
1399       Optional<AliasResult> Alias;
1400       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1401         AliasResult ThisAlias = getBestAAResults().alias(
1402             MemoryLocation(PN->getIncomingValue(i), PNSize),
1403             MemoryLocation(
1404                 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1405             AAQI);
1406         if (Alias)
1407           *Alias = MergeAliasResults(*Alias, ThisAlias);
1408         else
1409           Alias = ThisAlias;
1410         if (*Alias == AliasResult::MayAlias)
1411           break;
1412       }
1413       return *Alias;
1414     }
1415 
1416   SmallVector<Value *, 4> V1Srcs;
1417   // If a phi operand recurses back to the phi, we can still determine NoAlias
1418   // if we don't alias the underlying objects of the other phi operands, as we
1419   // know that the recursive phi needs to be based on them in some way.
1420   bool isRecursive = false;
1421   auto CheckForRecPhi = [&](Value *PV) {
1422     if (!EnableRecPhiAnalysis)
1423       return false;
1424     if (getUnderlyingObject(PV) == PN) {
1425       isRecursive = true;
1426       return true;
1427     }
1428     return false;
1429   };
1430 
1431   if (PV) {
1432     // If we have PhiValues then use it to get the underlying phi values.
1433     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
1434     // If we have more phi values than the search depth then return MayAlias
1435     // conservatively to avoid compile time explosion. The worst possible case
1436     // is if both sides are PHI nodes. In which case, this is O(m x n) time
1437     // where 'm' and 'n' are the number of PHI sources.
1438     if (PhiValueSet.size() > MaxLookupSearchDepth)
1439       return AliasResult::MayAlias;
1440     // Add the values to V1Srcs
1441     for (Value *PV1 : PhiValueSet) {
1442       if (CheckForRecPhi(PV1))
1443         continue;
1444       V1Srcs.push_back(PV1);
1445     }
1446   } else {
1447     // If we don't have PhiInfo then just look at the operands of the phi itself
1448     // FIXME: Remove this once we can guarantee that we have PhiInfo always
1449     SmallPtrSet<Value *, 4> UniqueSrc;
1450     Value *OnePhi = nullptr;
1451     for (Value *PV1 : PN->incoming_values()) {
1452       if (isa<PHINode>(PV1)) {
1453         if (OnePhi && OnePhi != PV1) {
1454           // To control potential compile time explosion, we choose to be
1455           // conserviate when we have more than one Phi input.  It is important
1456           // that we handle the single phi case as that lets us handle LCSSA
1457           // phi nodes and (combined with the recursive phi handling) simple
1458           // pointer induction variable patterns.
1459           return AliasResult::MayAlias;
1460         }
1461         OnePhi = PV1;
1462       }
1463 
1464       if (CheckForRecPhi(PV1))
1465         continue;
1466 
1467       if (UniqueSrc.insert(PV1).second)
1468         V1Srcs.push_back(PV1);
1469     }
1470 
1471     if (OnePhi && UniqueSrc.size() > 1)
1472       // Out of an abundance of caution, allow only the trivial lcssa and
1473       // recursive phi cases.
1474       return AliasResult::MayAlias;
1475   }
1476 
1477   // If V1Srcs is empty then that means that the phi has no underlying non-phi
1478   // value. This should only be possible in blocks unreachable from the entry
1479   // block, but return MayAlias just in case.
1480   if (V1Srcs.empty())
1481     return AliasResult::MayAlias;
1482 
1483   // If this PHI node is recursive, indicate that the pointer may be moved
1484   // across iterations. We can only prove NoAlias if different underlying
1485   // objects are involved.
1486   if (isRecursive)
1487     PNSize = LocationSize::beforeOrAfterPointer();
1488 
1489   // In the recursive alias queries below, we may compare values from two
1490   // different loop iterations. Keep track of visited phi blocks, which will
1491   // be used when determining value equivalence.
1492   bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second;
1493   auto _ = make_scope_exit([&]() {
1494     if (BlockInserted)
1495       VisitedPhiBBs.erase(PN->getParent());
1496   });
1497 
1498   // If we inserted a block into VisitedPhiBBs, alias analysis results that
1499   // have been cached earlier may no longer be valid. Perform recursive queries
1500   // with a new AAQueryInfo.
1501   AAQueryInfo NewAAQI = AAQI.withEmptyCache();
1502   AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI;
1503 
1504   AliasResult Alias = getBestAAResults().alias(
1505       MemoryLocation(V1Srcs[0], PNSize), MemoryLocation(V2, V2Size), *UseAAQI);
1506 
1507   // Early exit if the check of the first PHI source against V2 is MayAlias.
1508   // Other results are not possible.
1509   if (Alias == AliasResult::MayAlias)
1510     return AliasResult::MayAlias;
1511   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1512   // remain valid to all elements and needs to conservatively return MayAlias.
1513   if (isRecursive && Alias != AliasResult::NoAlias)
1514     return AliasResult::MayAlias;
1515 
1516   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1517   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1518   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1519     Value *V = V1Srcs[i];
1520 
1521     AliasResult ThisAlias = getBestAAResults().alias(
1522         MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), *UseAAQI);
1523     Alias = MergeAliasResults(ThisAlias, Alias);
1524     if (Alias == AliasResult::MayAlias)
1525       break;
1526   }
1527 
1528   return Alias;
1529 }
1530 
1531 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1532 /// array references.
1533 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1534                                       const Value *V2, LocationSize V2Size,
1535                                       AAQueryInfo &AAQI) {
1536   // If either of the memory references is empty, it doesn't matter what the
1537   // pointer values are.
1538   if (V1Size.isZero() || V2Size.isZero())
1539     return AliasResult::NoAlias;
1540 
1541   // Strip off any casts if they exist.
1542   V1 = V1->stripPointerCastsForAliasAnalysis();
1543   V2 = V2->stripPointerCastsForAliasAnalysis();
1544 
1545   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1546   // value for undef that aliases nothing in the program.
1547   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1548     return AliasResult::NoAlias;
1549 
1550   // Are we checking for alias of the same value?
1551   // Because we look 'through' phi nodes, we could look at "Value" pointers from
1552   // different iterations. We must therefore make sure that this is not the
1553   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1554   // happen by looking at the visited phi nodes and making sure they cannot
1555   // reach the value.
1556   if (isValueEqualInPotentialCycles(V1, V2))
1557     return AliasResult::MustAlias;
1558 
1559   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1560     return AliasResult::NoAlias; // Scalars cannot alias each other
1561 
1562   // Figure out what objects these things are pointing to if we can.
1563   const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1564   const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
1565 
1566   // Null values in the default address space don't point to any object, so they
1567   // don't alias any other pointer.
1568   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1569     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1570       return AliasResult::NoAlias;
1571   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1572     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1573       return AliasResult::NoAlias;
1574 
1575   if (O1 != O2) {
1576     // If V1/V2 point to two different objects, we know that we have no alias.
1577     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1578       return AliasResult::NoAlias;
1579 
1580     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1581     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1582         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1583       return AliasResult::NoAlias;
1584 
1585     // Function arguments can't alias with things that are known to be
1586     // unambigously identified at the function level.
1587     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1588         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1589       return AliasResult::NoAlias;
1590 
1591     // If one pointer is the result of a call/invoke or load and the other is a
1592     // non-escaping local object within the same function, then we know the
1593     // object couldn't escape to a point where the call could return it.
1594     //
1595     // Note that if the pointers are in different functions, there are a
1596     // variety of complications. A call with a nocapture argument may still
1597     // temporary store the nocapture argument's value in a temporary memory
1598     // location if that memory location doesn't escape. Or it may pass a
1599     // nocapture value to other functions as long as they don't capture it.
1600     if (isEscapeSource(O1) &&
1601         AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1)))
1602       return AliasResult::NoAlias;
1603     if (isEscapeSource(O2) &&
1604         AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2)))
1605       return AliasResult::NoAlias;
1606   }
1607 
1608   // If the size of one access is larger than the entire object on the other
1609   // side, then we know such behavior is undefined and can assume no alias.
1610   bool NullIsValidLocation = NullPointerIsDefined(&F);
1611   if ((isObjectSmallerThan(
1612           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
1613           TLI, NullIsValidLocation)) ||
1614       (isObjectSmallerThan(
1615           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
1616           TLI, NullIsValidLocation)))
1617     return AliasResult::NoAlias;
1618 
1619   // If one the accesses may be before the accessed pointer, canonicalize this
1620   // by using unknown after-pointer sizes for both accesses. This is
1621   // equivalent, because regardless of which pointer is lower, one of them
1622   // will always came after the other, as long as the underlying objects aren't
1623   // disjoint. We do this so that the rest of BasicAA does not have to deal
1624   // with accesses before the base pointer, and to improve cache utilization by
1625   // merging equivalent states.
1626   if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1627     V1Size = LocationSize::afterPointer();
1628     V2Size = LocationSize::afterPointer();
1629   }
1630 
1631   // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1632   // for recursive queries. For this reason, this limit is chosen to be large
1633   // enough to be very rarely hit, while still being small enough to avoid
1634   // stack overflows.
1635   if (AAQI.Depth >= 512)
1636     return AliasResult::MayAlias;
1637 
1638   // Check the cache before climbing up use-def chains. This also terminates
1639   // otherwise infinitely recursive queries.
1640   AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size});
1641   const bool Swapped = V1 > V2;
1642   if (Swapped)
1643     std::swap(Locs.first, Locs.second);
1644   const auto &Pair = AAQI.AliasCache.try_emplace(
1645       Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});
1646   if (!Pair.second) {
1647     auto &Entry = Pair.first->second;
1648     if (!Entry.isDefinitive()) {
1649       // Remember that we used an assumption.
1650       ++Entry.NumAssumptionUses;
1651       ++AAQI.NumAssumptionUses;
1652     }
1653     // Cache contains sorted {V1,V2} pairs but we should return original order.
1654     auto Result = Entry.Result;
1655     Result.swap(Swapped);
1656     return Result;
1657   }
1658 
1659   int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1660   unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1661   AliasResult Result =
1662       aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1663 
1664   auto It = AAQI.AliasCache.find(Locs);
1665   assert(It != AAQI.AliasCache.end() && "Must be in cache");
1666   auto &Entry = It->second;
1667 
1668   // Check whether a NoAlias assumption has been used, but disproven.
1669   bool AssumptionDisproven =
1670       Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1671   if (AssumptionDisproven)
1672     Result = AliasResult::MayAlias;
1673 
1674   // This is a definitive result now, when considered as a root query.
1675   AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1676   Entry.Result = Result;
1677   // Cache contains sorted {V1,V2} pairs.
1678   Entry.Result.swap(Swapped);
1679   Entry.NumAssumptionUses = -1;
1680 
1681   // If the assumption has been disproven, remove any results that may have
1682   // been based on this assumption. Do this after the Entry updates above to
1683   // avoid iterator invalidation.
1684   if (AssumptionDisproven)
1685     while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1686       AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());
1687 
1688   // The result may still be based on assumptions higher up in the chain.
1689   // Remember it, so it can be purged from the cache later.
1690   if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1691       Result != AliasResult::MayAlias)
1692     AAQI.AssumptionBasedResults.push_back(Locs);
1693   return Result;
1694 }
1695 
1696 AliasResult BasicAAResult::aliasCheckRecursive(
1697     const Value *V1, LocationSize V1Size,
1698     const Value *V2, LocationSize V2Size,
1699     AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
1700   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1701     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1702     if (Result != AliasResult::MayAlias)
1703       return Result;
1704   } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1705     AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
1706     Result.swap();
1707     if (Result != AliasResult::MayAlias)
1708       return Result;
1709   }
1710 
1711   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1712     AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1713     if (Result != AliasResult::MayAlias)
1714       return Result;
1715   } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1716     AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
1717     Result.swap();
1718     if (Result != AliasResult::MayAlias)
1719       return Result;
1720   }
1721 
1722   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1723     AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1724     if (Result != AliasResult::MayAlias)
1725       return Result;
1726   } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1727     AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);
1728     Result.swap();
1729     if (Result != AliasResult::MayAlias)
1730       return Result;
1731   }
1732 
1733   // If both pointers are pointing into the same object and one of them
1734   // accesses the entire object, then the accesses must overlap in some way.
1735   if (O1 == O2) {
1736     bool NullIsValidLocation = NullPointerIsDefined(&F);
1737     if (V1Size.isPrecise() && V2Size.isPrecise() &&
1738         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1739          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1740       return AliasResult::PartialAlias;
1741   }
1742 
1743   return AliasResult::MayAlias;
1744 }
1745 
1746 /// Check whether two Values can be considered equivalent.
1747 ///
1748 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1749 /// they can not be part of a cycle in the value graph by looking at all
1750 /// visited phi nodes an making sure that the phis cannot reach the value. We
1751 /// have to do this because we are looking through phi nodes (That is we say
1752 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1753 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1754                                                   const Value *V2) {
1755   if (V != V2)
1756     return false;
1757 
1758   const Instruction *Inst = dyn_cast<Instruction>(V);
1759   if (!Inst)
1760     return true;
1761 
1762   if (VisitedPhiBBs.empty())
1763     return true;
1764 
1765   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1766     return false;
1767 
1768   // Make sure that the visited phis cannot reach the Value. This ensures that
1769   // the Values cannot come from different iterations of a potential cycle the
1770   // phi nodes could be involved in.
1771   for (const auto *P : VisitedPhiBBs)
1772     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT))
1773       return false;
1774 
1775   return true;
1776 }
1777 
1778 /// Computes the symbolic difference between two de-composed GEPs.
1779 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1780                                            const DecomposedGEP &SrcGEP) {
1781   DestGEP.Offset -= SrcGEP.Offset;
1782   for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
1783     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1784     // than a few variable indexes.
1785     bool Found = false;
1786     for (auto I : enumerate(DestGEP.VarIndices)) {
1787       VariableGEPIndex &Dest = I.value();
1788       if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) ||
1789           !Dest.Val.hasSameCastsAs(Src.Val))
1790         continue;
1791 
1792       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1793       // goes to zero, remove the entry.
1794       if (Dest.Scale != Src.Scale) {
1795         Dest.Scale -= Src.Scale;
1796         Dest.IsNSW = false;
1797       } else {
1798         DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());
1799       }
1800       Found = true;
1801       break;
1802     }
1803 
1804     // If we didn't consume this entry, add it to the end of the Dest list.
1805     if (!Found) {
1806       VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW};
1807       DestGEP.VarIndices.push_back(Entry);
1808     }
1809   }
1810 }
1811 
1812 bool BasicAAResult::constantOffsetHeuristic(
1813     const DecomposedGEP &GEP, LocationSize MaybeV1Size,
1814     LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) {
1815   if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
1816       !MaybeV2Size.hasValue())
1817     return false;
1818 
1819   const uint64_t V1Size = MaybeV1Size.getValue();
1820   const uint64_t V2Size = MaybeV2Size.getValue();
1821 
1822   const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
1823 
1824   if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||
1825       Var0.Scale != -Var1.Scale ||
1826       Var0.Val.V->getType() != Var1.Val.V->getType())
1827     return false;
1828 
1829   // We'll strip off the Extensions of Var0 and Var1 and do another round
1830   // of GetLinearExpression decomposition. In the example above, if Var0
1831   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1832 
1833   LinearExpression E0 =
1834       GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);
1835   LinearExpression E1 =
1836       GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
1837   if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
1838       !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V))
1839     return false;
1840 
1841   // We have a hit - Var0 and Var1 only differ by a constant offset!
1842 
1843   // If we've been sext'ed then zext'd the maximum difference between Var0 and
1844   // Var1 is possible to calculate, but we're just interested in the absolute
1845   // minimum difference between the two. The minimum distance may occur due to
1846   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1847   // the minimum distance between %i and %i + 5 is 3.
1848   APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
1849   MinDiff = APIntOps::umin(MinDiff, Wrapped);
1850   APInt MinDiffBytes =
1851     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
1852 
1853   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1854   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1855   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1856   // V2Size can fit in the MinDiffBytes gap.
1857   return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&
1858          MinDiffBytes.uge(V2Size + GEP.Offset.abs());
1859 }
1860 
1861 //===----------------------------------------------------------------------===//
1862 // BasicAliasAnalysis Pass
1863 //===----------------------------------------------------------------------===//
1864 
1865 AnalysisKey BasicAA::Key;
1866 
1867 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1868   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1869   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1870   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1871   auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F);
1872   return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV);
1873 }
1874 
1875 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
1876   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
1877 }
1878 
1879 char BasicAAWrapperPass::ID = 0;
1880 
1881 void BasicAAWrapperPass::anchor() {}
1882 
1883 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
1884                       "Basic Alias Analysis (stateless AA impl)", true, true)
1885 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1886 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1887 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1888 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
1889 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
1890                     "Basic Alias Analysis (stateless AA impl)", true, true)
1891 
1892 FunctionPass *llvm::createBasicAAWrapperPass() {
1893   return new BasicAAWrapperPass();
1894 }
1895 
1896 bool BasicAAWrapperPass::runOnFunction(Function &F) {
1897   auto &ACT = getAnalysis<AssumptionCacheTracker>();
1898   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
1899   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
1900   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
1901 
1902   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
1903                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
1904                                  &DTWP.getDomTree(),
1905                                  PVWP ? &PVWP->getResult() : nullptr));
1906 
1907   return false;
1908 }
1909 
1910 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1911   AU.setPreservesAll();
1912   AU.addRequiredTransitive<AssumptionCacheTracker>();
1913   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1914   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1915   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
1916 }
1917 
1918 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
1919   return BasicAAResult(
1920       F.getParent()->getDataLayout(), F,
1921       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
1922       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
1923 }
1924