10b57cec5SDimitry Andric //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the primary stateless implementation of the
100b57cec5SDimitry Andric // Alias Analysis interface that implements identities (two different
110b57cec5SDimitry Andric // globals cannot alias, etc), but does no stateful analysis.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
17e8d8bef9SDimitry Andric #include "llvm/ADT/ScopeExit.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
28480093f4SDimitry Andric #include "llvm/Analysis/PhiValues.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
310b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
320b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
34349cc55cSDimitry Andric #include "llvm/IR/ConstantRange.h"
350b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
360b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
370b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
390b57cec5SDimitry Andric #include "llvm/IR/Function.h"
400b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
410b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
430b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
450b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
460b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
470b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
480b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
490b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
500b57cec5SDimitry Andric #include "llvm/IR/Type.h"
510b57cec5SDimitry Andric #include "llvm/IR/User.h"
520b57cec5SDimitry Andric #include "llvm/IR/Value.h"
53480093f4SDimitry Andric #include "llvm/InitializePasses.h"
540b57cec5SDimitry Andric #include "llvm/Pass.h"
550b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
560b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
570b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
580b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
590b57cec5SDimitry Andric #include <cassert>
600b57cec5SDimitry Andric #include <cstdint>
610b57cec5SDimitry Andric #include <cstdlib>
620b57cec5SDimitry Andric #include <utility>
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric #define DEBUG_TYPE "basicaa"
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric /// Enable analysis of recursive PHI nodes.
695ffd83dbSDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
70e8d8bef9SDimitry Andric                                           cl::init(true));
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of
730b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision
740b57cec5SDimitry Andric /// of basic alias analysis.
750b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to "
760b57cec5SDimitry Andric                               "decompose GEPs is reached");
770b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric /// Cutoff after which to stop analysing a set of phi nodes potentially involved
800b57cec5SDimitry Andric /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
810b57cec5SDimitry Andric /// careful with value equivalence. We use reachability to make sure a value
820b57cec5SDimitry Andric /// cannot be involved in a cycle.
830b57cec5SDimitry Andric const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and
86349cc55cSDimitry Andric // getUnderlyingObject().
870b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6;
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
900b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
910b57cec5SDimitry Andric   // We don't care if this analysis itself is preserved, it has no state. But
920b57cec5SDimitry Andric   // we need to check that the analyses it depends on have been. Note that we
930b57cec5SDimitry Andric   // may be created without handles to some analyses and in that case don't
940b57cec5SDimitry Andric   // depend on them.
950b57cec5SDimitry Andric   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
960b57cec5SDimitry Andric       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
970b57cec5SDimitry Andric       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
980b57cec5SDimitry Andric     return true;
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   // Otherwise this analysis result remains valid.
1010b57cec5SDimitry Andric   return false;
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1050b57cec5SDimitry Andric // Useful predicates
1060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric /// Returns true if the pointer is one which would have been considered an
1090b57cec5SDimitry Andric /// escape by isNonEscapingLocalObject.
1100b57cec5SDimitry Andric static bool isEscapeSource(const Value *V) {
1110b57cec5SDimitry Andric   if (isa<CallBase>(V))
1120b57cec5SDimitry Andric     return true;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // The load case works because isNonEscapingLocalObject considers all
1150b57cec5SDimitry Andric   // stores to be escapes (it passes true for the StoreCaptures argument
1160b57cec5SDimitry Andric   // to PointerMayBeCaptured).
1170b57cec5SDimitry Andric   if (isa<LoadInst>(V))
1180b57cec5SDimitry Andric     return true;
1190b57cec5SDimitry Andric 
120fe6060f1SDimitry Andric   // The inttoptr case works because isNonEscapingLocalObject considers all
121fe6060f1SDimitry Andric   // means of converting or equating a pointer to an int (ptrtoint, ptr store
122fe6060f1SDimitry Andric   // which could be followed by an integer load, ptr<->int compare) as
123fe6060f1SDimitry Andric   // escaping, and objects located at well-known addresses via platform-specific
124fe6060f1SDimitry Andric   // means cannot be considered non-escaping local objects.
125fe6060f1SDimitry Andric   if (isa<IntToPtrInst>(V))
126fe6060f1SDimitry Andric     return true;
127fe6060f1SDimitry Andric 
1280b57cec5SDimitry Andric   return false;
1290b57cec5SDimitry Andric }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown.
1320b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
1330b57cec5SDimitry Andric                               const TargetLibraryInfo &TLI,
1340b57cec5SDimitry Andric                               bool NullIsValidLoc,
1350b57cec5SDimitry Andric                               bool RoundToAlign = false) {
1360b57cec5SDimitry Andric   uint64_t Size;
1370b57cec5SDimitry Andric   ObjectSizeOpts Opts;
1380b57cec5SDimitry Andric   Opts.RoundToAlign = RoundToAlign;
1390b57cec5SDimitry Andric   Opts.NullIsUnknownSize = NullIsValidLoc;
1400b57cec5SDimitry Andric   if (getObjectSize(V, Size, DL, &TLI, Opts))
1410b57cec5SDimitry Andric     return Size;
1420b57cec5SDimitry Andric   return MemoryLocation::UnknownSize;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than
1460b57cec5SDimitry Andric /// Size.
1470b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size,
1480b57cec5SDimitry Andric                                 const DataLayout &DL,
1490b57cec5SDimitry Andric                                 const TargetLibraryInfo &TLI,
1500b57cec5SDimitry Andric                                 bool NullIsValidLoc) {
1510b57cec5SDimitry Andric   // Note that the meanings of the "object" are slightly different in the
1520b57cec5SDimitry Andric   // following contexts:
1530b57cec5SDimitry Andric   //    c1: llvm::getObjectSize()
1540b57cec5SDimitry Andric   //    c2: llvm.objectsize() intrinsic
1550b57cec5SDimitry Andric   //    c3: isObjectSmallerThan()
1560b57cec5SDimitry Andric   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
1570b57cec5SDimitry Andric   // refers to the "entire object".
1580b57cec5SDimitry Andric   //
1590b57cec5SDimitry Andric   //  Consider this example:
1600b57cec5SDimitry Andric   //     char *p = (char*)malloc(100)
1610b57cec5SDimitry Andric   //     char *q = p+80;
1620b57cec5SDimitry Andric   //
1630b57cec5SDimitry Andric   //  In the context of c1 and c2, the "object" pointed by q refers to the
1640b57cec5SDimitry Andric   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
1650b57cec5SDimitry Andric   //
1660b57cec5SDimitry Andric   //  However, in the context of c3, the "object" refers to the chunk of memory
1670b57cec5SDimitry Andric   // being allocated. So, the "object" has 100 bytes, and q points to the middle
1680b57cec5SDimitry Andric   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
1690b57cec5SDimitry Andric   // parameter, before the llvm::getObjectSize() is called to get the size of
1700b57cec5SDimitry Andric   // entire object, we should:
1710b57cec5SDimitry Andric   //    - either rewind the pointer q to the base-address of the object in
1720b57cec5SDimitry Andric   //      question (in this case rewind to p), or
1730b57cec5SDimitry Andric   //    - just give up. It is up to caller to make sure the pointer is pointing
1740b57cec5SDimitry Andric   //      to the base address the object.
1750b57cec5SDimitry Andric   //
1760b57cec5SDimitry Andric   // We go for 2nd option for simplicity.
1770b57cec5SDimitry Andric   if (!isIdentifiedObject(V))
1780b57cec5SDimitry Andric     return false;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // This function needs to use the aligned object size because we allow
1810b57cec5SDimitry Andric   // reads a bit past the end given sufficient alignment.
1820b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
1830b57cec5SDimitry Andric                                       /*RoundToAlign*/ true);
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1888bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object,
1898bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query
1908bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here.
1918bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V,
1928bcb0991SDimitry Andric                                      const LocationSize &LocSize,
1938bcb0991SDimitry Andric                                      const DataLayout &DL,
1948bcb0991SDimitry Andric                                      bool NullIsValidLoc) {
1958bcb0991SDimitry Andric   // If we have dereferenceability information we know a lower bound for the
1968bcb0991SDimitry Andric   // extent as accesses for a lower offset would be valid. We need to exclude
197349cc55cSDimitry Andric   // the "or null" part if null is a valid pointer. We can ignore frees, as an
198349cc55cSDimitry Andric   // access after free would be undefined behavior.
199fe6060f1SDimitry Andric   bool CanBeNull, CanBeFreed;
200fe6060f1SDimitry Andric   uint64_t DerefBytes =
201fe6060f1SDimitry Andric     V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
2028bcb0991SDimitry Andric   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
2038bcb0991SDimitry Andric   // If queried with a precise location size, we assume that location size to be
2048bcb0991SDimitry Andric   // accessed, thus valid.
2058bcb0991SDimitry Andric   if (LocSize.isPrecise())
2068bcb0991SDimitry Andric     DerefBytes = std::max(DerefBytes, LocSize.getValue());
2078bcb0991SDimitry Andric   return DerefBytes;
2088bcb0991SDimitry Andric }
2098bcb0991SDimitry Andric 
2100b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size.
2110b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
2120b57cec5SDimitry Andric                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
2130b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
2140b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
218349cc55cSDimitry Andric // CaptureInfo implementations
219349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
220349cc55cSDimitry Andric 
221349cc55cSDimitry Andric CaptureInfo::~CaptureInfo() = default;
222349cc55cSDimitry Andric 
223349cc55cSDimitry Andric bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object,
224349cc55cSDimitry Andric                                                 const Instruction *I) {
225349cc55cSDimitry Andric   return isNonEscapingLocalObject(Object, &IsCapturedCache);
226349cc55cSDimitry Andric }
227349cc55cSDimitry Andric 
228349cc55cSDimitry Andric bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object,
229349cc55cSDimitry Andric                                                  const Instruction *I) {
230349cc55cSDimitry Andric   if (!isIdentifiedFunctionLocal(Object))
231349cc55cSDimitry Andric     return false;
232349cc55cSDimitry Andric 
233349cc55cSDimitry Andric   auto Iter = EarliestEscapes.insert({Object, nullptr});
234349cc55cSDimitry Andric   if (Iter.second) {
235349cc55cSDimitry Andric     Instruction *EarliestCapture = FindEarliestCapture(
236349cc55cSDimitry Andric         Object, *const_cast<Function *>(I->getFunction()),
237349cc55cSDimitry Andric         /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT);
238349cc55cSDimitry Andric     if (EarliestCapture) {
239349cc55cSDimitry Andric       auto Ins = Inst2Obj.insert({EarliestCapture, {}});
240349cc55cSDimitry Andric       Ins.first->second.push_back(Object);
241349cc55cSDimitry Andric     }
242349cc55cSDimitry Andric     Iter.first->second = EarliestCapture;
243349cc55cSDimitry Andric   }
244349cc55cSDimitry Andric 
245349cc55cSDimitry Andric   // No capturing instruction.
246349cc55cSDimitry Andric   if (!Iter.first->second)
247349cc55cSDimitry Andric     return true;
248349cc55cSDimitry Andric 
249349cc55cSDimitry Andric   return I != Iter.first->second &&
250349cc55cSDimitry Andric          !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI);
251349cc55cSDimitry Andric }
252349cc55cSDimitry Andric 
253349cc55cSDimitry Andric void EarliestEscapeInfo::removeInstruction(Instruction *I) {
254349cc55cSDimitry Andric   auto Iter = Inst2Obj.find(I);
255349cc55cSDimitry Andric   if (Iter != Inst2Obj.end()) {
256349cc55cSDimitry Andric     for (const Value *Obj : Iter->second)
257349cc55cSDimitry Andric       EarliestEscapes.erase(Obj);
258349cc55cSDimitry Andric     Inst2Obj.erase(I);
259349cc55cSDimitry Andric   }
260349cc55cSDimitry Andric }
261349cc55cSDimitry Andric 
262349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
2630b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis
2640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2650b57cec5SDimitry Andric 
266fe6060f1SDimitry Andric namespace {
267349cc55cSDimitry Andric /// Represents zext(sext(trunc(V))).
268349cc55cSDimitry Andric struct CastedValue {
269fe6060f1SDimitry Andric   const Value *V;
270349cc55cSDimitry Andric   unsigned ZExtBits = 0;
271349cc55cSDimitry Andric   unsigned SExtBits = 0;
272349cc55cSDimitry Andric   unsigned TruncBits = 0;
273fe6060f1SDimitry Andric 
274349cc55cSDimitry Andric   explicit CastedValue(const Value *V) : V(V) {}
275349cc55cSDimitry Andric   explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
276349cc55cSDimitry Andric                        unsigned TruncBits)
277349cc55cSDimitry Andric       : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits) {}
278fe6060f1SDimitry Andric 
279fe6060f1SDimitry Andric   unsigned getBitWidth() const {
280349cc55cSDimitry Andric     return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
281349cc55cSDimitry Andric            SExtBits;
282fe6060f1SDimitry Andric   }
283fe6060f1SDimitry Andric 
284349cc55cSDimitry Andric   CastedValue withValue(const Value *NewV) const {
285349cc55cSDimitry Andric     return CastedValue(NewV, ZExtBits, SExtBits, TruncBits);
286fe6060f1SDimitry Andric   }
287fe6060f1SDimitry Andric 
288349cc55cSDimitry Andric   /// Replace V with zext(NewV)
289349cc55cSDimitry Andric   CastedValue withZExtOfValue(const Value *NewV) const {
290fe6060f1SDimitry Andric     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
291fe6060f1SDimitry Andric                         NewV->getType()->getPrimitiveSizeInBits();
292349cc55cSDimitry Andric     if (ExtendBy <= TruncBits)
293349cc55cSDimitry Andric       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
294349cc55cSDimitry Andric 
295fe6060f1SDimitry Andric     // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
296349cc55cSDimitry Andric     ExtendBy -= TruncBits;
297349cc55cSDimitry Andric     return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0);
298fe6060f1SDimitry Andric   }
299fe6060f1SDimitry Andric 
300349cc55cSDimitry Andric   /// Replace V with sext(NewV)
301349cc55cSDimitry Andric   CastedValue withSExtOfValue(const Value *NewV) const {
302fe6060f1SDimitry Andric     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
303fe6060f1SDimitry Andric                         NewV->getType()->getPrimitiveSizeInBits();
304349cc55cSDimitry Andric     if (ExtendBy <= TruncBits)
305349cc55cSDimitry Andric       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
306349cc55cSDimitry Andric 
307fe6060f1SDimitry Andric     // zext(sext(sext(NewV)))
308349cc55cSDimitry Andric     ExtendBy -= TruncBits;
309349cc55cSDimitry Andric     return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0);
310fe6060f1SDimitry Andric   }
311fe6060f1SDimitry Andric 
312fe6060f1SDimitry Andric   APInt evaluateWith(APInt N) const {
313fe6060f1SDimitry Andric     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
314fe6060f1SDimitry Andric            "Incompatible bit width");
315349cc55cSDimitry Andric     if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);
316fe6060f1SDimitry Andric     if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
317fe6060f1SDimitry Andric     if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);
318fe6060f1SDimitry Andric     return N;
319fe6060f1SDimitry Andric   }
320fe6060f1SDimitry Andric 
321349cc55cSDimitry Andric   ConstantRange evaluateWith(ConstantRange N) const {
322349cc55cSDimitry Andric     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
323349cc55cSDimitry Andric            "Incompatible bit width");
324349cc55cSDimitry Andric     if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);
325349cc55cSDimitry Andric     if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
326349cc55cSDimitry Andric     if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);
327349cc55cSDimitry Andric     return N;
328349cc55cSDimitry Andric   }
329349cc55cSDimitry Andric 
330fe6060f1SDimitry Andric   bool canDistributeOver(bool NUW, bool NSW) const {
331fe6060f1SDimitry Andric     // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
332fe6060f1SDimitry Andric     // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
333349cc55cSDimitry Andric     // trunc(x op y) == trunc(x) op trunc(y)
334fe6060f1SDimitry Andric     return (!ZExtBits || NUW) && (!SExtBits || NSW);
335fe6060f1SDimitry Andric   }
336349cc55cSDimitry Andric 
337349cc55cSDimitry Andric   bool hasSameCastsAs(const CastedValue &Other) const {
338349cc55cSDimitry Andric     return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
339349cc55cSDimitry Andric            TruncBits == Other.TruncBits;
340349cc55cSDimitry Andric   }
341fe6060f1SDimitry Andric };
342fe6060f1SDimitry Andric 
343349cc55cSDimitry Andric /// Represents zext(sext(trunc(V))) * Scale + Offset.
344fe6060f1SDimitry Andric struct LinearExpression {
345349cc55cSDimitry Andric   CastedValue Val;
346fe6060f1SDimitry Andric   APInt Scale;
347fe6060f1SDimitry Andric   APInt Offset;
348fe6060f1SDimitry Andric 
349fe6060f1SDimitry Andric   /// True if all operations in this expression are NSW.
350fe6060f1SDimitry Andric   bool IsNSW;
351fe6060f1SDimitry Andric 
352349cc55cSDimitry Andric   LinearExpression(const CastedValue &Val, const APInt &Scale,
353fe6060f1SDimitry Andric                    const APInt &Offset, bool IsNSW)
354fe6060f1SDimitry Andric       : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {}
355fe6060f1SDimitry Andric 
356349cc55cSDimitry Andric   LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) {
357fe6060f1SDimitry Andric     unsigned BitWidth = Val.getBitWidth();
358fe6060f1SDimitry Andric     Scale = APInt(BitWidth, 1);
359fe6060f1SDimitry Andric     Offset = APInt(BitWidth, 0);
360fe6060f1SDimitry Andric   }
361349cc55cSDimitry Andric 
362349cc55cSDimitry Andric   LinearExpression mul(const APInt &Other, bool MulIsNSW) const {
363349cc55cSDimitry Andric     // The check for zero offset is necessary, because generally
364349cc55cSDimitry Andric     // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
365349cc55cSDimitry Andric     bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
366349cc55cSDimitry Andric     return LinearExpression(Val, Scale * Other, Offset * Other, NSW);
367349cc55cSDimitry Andric   }
368fe6060f1SDimitry Andric };
369fe6060f1SDimitry Andric }
370fe6060f1SDimitry Andric 
3710b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and
3720b57cec5SDimitry Andric /// B are constant integers.
373fe6060f1SDimitry Andric static LinearExpression GetLinearExpression(
374349cc55cSDimitry Andric     const CastedValue &Val,  const DataLayout &DL, unsigned Depth,
375fe6060f1SDimitry Andric     AssumptionCache *AC, DominatorTree *DT) {
3760b57cec5SDimitry Andric   // Limit our recursion depth.
377fe6060f1SDimitry Andric   if (Depth == 6)
378fe6060f1SDimitry Andric     return Val;
3790b57cec5SDimitry Andric 
380fe6060f1SDimitry Andric   if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
381fe6060f1SDimitry Andric     return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
382fe6060f1SDimitry Andric                             Val.evaluateWith(Const->getValue()), true);
3830b57cec5SDimitry Andric 
384fe6060f1SDimitry Andric   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
3850b57cec5SDimitry Andric     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
386fe6060f1SDimitry Andric       APInt RHS = Val.evaluateWith(RHSC->getValue());
387fe6060f1SDimitry Andric       // The only non-OBO case we deal with is or, and only limited to the
388fe6060f1SDimitry Andric       // case where it is both nuw and nsw.
389fe6060f1SDimitry Andric       bool NUW = true, NSW = true;
390fe6060f1SDimitry Andric       if (isa<OverflowingBinaryOperator>(BOp)) {
391fe6060f1SDimitry Andric         NUW &= BOp->hasNoUnsignedWrap();
392fe6060f1SDimitry Andric         NSW &= BOp->hasNoSignedWrap();
393fe6060f1SDimitry Andric       }
394fe6060f1SDimitry Andric       if (!Val.canDistributeOver(NUW, NSW))
395fe6060f1SDimitry Andric         return Val;
3960b57cec5SDimitry Andric 
397349cc55cSDimitry Andric       // While we can distribute over trunc, we cannot preserve nowrap flags
398349cc55cSDimitry Andric       // in that case.
399349cc55cSDimitry Andric       if (Val.TruncBits)
400349cc55cSDimitry Andric         NUW = NSW = false;
401349cc55cSDimitry Andric 
402fe6060f1SDimitry Andric       LinearExpression E(Val);
4030b57cec5SDimitry Andric       switch (BOp->getOpcode()) {
4040b57cec5SDimitry Andric       default:
4050b57cec5SDimitry Andric         // We don't understand this instruction, so we can't decompose it any
4060b57cec5SDimitry Andric         // further.
407fe6060f1SDimitry Andric         return Val;
4080b57cec5SDimitry Andric       case Instruction::Or:
4090b57cec5SDimitry Andric         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
4100b57cec5SDimitry Andric         // analyze it.
4110b57cec5SDimitry Andric         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
412fe6060f1SDimitry Andric                                BOp, DT))
413fe6060f1SDimitry Andric           return Val;
4140b57cec5SDimitry Andric 
415fe6060f1SDimitry Andric         LLVM_FALLTHROUGH;
416fe6060f1SDimitry Andric       case Instruction::Add: {
417fe6060f1SDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
418fe6060f1SDimitry Andric                                 Depth + 1, AC, DT);
419fe6060f1SDimitry Andric         E.Offset += RHS;
420fe6060f1SDimitry Andric         E.IsNSW &= NSW;
421fe6060f1SDimitry Andric         break;
422fe6060f1SDimitry Andric       }
423fe6060f1SDimitry Andric       case Instruction::Sub: {
424fe6060f1SDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
425fe6060f1SDimitry Andric                                 Depth + 1, AC, DT);
426fe6060f1SDimitry Andric         E.Offset -= RHS;
427fe6060f1SDimitry Andric         E.IsNSW &= NSW;
428fe6060f1SDimitry Andric         break;
429fe6060f1SDimitry Andric       }
430349cc55cSDimitry Andric       case Instruction::Mul:
431fe6060f1SDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
432349cc55cSDimitry Andric                                 Depth + 1, AC, DT)
433349cc55cSDimitry Andric                 .mul(RHS, NSW);
434fe6060f1SDimitry Andric         break;
435fe6060f1SDimitry Andric       case Instruction::Shl:
4360b57cec5SDimitry Andric         // We're trying to linearize an expression of the kind:
4370b57cec5SDimitry Andric         //   shl i8 -128, 36
4380b57cec5SDimitry Andric         // where the shift count exceeds the bitwidth of the type.
4390b57cec5SDimitry Andric         // We can't decompose this further (the expression would return
4400b57cec5SDimitry Andric         // a poison value).
441fe6060f1SDimitry Andric         if (RHS.getLimitedValue() > Val.getBitWidth())
442fe6060f1SDimitry Andric           return Val;
4430b57cec5SDimitry Andric 
444fe6060f1SDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
445fe6060f1SDimitry Andric                                 Depth + 1, AC, DT);
446fe6060f1SDimitry Andric         E.Offset <<= RHS.getLimitedValue();
447fe6060f1SDimitry Andric         E.Scale <<= RHS.getLimitedValue();
448fe6060f1SDimitry Andric         E.IsNSW &= NSW;
449fe6060f1SDimitry Andric         break;
4500b57cec5SDimitry Andric       }
451fe6060f1SDimitry Andric       return E;
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric 
455fe6060f1SDimitry Andric   if (isa<ZExtInst>(Val.V))
456fe6060f1SDimitry Andric     return GetLinearExpression(
457fe6060f1SDimitry Andric         Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
458fe6060f1SDimitry Andric         DL, Depth + 1, AC, DT);
4590b57cec5SDimitry Andric 
460fe6060f1SDimitry Andric   if (isa<SExtInst>(Val.V))
461fe6060f1SDimitry Andric     return GetLinearExpression(
462fe6060f1SDimitry Andric         Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
463fe6060f1SDimitry Andric         DL, Depth + 1, AC, DT);
4640b57cec5SDimitry Andric 
465fe6060f1SDimitry Andric   return Val;
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
468349cc55cSDimitry Andric /// To ensure a pointer offset fits in an integer of size IndexSize
469349cc55cSDimitry Andric /// (in bits) when that size is smaller than the maximum index size. This is
4700b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices
4710b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information
472349cc55cSDimitry Andric /// where the maximum index size is 64b.
473349cc55cSDimitry Andric static APInt adjustToIndexSize(const APInt &Offset, unsigned IndexSize) {
474349cc55cSDimitry Andric   assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!");
475349cc55cSDimitry Andric   unsigned ShiftBits = Offset.getBitWidth() - IndexSize;
4760b57cec5SDimitry Andric   return (Offset << ShiftBits).ashr(ShiftBits);
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric 
479349cc55cSDimitry Andric namespace {
480349cc55cSDimitry Andric // A linear transformation of a Value; this class represents
481349cc55cSDimitry Andric // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
482349cc55cSDimitry Andric struct VariableGEPIndex {
483349cc55cSDimitry Andric   CastedValue Val;
484349cc55cSDimitry Andric   APInt Scale;
4850b57cec5SDimitry Andric 
486349cc55cSDimitry Andric   // Context instruction to use when querying information about this index.
487349cc55cSDimitry Andric   const Instruction *CxtI;
488349cc55cSDimitry Andric 
489349cc55cSDimitry Andric   /// True if all operations in this expression are NSW.
490349cc55cSDimitry Andric   bool IsNSW;
491349cc55cSDimitry Andric 
492349cc55cSDimitry Andric   void dump() const {
493349cc55cSDimitry Andric     print(dbgs());
494349cc55cSDimitry Andric     dbgs() << "\n";
4950b57cec5SDimitry Andric   }
496349cc55cSDimitry Andric   void print(raw_ostream &OS) const {
497349cc55cSDimitry Andric     OS << "(V=" << Val.V->getName()
498349cc55cSDimitry Andric        << ", zextbits=" << Val.ZExtBits
499349cc55cSDimitry Andric        << ", sextbits=" << Val.SExtBits
500349cc55cSDimitry Andric        << ", truncbits=" << Val.TruncBits
501349cc55cSDimitry Andric        << ", scale=" << Scale << ")";
502349cc55cSDimitry Andric   }
503349cc55cSDimitry Andric };
504349cc55cSDimitry Andric }
505349cc55cSDimitry Andric 
506349cc55cSDimitry Andric // Represents the internal structure of a GEP, decomposed into a base pointer,
507349cc55cSDimitry Andric // constant offsets, and variable scaled indices.
508349cc55cSDimitry Andric struct BasicAAResult::DecomposedGEP {
509349cc55cSDimitry Andric   // Base pointer of the GEP
510349cc55cSDimitry Andric   const Value *Base;
511349cc55cSDimitry Andric   // Total constant offset from base.
512349cc55cSDimitry Andric   APInt Offset;
513349cc55cSDimitry Andric   // Scaled variable (non-constant) indices.
514349cc55cSDimitry Andric   SmallVector<VariableGEPIndex, 4> VarIndices;
515349cc55cSDimitry Andric   // Are all operations inbounds GEPs or non-indexing operations?
516349cc55cSDimitry Andric   // (None iff expression doesn't involve any geps)
517349cc55cSDimitry Andric   Optional<bool> InBounds;
518349cc55cSDimitry Andric 
519349cc55cSDimitry Andric   void dump() const {
520349cc55cSDimitry Andric     print(dbgs());
521349cc55cSDimitry Andric     dbgs() << "\n";
522349cc55cSDimitry Andric   }
523349cc55cSDimitry Andric   void print(raw_ostream &OS) const {
524349cc55cSDimitry Andric     OS << "(DecomposedGEP Base=" << Base->getName()
525349cc55cSDimitry Andric        << ", Offset=" << Offset
526349cc55cSDimitry Andric        << ", VarIndices=[";
527349cc55cSDimitry Andric     for (size_t i = 0; i < VarIndices.size(); i++) {
528349cc55cSDimitry Andric       if (i != 0)
529349cc55cSDimitry Andric         OS << ", ";
530349cc55cSDimitry Andric       VarIndices[i].print(OS);
531349cc55cSDimitry Andric     }
532349cc55cSDimitry Andric     OS << "])";
533349cc55cSDimitry Andric   }
534349cc55cSDimitry Andric };
535349cc55cSDimitry Andric 
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer
5380b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets.
5390b57cec5SDimitry Andric ///
5400b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
5410b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the
5420b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As
5430b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form.
544e8d8bef9SDimitry Andric BasicAAResult::DecomposedGEP
545e8d8bef9SDimitry Andric BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
546e8d8bef9SDimitry Andric                                       AssumptionCache *AC, DominatorTree *DT) {
5470b57cec5SDimitry Andric   // Limit recursion depth to limit compile time in crazy cases.
5480b57cec5SDimitry Andric   unsigned MaxLookup = MaxLookupSearchDepth;
5490b57cec5SDimitry Andric   SearchTimes++;
550e8d8bef9SDimitry Andric   const Instruction *CxtI = dyn_cast<Instruction>(V);
5510b57cec5SDimitry Andric 
552349cc55cSDimitry Andric   unsigned MaxIndexSize = DL.getMaxIndexSizeInBits();
553e8d8bef9SDimitry Andric   DecomposedGEP Decomposed;
554349cc55cSDimitry Andric   Decomposed.Offset = APInt(MaxIndexSize, 0);
5550b57cec5SDimitry Andric   do {
5560b57cec5SDimitry Andric     // See if this is a bitcast or GEP.
5570b57cec5SDimitry Andric     const Operator *Op = dyn_cast<Operator>(V);
5580b57cec5SDimitry Andric     if (!Op) {
5590b57cec5SDimitry Andric       // The only non-operator case we can handle are GlobalAliases.
5600b57cec5SDimitry Andric       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
5610b57cec5SDimitry Andric         if (!GA->isInterposable()) {
5620b57cec5SDimitry Andric           V = GA->getAliasee();
5630b57cec5SDimitry Andric           continue;
5640b57cec5SDimitry Andric         }
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric       Decomposed.Base = V;
567e8d8bef9SDimitry Andric       return Decomposed;
5680b57cec5SDimitry Andric     }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric     if (Op->getOpcode() == Instruction::BitCast ||
5710b57cec5SDimitry Andric         Op->getOpcode() == Instruction::AddrSpaceCast) {
5720b57cec5SDimitry Andric       V = Op->getOperand(0);
5730b57cec5SDimitry Andric       continue;
5740b57cec5SDimitry Andric     }
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
5770b57cec5SDimitry Andric     if (!GEPOp) {
5785ffd83dbSDimitry Andric       if (const auto *PHI = dyn_cast<PHINode>(V)) {
5795ffd83dbSDimitry Andric         // Look through single-arg phi nodes created by LCSSA.
5805ffd83dbSDimitry Andric         if (PHI->getNumIncomingValues() == 1) {
5815ffd83dbSDimitry Andric           V = PHI->getIncomingValue(0);
5825ffd83dbSDimitry Andric           continue;
5835ffd83dbSDimitry Andric         }
5845ffd83dbSDimitry Andric       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
5850b57cec5SDimitry Andric         // CaptureTracking can know about special capturing properties of some
5860b57cec5SDimitry Andric         // intrinsics like launder.invariant.group, that can't be expressed with
5870b57cec5SDimitry Andric         // the attributes, but have properties like returning aliasing pointer.
5880b57cec5SDimitry Andric         // Because some analysis may assume that nocaptured pointer is not
5890b57cec5SDimitry Andric         // returned from some special intrinsic (because function would have to
5900b57cec5SDimitry Andric         // be marked with returns attribute), it is crucial to use this function
5910b57cec5SDimitry Andric         // because it should be in sync with CaptureTracking. Not using it may
5920b57cec5SDimitry Andric         // cause weird miscompilations where 2 aliasing pointers are assumed to
5930b57cec5SDimitry Andric         // noalias.
5948bcb0991SDimitry Andric         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
5950b57cec5SDimitry Andric           V = RP;
5960b57cec5SDimitry Andric           continue;
5970b57cec5SDimitry Andric         }
5980b57cec5SDimitry Andric       }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric       Decomposed.Base = V;
601e8d8bef9SDimitry Andric       return Decomposed;
6020b57cec5SDimitry Andric     }
6030b57cec5SDimitry Andric 
604fe6060f1SDimitry Andric     // Track whether we've seen at least one in bounds gep, and if so, whether
605fe6060f1SDimitry Andric     // all geps parsed were in bounds.
606fe6060f1SDimitry Andric     if (Decomposed.InBounds == None)
607fe6060f1SDimitry Andric       Decomposed.InBounds = GEPOp->isInBounds();
608fe6060f1SDimitry Andric     else if (!GEPOp->isInBounds())
609fe6060f1SDimitry Andric       Decomposed.InBounds = false;
610fe6060f1SDimitry Andric 
611349cc55cSDimitry Andric     assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
6120b57cec5SDimitry Andric 
6135ffd83dbSDimitry Andric     // Don't attempt to analyze GEPs if index scale is not a compile-time
6145ffd83dbSDimitry Andric     // constant.
6155ffd83dbSDimitry Andric     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
6165ffd83dbSDimitry Andric       Decomposed.Base = V;
617e8d8bef9SDimitry Andric       return Decomposed;
6185ffd83dbSDimitry Andric     }
6195ffd83dbSDimitry Andric 
6200b57cec5SDimitry Andric     unsigned AS = GEPOp->getPointerAddressSpace();
6210b57cec5SDimitry Andric     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
6220b57cec5SDimitry Andric     gep_type_iterator GTI = gep_type_begin(GEPOp);
623349cc55cSDimitry Andric     unsigned IndexSize = DL.getIndexSizeInBits(AS);
6240b57cec5SDimitry Andric     // Assume all GEP operands are constants until proven otherwise.
6250b57cec5SDimitry Andric     bool GepHasConstantOffset = true;
6260b57cec5SDimitry Andric     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
6270b57cec5SDimitry Andric          I != E; ++I, ++GTI) {
6280b57cec5SDimitry Andric       const Value *Index = *I;
6290b57cec5SDimitry Andric       // Compute the (potentially symbolic) offset in bytes for this index.
6300b57cec5SDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
6310b57cec5SDimitry Andric         // For a struct, add the member offset.
6320b57cec5SDimitry Andric         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
6330b57cec5SDimitry Andric         if (FieldNo == 0)
6340b57cec5SDimitry Andric           continue;
6350b57cec5SDimitry Andric 
636e8d8bef9SDimitry Andric         Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
6370b57cec5SDimitry Andric         continue;
6380b57cec5SDimitry Andric       }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric       // For an array/pointer, add the element offset, explicitly scaled.
6410b57cec5SDimitry Andric       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
6420b57cec5SDimitry Andric         if (CIdx->isZero())
6430b57cec5SDimitry Andric           continue;
644e8d8bef9SDimitry Andric         Decomposed.Offset +=
645e8d8bef9SDimitry Andric             DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
646349cc55cSDimitry Andric             CIdx->getValue().sextOrTrunc(MaxIndexSize);
6470b57cec5SDimitry Andric         continue;
6480b57cec5SDimitry Andric       }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric       GepHasConstantOffset = false;
6510b57cec5SDimitry Andric 
652349cc55cSDimitry Andric       // If the integer type is smaller than the index size, it is implicitly
653349cc55cSDimitry Andric       // sign extended or truncated to index size.
6540b57cec5SDimitry Andric       unsigned Width = Index->getType()->getIntegerBitWidth();
655349cc55cSDimitry Andric       unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
656349cc55cSDimitry Andric       unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
657fe6060f1SDimitry Andric       LinearExpression LE = GetLinearExpression(
658349cc55cSDimitry Andric           CastedValue(Index, 0, SExtBits, TruncBits), DL, 0, AC, DT);
6590b57cec5SDimitry Andric 
660349cc55cSDimitry Andric       // Scale by the type size.
661349cc55cSDimitry Andric       unsigned TypeSize =
662349cc55cSDimitry Andric           DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize();
663349cc55cSDimitry Andric       LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds());
664349cc55cSDimitry Andric       Decomposed.Offset += LE.Offset.sextOrSelf(MaxIndexSize);
665349cc55cSDimitry Andric       APInt Scale = LE.Scale.sextOrSelf(MaxIndexSize);
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric       // If we already had an occurrence of this index variable, merge this
6680b57cec5SDimitry Andric       // scale into it.  For example, we want to handle:
6690b57cec5SDimitry Andric       //   A[x][x] -> x*16 + x*4 -> x*20
6700b57cec5SDimitry Andric       // This also ensures that 'x' only appears in the index list once.
6710b57cec5SDimitry Andric       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
672349cc55cSDimitry Andric         if (Decomposed.VarIndices[i].Val.V == LE.Val.V &&
673349cc55cSDimitry Andric             Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {
6740b57cec5SDimitry Andric           Scale += Decomposed.VarIndices[i].Scale;
6750b57cec5SDimitry Andric           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
6760b57cec5SDimitry Andric           break;
6770b57cec5SDimitry Andric         }
6780b57cec5SDimitry Andric       }
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric       // Make sure that we have a scale that makes sense for this target's
681349cc55cSDimitry Andric       // index size.
682349cc55cSDimitry Andric       Scale = adjustToIndexSize(Scale, IndexSize);
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric       if (!!Scale) {
685349cc55cSDimitry Andric         VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW};
6860b57cec5SDimitry Andric         Decomposed.VarIndices.push_back(Entry);
6870b57cec5SDimitry Andric       }
6880b57cec5SDimitry Andric     }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric     // Take care of wrap-arounds
691e8d8bef9SDimitry Andric     if (GepHasConstantOffset)
692349cc55cSDimitry Andric       Decomposed.Offset = adjustToIndexSize(Decomposed.Offset, IndexSize);
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric     // Analyze the base pointer next.
6950b57cec5SDimitry Andric     V = GEPOp->getOperand(0);
6960b57cec5SDimitry Andric   } while (--MaxLookup);
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // If the chain of expressions is too deep, just return early.
6990b57cec5SDimitry Andric   Decomposed.Base = V;
7000b57cec5SDimitry Andric   SearchLimitReached++;
701e8d8bef9SDimitry Andric   return Decomposed;
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric /// Returns whether the given pointer value points to memory that is local to
7050b57cec5SDimitry Andric /// the function, with global constants being considered local to all
7060b57cec5SDimitry Andric /// functions.
7070b57cec5SDimitry Andric bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
7080b57cec5SDimitry Andric                                            AAQueryInfo &AAQI, bool OrLocal) {
7090b57cec5SDimitry Andric   assert(Visited.empty() && "Visited must be cleared after use!");
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   unsigned MaxLookup = 8;
7120b57cec5SDimitry Andric   SmallVector<const Value *, 16> Worklist;
7130b57cec5SDimitry Andric   Worklist.push_back(Loc.Ptr);
7140b57cec5SDimitry Andric   do {
715e8d8bef9SDimitry Andric     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
7160b57cec5SDimitry Andric     if (!Visited.insert(V).second) {
7170b57cec5SDimitry Andric       Visited.clear();
7180b57cec5SDimitry Andric       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7190b57cec5SDimitry Andric     }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric     // An alloca instruction defines local memory.
7220b57cec5SDimitry Andric     if (OrLocal && isa<AllocaInst>(V))
7230b57cec5SDimitry Andric       continue;
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric     // A global constant counts as local memory for our purposes.
7260b57cec5SDimitry Andric     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7270b57cec5SDimitry Andric       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
7280b57cec5SDimitry Andric       // global to be marked constant in some modules and non-constant in
7290b57cec5SDimitry Andric       // others.  GV may even be a declaration, not a definition.
7300b57cec5SDimitry Andric       if (!GV->isConstant()) {
7310b57cec5SDimitry Andric         Visited.clear();
7320b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7330b57cec5SDimitry Andric       }
7340b57cec5SDimitry Andric       continue;
7350b57cec5SDimitry Andric     }
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric     // If both select values point to local memory, then so does the select.
7380b57cec5SDimitry Andric     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7390b57cec5SDimitry Andric       Worklist.push_back(SI->getTrueValue());
7400b57cec5SDimitry Andric       Worklist.push_back(SI->getFalseValue());
7410b57cec5SDimitry Andric       continue;
7420b57cec5SDimitry Andric     }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric     // If all values incoming to a phi node point to local memory, then so does
7450b57cec5SDimitry Andric     // the phi.
7460b57cec5SDimitry Andric     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7470b57cec5SDimitry Andric       // Don't bother inspecting phi nodes with many operands.
7480b57cec5SDimitry Andric       if (PN->getNumIncomingValues() > MaxLookup) {
7490b57cec5SDimitry Andric         Visited.clear();
7500b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7510b57cec5SDimitry Andric       }
752e8d8bef9SDimitry Andric       append_range(Worklist, PN->incoming_values());
7530b57cec5SDimitry Andric       continue;
7540b57cec5SDimitry Andric     }
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric     // Otherwise be conservative.
7570b57cec5SDimitry Andric     Visited.clear();
7580b57cec5SDimitry Andric     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7590b57cec5SDimitry Andric   } while (!Worklist.empty() && --MaxLookup);
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   Visited.clear();
7620b57cec5SDimitry Andric   return Worklist.empty();
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric 
765fe6060f1SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
766fe6060f1SDimitry Andric   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
767fe6060f1SDimitry Andric   return II && II->getIntrinsicID() == IID;
768fe6060f1SDimitry Andric }
769fe6060f1SDimitry Andric 
7700b57cec5SDimitry Andric /// Returns the behavior when calling the given call site.
7710b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
7720b57cec5SDimitry Andric   if (Call->doesNotAccessMemory())
7730b57cec5SDimitry Andric     // Can't do better than this.
7740b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric   // If the callsite knows it only reads memory, don't return worse
7790b57cec5SDimitry Andric   // than that.
7800b57cec5SDimitry Andric   if (Call->onlyReadsMemory())
7810b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7820b57cec5SDimitry Andric   else if (Call->doesNotReadMemory())
7835ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   if (Call->onlyAccessesArgMemory())
7860b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7870b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemory())
7880b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7890b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
7900b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   // If the call has operand bundles then aliasing attributes from the function
7930b57cec5SDimitry Andric   // it calls do not directly apply to the call.  This can be made more precise
7940b57cec5SDimitry Andric   // in the future.
7950b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
7960b57cec5SDimitry Andric     if (const Function *F = Call->getCalledFunction())
7970b57cec5SDimitry Andric       Min =
7980b57cec5SDimitry Andric           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   return Min;
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call
8040b57cec5SDimitry Andric /// site is not known.
8050b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
8060b57cec5SDimitry Andric   // If the function declares it doesn't access memory, we can't do better.
8070b57cec5SDimitry Andric   if (F->doesNotAccessMemory())
8080b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   // If the function declares it only reads memory, go with that.
8130b57cec5SDimitry Andric   if (F->onlyReadsMemory())
8140b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
8150b57cec5SDimitry Andric   else if (F->doesNotReadMemory())
8165ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   if (F->onlyAccessesArgMemory())
8190b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
8200b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemory())
8210b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
8220b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemOrArgMem())
8230b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   return Min;
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric /// Returns true if this is a writeonly (i.e Mod only) parameter.
8290b57cec5SDimitry Andric static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
8300b57cec5SDimitry Andric                              const TargetLibraryInfo &TLI) {
8310b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
8320b57cec5SDimitry Andric     return true;
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   // We can bound the aliasing properties of memset_pattern16 just as we can
8350b57cec5SDimitry Andric   // for memcpy/memset.  This is particularly important because the
8360b57cec5SDimitry Andric   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
8370b57cec5SDimitry Andric   // whenever possible.
8380b57cec5SDimitry Andric   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
8390b57cec5SDimitry Andric   // attributes.
8400b57cec5SDimitry Andric   LibFunc F;
8410b57cec5SDimitry Andric   if (Call->getCalledFunction() &&
8420b57cec5SDimitry Andric       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
8430b57cec5SDimitry Andric       F == LibFunc_memset_pattern16 && TLI.has(F))
8440b57cec5SDimitry Andric     if (ArgIdx == 0)
8450b57cec5SDimitry Andric       return true;
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   // TODO: memset_pattern4, memset_pattern8
8480b57cec5SDimitry Andric   // TODO: _chk variants
8490b57cec5SDimitry Andric   // TODO: strcmp, strcpy
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   return false;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
8550b57cec5SDimitry Andric                                            unsigned ArgIdx) {
8560b57cec5SDimitry Andric   // Checking for known builtin intrinsics and target library functions.
8570b57cec5SDimitry Andric   if (isWriteOnlyParam(Call, ArgIdx, TLI))
8580b57cec5SDimitry Andric     return ModRefInfo::Mod;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
8610b57cec5SDimitry Andric     return ModRefInfo::Ref;
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
8640b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
8670b57cec5SDimitry Andric }
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric #ifndef NDEBUG
8700b57cec5SDimitry Andric static const Function *getParent(const Value *V) {
8710b57cec5SDimitry Andric   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
8720b57cec5SDimitry Andric     if (!inst->getParent())
8730b57cec5SDimitry Andric       return nullptr;
8740b57cec5SDimitry Andric     return inst->getParent()->getParent();
8750b57cec5SDimitry Andric   }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   if (const Argument *arg = dyn_cast<Argument>(V))
8780b57cec5SDimitry Andric     return arg->getParent();
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric   return nullptr;
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) {
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   const Function *F1 = getParent(O1);
8860b57cec5SDimitry Andric   const Function *F2 = getParent(O2);
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   return !F1 || !F2 || F1 == F2;
8890b57cec5SDimitry Andric }
8900b57cec5SDimitry Andric #endif
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
8930b57cec5SDimitry Andric                                  const MemoryLocation &LocB,
8940b57cec5SDimitry Andric                                  AAQueryInfo &AAQI) {
8950b57cec5SDimitry Andric   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
8960b57cec5SDimitry Andric          "BasicAliasAnalysis doesn't support interprocedural queries.");
897fe6060f1SDimitry Andric   return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI);
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory
9010b57cec5SDimitry Andric /// object.
9020b57cec5SDimitry Andric ///
9030b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't
9040b57cec5SDimitry Andric /// say much about this query.  We do, however, use simple "address taken"
9050b57cec5SDimitry Andric /// analysis on local objects.
9060b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
9070b57cec5SDimitry Andric                                         const MemoryLocation &Loc,
9080b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
9090b57cec5SDimitry Andric   assert(notDifferentParent(Call, Loc.Ptr) &&
9100b57cec5SDimitry Andric          "AliasAnalysis query involving multiple functions!");
9110b57cec5SDimitry Andric 
912e8d8bef9SDimitry Andric   const Value *Object = getUnderlyingObject(Loc.Ptr);
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   // Calls marked 'tail' cannot read or write allocas from the current frame
9150b57cec5SDimitry Andric   // because the current frame might be destroyed by the time they run. However,
9160b57cec5SDimitry Andric   // a tail call may use an alloca with byval. Calling with byval copies the
9170b57cec5SDimitry Andric   // contents of the alloca into argument registers or stack slots, so there is
9180b57cec5SDimitry Andric   // no lifetime issue.
9190b57cec5SDimitry Andric   if (isa<AllocaInst>(Object))
9200b57cec5SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(Call))
9210b57cec5SDimitry Andric       if (CI->isTailCall() &&
9220b57cec5SDimitry Andric           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
9230b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
9260b57cec5SDimitry Andric   // modify them even though the alloca is not escaped.
9270b57cec5SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(Object))
9280b57cec5SDimitry Andric     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
9290b57cec5SDimitry Andric       return ModRefInfo::Mod;
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   // If the pointer is to a locally allocated object that does not escape,
9320b57cec5SDimitry Andric   // then the call can not mod/ref the pointer unless the call takes the pointer
9330b57cec5SDimitry Andric   // as an argument, and itself doesn't capture it.
9340b57cec5SDimitry Andric   if (!isa<Constant>(Object) && Call != Object &&
935349cc55cSDimitry Andric       AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) {
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric     // Optimistically assume that call doesn't touch Object and check this
9380b57cec5SDimitry Andric     // assumption in the following loop.
9390b57cec5SDimitry Andric     ModRefInfo Result = ModRefInfo::NoModRef;
9400b57cec5SDimitry Andric     bool IsMustAlias = true;
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric     unsigned OperandNo = 0;
9430b57cec5SDimitry Andric     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
9440b57cec5SDimitry Andric          CI != CE; ++CI, ++OperandNo) {
9450b57cec5SDimitry Andric       // Only look at the no-capture or byval pointer arguments.  If this
9460b57cec5SDimitry Andric       // pointer were passed to arguments that were neither of these, then it
9470b57cec5SDimitry Andric       // couldn't be no-capture.
9480b57cec5SDimitry Andric       if (!(*CI)->getType()->isPointerTy() ||
949349cc55cSDimitry Andric           (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() &&
9500b57cec5SDimitry Andric            !Call->isByValArgument(OperandNo)))
9510b57cec5SDimitry Andric         continue;
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric       // Call doesn't access memory through this operand, so we don't care
9540b57cec5SDimitry Andric       // if it aliases with Object.
9550b57cec5SDimitry Andric       if (Call->doesNotAccessMemory(OperandNo))
9560b57cec5SDimitry Andric         continue;
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric       // If this is a no-capture pointer argument, see if we can tell that it
9590b57cec5SDimitry Andric       // is impossible to alias the pointer we're checking.
960e8d8bef9SDimitry Andric       AliasResult AR = getBestAAResults().alias(
961e8d8bef9SDimitry Andric           MemoryLocation::getBeforeOrAfter(*CI),
962e8d8bef9SDimitry Andric           MemoryLocation::getBeforeOrAfter(Object), AAQI);
963fe6060f1SDimitry Andric       if (AR != AliasResult::MustAlias)
9640b57cec5SDimitry Andric         IsMustAlias = false;
9650b57cec5SDimitry Andric       // Operand doesn't alias 'Object', continue looking for other aliases
966fe6060f1SDimitry Andric       if (AR == AliasResult::NoAlias)
9670b57cec5SDimitry Andric         continue;
9680b57cec5SDimitry Andric       // Operand aliases 'Object', but call doesn't modify it. Strengthen
9690b57cec5SDimitry Andric       // initial assumption and keep looking in case if there are more aliases.
9700b57cec5SDimitry Andric       if (Call->onlyReadsMemory(OperandNo)) {
9710b57cec5SDimitry Andric         Result = setRef(Result);
9720b57cec5SDimitry Andric         continue;
9730b57cec5SDimitry Andric       }
9740b57cec5SDimitry Andric       // Operand aliases 'Object' but call only writes into it.
9750b57cec5SDimitry Andric       if (Call->doesNotReadMemory(OperandNo)) {
9760b57cec5SDimitry Andric         Result = setMod(Result);
9770b57cec5SDimitry Andric         continue;
9780b57cec5SDimitry Andric       }
9790b57cec5SDimitry Andric       // This operand aliases 'Object' and call reads and writes into it.
9800b57cec5SDimitry Andric       // Setting ModRef will not yield an early return below, MustAlias is not
9810b57cec5SDimitry Andric       // used further.
9820b57cec5SDimitry Andric       Result = ModRefInfo::ModRef;
9830b57cec5SDimitry Andric       break;
9840b57cec5SDimitry Andric     }
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric     // No operand aliases, reset Must bit. Add below if at least one aliases
9870b57cec5SDimitry Andric     // and all aliases found are MustAlias.
9880b57cec5SDimitry Andric     if (isNoModRef(Result))
9890b57cec5SDimitry Andric       IsMustAlias = false;
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric     // Early return if we improved mod ref information
9920b57cec5SDimitry Andric     if (!isModAndRefSet(Result)) {
9930b57cec5SDimitry Andric       if (isNoModRef(Result))
9940b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
9950b57cec5SDimitry Andric       return IsMustAlias ? setMust(Result) : clearMust(Result);
9960b57cec5SDimitry Andric     }
9970b57cec5SDimitry Andric   }
9980b57cec5SDimitry Andric 
9995ffd83dbSDimitry Andric   // If the call is malloc/calloc like, we can assume that it doesn't
10000b57cec5SDimitry Andric   // modify any IR visible value.  This is only valid because we assume these
10010b57cec5SDimitry Andric   // routines do not read values visible in the IR.  TODO: Consider special
10020b57cec5SDimitry Andric   // casing realloc and strdup routines which access only their arguments as
10030b57cec5SDimitry Andric   // well.  Or alternatively, replace all of this with inaccessiblememonly once
10040b57cec5SDimitry Andric   // that's implemented fully.
10050b57cec5SDimitry Andric   if (isMallocOrCallocLikeFn(Call, &TLI)) {
10060b57cec5SDimitry Andric     // Be conservative if the accessed pointer may alias the allocation -
10070b57cec5SDimitry Andric     // fallback to the generic handling below.
1008fe6060f1SDimitry Andric     if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc,
1009fe6060f1SDimitry Andric                                  AAQI) == AliasResult::NoAlias)
10100b57cec5SDimitry Andric       return ModRefInfo::NoModRef;
10110b57cec5SDimitry Andric   }
10120b57cec5SDimitry Andric 
1013e8d8bef9SDimitry Andric   // The semantics of memcpy intrinsics either exactly overlap or do not
1014e8d8bef9SDimitry Andric   // overlap, i.e., source and destination of any given memcpy are either
1015e8d8bef9SDimitry Andric   // no-alias or must-alias.
10160b57cec5SDimitry Andric   if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
1017e8d8bef9SDimitry Andric     AliasResult SrcAA =
1018e8d8bef9SDimitry Andric         getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI);
1019e8d8bef9SDimitry Andric     AliasResult DestAA =
1020e8d8bef9SDimitry Andric         getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI);
10210b57cec5SDimitry Andric     // It's also possible for Loc to alias both src and dest, or neither.
10220b57cec5SDimitry Andric     ModRefInfo rv = ModRefInfo::NoModRef;
1023fe6060f1SDimitry Andric     if (SrcAA != AliasResult::NoAlias)
10240b57cec5SDimitry Andric       rv = setRef(rv);
1025fe6060f1SDimitry Andric     if (DestAA != AliasResult::NoAlias)
10260b57cec5SDimitry Andric       rv = setMod(rv);
10270b57cec5SDimitry Andric     return rv;
10280b57cec5SDimitry Andric   }
10290b57cec5SDimitry Andric 
1030fe6060f1SDimitry Andric   // Guard intrinsics are marked as arbitrarily writing so that proper control
1031fe6060f1SDimitry Andric   // dependencies are maintained but they never mods any particular memory
1032fe6060f1SDimitry Andric   // location.
10330b57cec5SDimitry Andric   //
10340b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10350b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10360b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10370b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
10380b57cec5SDimitry Andric     return ModRefInfo::Ref;
1039e8d8bef9SDimitry Andric   // The same applies to deoptimize which is essentially a guard(false).
1040e8d8bef9SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize))
1041e8d8bef9SDimitry Andric     return ModRefInfo::Ref;
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
10440b57cec5SDimitry Andric   // writing so that proper control dependencies are maintained but they never
10450b57cec5SDimitry Andric   // mod any particular memory location visible to the IR.
10460b57cec5SDimitry Andric   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
10470b57cec5SDimitry Andric   // intrinsic is now modeled as reading memory. This prevents hoisting the
10480b57cec5SDimitry Andric   // invariant.start intrinsic over stores. Consider:
10490b57cec5SDimitry Andric   // *ptr = 40;
10500b57cec5SDimitry Andric   // *ptr = 50;
10510b57cec5SDimitry Andric   // invariant_start(ptr)
10520b57cec5SDimitry Andric   // int val = *ptr;
10530b57cec5SDimitry Andric   // print(val);
10540b57cec5SDimitry Andric   //
10550b57cec5SDimitry Andric   // This cannot be transformed to:
10560b57cec5SDimitry Andric   //
10570b57cec5SDimitry Andric   // *ptr = 40;
10580b57cec5SDimitry Andric   // invariant_start(ptr)
10590b57cec5SDimitry Andric   // *ptr = 50;
10600b57cec5SDimitry Andric   // int val = *ptr;
10610b57cec5SDimitry Andric   // print(val);
10620b57cec5SDimitry Andric   //
10630b57cec5SDimitry Andric   // The transformation will cause the second store to be ignored (based on
10640b57cec5SDimitry Andric   // rules of invariant.start)  and print 40, while the first program always
10650b57cec5SDimitry Andric   // prints 50.
10660b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
10670b57cec5SDimitry Andric     return ModRefInfo::Ref;
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10700b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
10740b57cec5SDimitry Andric                                         const CallBase *Call2,
10750b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
1076fe6060f1SDimitry Andric   // Guard intrinsics are marked as arbitrarily writing so that proper control
1077fe6060f1SDimitry Andric   // dependencies are maintained but they never mods any particular memory
1078fe6060f1SDimitry Andric   // location.
10790b57cec5SDimitry Andric   //
10800b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10810b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10820b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric   // NB! This function is *not* commutative, so we special case two
10850b57cec5SDimitry Andric   // possibilities for guard intrinsics.
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
10880b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
10890b57cec5SDimitry Andric                ? ModRefInfo::Ref
10900b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
10930b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
10940b57cec5SDimitry Andric                ? ModRefInfo::Mod
10950b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10980b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
1101fe6060f1SDimitry Andric /// Return true if we know V to the base address of the corresponding memory
1102fe6060f1SDimitry Andric /// object.  This implies that any address less than V must be out of bounds
1103fe6060f1SDimitry Andric /// for the underlying object.  Note that just being isIdentifiedObject() is
1104fe6060f1SDimitry Andric /// not enough - For example, a negative offset from a noalias argument or call
1105fe6060f1SDimitry Andric /// can be inbounds w.r.t the actual underlying object.
1106fe6060f1SDimitry Andric static bool isBaseOfObject(const Value *V) {
1107fe6060f1SDimitry Andric   // TODO: We can handle other cases here
1108fe6060f1SDimitry Andric   // 1) For GC languages, arguments to functions are often required to be
1109fe6060f1SDimitry Andric   //    base pointers.
1110fe6060f1SDimitry Andric   // 2) Result of allocation routines are often base pointers.  Leverage TLI.
1111fe6060f1SDimitry Andric   return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
11120b57cec5SDimitry Andric }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
11150b57cec5SDimitry Andric /// another pointer.
11160b57cec5SDimitry Andric ///
11170b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2.
1118e8d8bef9SDimitry Andric /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
11190b57cec5SDimitry Andric /// V2.
11200b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP(
1121fe6060f1SDimitry Andric     const GEPOperator *GEP1, LocationSize V1Size,
1122fe6060f1SDimitry Andric     const Value *V2, LocationSize V2Size,
11230b57cec5SDimitry Andric     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1124fe6060f1SDimitry Andric   if (!V1Size.hasValue() && !V2Size.hasValue()) {
1125fe6060f1SDimitry Andric     // TODO: This limitation exists for compile-time reasons. Relax it if we
1126fe6060f1SDimitry Andric     // can avoid exponential pathological cases.
1127fe6060f1SDimitry Andric     if (!isa<GEPOperator>(V2))
1128fe6060f1SDimitry Andric       return AliasResult::MayAlias;
1129fe6060f1SDimitry Andric 
1130fe6060f1SDimitry Andric     // If both accesses have unknown size, we can only check whether the base
1131fe6060f1SDimitry Andric     // objects don't alias.
1132fe6060f1SDimitry Andric     AliasResult BaseAlias = getBestAAResults().alias(
1133fe6060f1SDimitry Andric         MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1134fe6060f1SDimitry Andric         MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1135fe6060f1SDimitry Andric     return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1136fe6060f1SDimitry Andric                                              : AliasResult::MayAlias;
1137fe6060f1SDimitry Andric   }
1138fe6060f1SDimitry Andric 
1139e8d8bef9SDimitry Andric   DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1140e8d8bef9SDimitry Andric   DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
11410b57cec5SDimitry Andric 
1142349cc55cSDimitry Andric   // Bail if we were not able to decompose anything.
1143349cc55cSDimitry Andric   if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1144fe6060f1SDimitry Andric     return AliasResult::MayAlias;
11455ffd83dbSDimitry Andric 
11460b57cec5SDimitry Andric   // Subtract the GEP2 pointer from the GEP1 pointer to find out their
11470b57cec5SDimitry Andric   // symbolic difference.
1148349cc55cSDimitry Andric   subtractDecomposedGEPs(DecompGEP1, DecompGEP2);
11490b57cec5SDimitry Andric 
1150fe6060f1SDimitry Andric   // If an inbounds GEP would have to start from an out of bounds address
1151fe6060f1SDimitry Andric   // for the two to alias, then we can assume noalias.
1152fe6060f1SDimitry Andric   if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() &&
1153fe6060f1SDimitry Andric       V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) &&
1154fe6060f1SDimitry Andric       isBaseOfObject(DecompGEP2.Base))
1155fe6060f1SDimitry Andric     return AliasResult::NoAlias;
11560b57cec5SDimitry Andric 
1157fe6060f1SDimitry Andric   if (isa<GEPOperator>(V2)) {
1158fe6060f1SDimitry Andric     // Symmetric case to above.
1159fe6060f1SDimitry Andric     if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() &&
1160fe6060f1SDimitry Andric         V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) &&
1161fe6060f1SDimitry Andric         isBaseOfObject(DecompGEP1.Base))
1162fe6060f1SDimitry Andric       return AliasResult::NoAlias;
11630b57cec5SDimitry Andric   }
11640b57cec5SDimitry Andric 
1165fe6060f1SDimitry Andric   // For GEPs with identical offsets, we can preserve the size and AAInfo
1166fe6060f1SDimitry Andric   // when performing the alias check on the underlying objects.
1167e8d8bef9SDimitry Andric   if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1168349cc55cSDimitry Andric     return getBestAAResults().alias(MemoryLocation(DecompGEP1.Base, V1Size),
1169349cc55cSDimitry Andric                                     MemoryLocation(DecompGEP2.Base, V2Size),
1170349cc55cSDimitry Andric                                     AAQI);
1171fe6060f1SDimitry Andric 
1172fe6060f1SDimitry Andric   // Do the base pointers alias?
1173fe6060f1SDimitry Andric   AliasResult BaseAlias = getBestAAResults().alias(
1174349cc55cSDimitry Andric       MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1175349cc55cSDimitry Andric       MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);
1176fe6060f1SDimitry Andric 
1177fe6060f1SDimitry Andric   // If we get a No or May, then return it immediately, no amount of analysis
1178fe6060f1SDimitry Andric   // will improve this situation.
1179fe6060f1SDimitry Andric   if (BaseAlias != AliasResult::MustAlias) {
1180fe6060f1SDimitry Andric     assert(BaseAlias == AliasResult::NoAlias ||
1181fe6060f1SDimitry Andric            BaseAlias == AliasResult::MayAlias);
1182fe6060f1SDimitry Andric     return BaseAlias;
1183fe6060f1SDimitry Andric   }
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   // If there is a constant difference between the pointers, but the difference
11860b57cec5SDimitry Andric   // is less than the size of the associated memory object, then we know
11870b57cec5SDimitry Andric   // that the objects are partially overlapping.  If the difference is
11880b57cec5SDimitry Andric   // greater, we know they do not overlap.
1189349cc55cSDimitry Andric   if (DecompGEP1.VarIndices.empty()) {
1190fe6060f1SDimitry Andric     APInt &Off = DecompGEP1.Offset;
1191fe6060f1SDimitry Andric 
1192fe6060f1SDimitry Andric     // Initialize for Off >= 0 (V2 <= GEP1) case.
1193fe6060f1SDimitry Andric     const Value *LeftPtr = V2;
1194fe6060f1SDimitry Andric     const Value *RightPtr = GEP1;
1195fe6060f1SDimitry Andric     LocationSize VLeftSize = V2Size;
1196fe6060f1SDimitry Andric     LocationSize VRightSize = V1Size;
1197fe6060f1SDimitry Andric     const bool Swapped = Off.isNegative();
1198fe6060f1SDimitry Andric 
1199fe6060f1SDimitry Andric     if (Swapped) {
1200fe6060f1SDimitry Andric       // Swap if we have the situation where:
12010b57cec5SDimitry Andric       // +                +
12020b57cec5SDimitry Andric       // | BaseOffset     |
12030b57cec5SDimitry Andric       // ---------------->|
12040b57cec5SDimitry Andric       // |-->V1Size       |-------> V2Size
12050b57cec5SDimitry Andric       // GEP1             V2
1206fe6060f1SDimitry Andric       std::swap(LeftPtr, RightPtr);
1207fe6060f1SDimitry Andric       std::swap(VLeftSize, VRightSize);
1208fe6060f1SDimitry Andric       Off = -Off;
12090b57cec5SDimitry Andric     }
1210fe6060f1SDimitry Andric 
1211349cc55cSDimitry Andric     if (!VLeftSize.hasValue())
1212349cc55cSDimitry Andric       return AliasResult::MayAlias;
1213349cc55cSDimitry Andric 
1214fe6060f1SDimitry Andric     const uint64_t LSize = VLeftSize.getValue();
1215fe6060f1SDimitry Andric     if (Off.ult(LSize)) {
1216fe6060f1SDimitry Andric       // Conservatively drop processing if a phi was visited and/or offset is
1217fe6060f1SDimitry Andric       // too big.
1218fe6060f1SDimitry Andric       AliasResult AR = AliasResult::PartialAlias;
1219fe6060f1SDimitry Andric       if (VRightSize.hasValue() && Off.ule(INT32_MAX) &&
1220fe6060f1SDimitry Andric           (Off + VRightSize.getValue()).ule(LSize)) {
1221fe6060f1SDimitry Andric         // Memory referenced by right pointer is nested. Save the offset in
1222fe6060f1SDimitry Andric         // cache. Note that originally offset estimated as GEP1-V2, but
1223fe6060f1SDimitry Andric         // AliasResult contains the shift that represents GEP1+Offset=V2.
1224fe6060f1SDimitry Andric         AR.setOffset(-Off.getSExtValue());
1225fe6060f1SDimitry Andric         AR.swap(Swapped);
1226fe6060f1SDimitry Andric       }
1227fe6060f1SDimitry Andric       return AR;
1228fe6060f1SDimitry Andric     }
1229fe6060f1SDimitry Andric     return AliasResult::NoAlias;
12300b57cec5SDimitry Andric   }
12310b57cec5SDimitry Andric 
1232349cc55cSDimitry Andric   // We need to know both acess sizes for all the following heuristics.
1233349cc55cSDimitry Andric   if (!V1Size.hasValue() || !V2Size.hasValue())
1234349cc55cSDimitry Andric     return AliasResult::MayAlias;
1235349cc55cSDimitry Andric 
1236e8d8bef9SDimitry Andric   APInt GCD;
1237349cc55cSDimitry Andric   ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset);
12380b57cec5SDimitry Andric   for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1239349cc55cSDimitry Andric     const VariableGEPIndex &Index = DecompGEP1.VarIndices[i];
1240349cc55cSDimitry Andric     const APInt &Scale = Index.Scale;
1241349cc55cSDimitry Andric     APInt ScaleForGCD = Scale;
1242349cc55cSDimitry Andric     if (!Index.IsNSW)
1243fe6060f1SDimitry Andric       ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(),
1244fe6060f1SDimitry Andric                                         Scale.countTrailingZeros());
1245fe6060f1SDimitry Andric 
1246e8d8bef9SDimitry Andric     if (i == 0)
1247fe6060f1SDimitry Andric       GCD = ScaleForGCD.abs();
1248e8d8bef9SDimitry Andric     else
1249fe6060f1SDimitry Andric       GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
12500b57cec5SDimitry Andric 
1251349cc55cSDimitry Andric     ConstantRange CR =
1252349cc55cSDimitry Andric         computeConstantRange(Index.Val.V, true, &AC, Index.CxtI);
1253349cc55cSDimitry Andric     KnownBits Known =
1254349cc55cSDimitry Andric         computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT);
1255349cc55cSDimitry Andric     CR = CR.intersectWith(
1256349cc55cSDimitry Andric         ConstantRange::fromKnownBits(Known, /* Signed */ true),
1257349cc55cSDimitry Andric         ConstantRange::Signed);
1258349cc55cSDimitry Andric     CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());
12590b57cec5SDimitry Andric 
1260349cc55cSDimitry Andric     assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
1261349cc55cSDimitry Andric            "Bit widths are normalized to MaxIndexSize");
1262349cc55cSDimitry Andric     if (Index.IsNSW)
1263349cc55cSDimitry Andric       OffsetRange = OffsetRange.add(CR.smul_sat(ConstantRange(Scale)));
1264349cc55cSDimitry Andric     else
1265349cc55cSDimitry Andric       OffsetRange = OffsetRange.add(CR.smul_fast(ConstantRange(Scale)));
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric 
1268e8d8bef9SDimitry Andric   // We now have accesses at two offsets from the same base:
1269e8d8bef9SDimitry Andric   //  1. (...)*GCD + DecompGEP1.Offset with size V1Size
1270e8d8bef9SDimitry Andric   //  2. 0 with size V2Size
1271e8d8bef9SDimitry Andric   // Using arithmetic modulo GCD, the accesses are at
1272e8d8bef9SDimitry Andric   // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1273e8d8bef9SDimitry Andric   // into the range [V2Size..GCD), then we know they cannot overlap.
1274e8d8bef9SDimitry Andric   APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1275e8d8bef9SDimitry Andric   if (ModOffset.isNegative())
1276e8d8bef9SDimitry Andric     ModOffset += GCD; // We want mod, not rem.
1277349cc55cSDimitry Andric   if (ModOffset.uge(V2Size.getValue()) &&
1278e8d8bef9SDimitry Andric       (GCD - ModOffset).uge(V1Size.getValue()))
1279fe6060f1SDimitry Andric     return AliasResult::NoAlias;
12800b57cec5SDimitry Andric 
1281349cc55cSDimitry Andric   // Compute ranges of potentially accessed bytes for both accesses. If the
1282349cc55cSDimitry Andric   // interseciton is empty, there can be no overlap.
1283349cc55cSDimitry Andric   unsigned BW = OffsetRange.getBitWidth();
1284349cc55cSDimitry Andric   ConstantRange Range1 = OffsetRange.add(
1285349cc55cSDimitry Andric       ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1286349cc55cSDimitry Andric   ConstantRange Range2 =
1287349cc55cSDimitry Andric       ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1288349cc55cSDimitry Andric   if (Range1.intersectWith(Range2).isEmptySet())
1289fe6060f1SDimitry Andric     return AliasResult::NoAlias;
1290e8d8bef9SDimitry Andric 
1291349cc55cSDimitry Andric   // Try to determine the range of values for VarIndex such that
1292349cc55cSDimitry Andric   // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex.
1293e8d8bef9SDimitry Andric   Optional<APInt> MinAbsVarIndex;
1294e8d8bef9SDimitry Andric   if (DecompGEP1.VarIndices.size() == 1) {
1295349cc55cSDimitry Andric     // VarIndex = Scale*V.
1296e8d8bef9SDimitry Andric     const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];
1297349cc55cSDimitry Andric     if (Var.Val.TruncBits == 0 &&
1298349cc55cSDimitry Andric         isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) {
1299349cc55cSDimitry Andric       // If V != 0 then abs(VarIndex) >= abs(Scale).
1300e8d8bef9SDimitry Andric       MinAbsVarIndex = Var.Scale.abs();
1301349cc55cSDimitry Andric     }
1302e8d8bef9SDimitry Andric   } else if (DecompGEP1.VarIndices.size() == 2) {
1303e8d8bef9SDimitry Andric     // VarIndex = Scale*V0 + (-Scale)*V1.
1304e8d8bef9SDimitry Andric     // If V0 != V1 then abs(VarIndex) >= abs(Scale).
1305e8d8bef9SDimitry Andric     // Check that VisitedPhiBBs is empty, to avoid reasoning about
1306e8d8bef9SDimitry Andric     // inequality of values across loop iterations.
1307e8d8bef9SDimitry Andric     const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];
1308e8d8bef9SDimitry Andric     const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];
1309349cc55cSDimitry Andric     if (Var0.Scale == -Var1.Scale && Var0.Val.TruncBits == 0 &&
1310349cc55cSDimitry Andric         Var0.Val.hasSameCastsAs(Var1.Val) && VisitedPhiBBs.empty() &&
1311349cc55cSDimitry Andric         isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr,
1312349cc55cSDimitry Andric                         DT))
1313e8d8bef9SDimitry Andric       MinAbsVarIndex = Var0.Scale.abs();
1314e8d8bef9SDimitry Andric   }
1315e8d8bef9SDimitry Andric 
1316e8d8bef9SDimitry Andric   if (MinAbsVarIndex) {
1317e8d8bef9SDimitry Andric     // The constant offset will have added at least +/-MinAbsVarIndex to it.
1318e8d8bef9SDimitry Andric     APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1319e8d8bef9SDimitry Andric     APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1320349cc55cSDimitry Andric     // We know that Offset <= OffsetLo || Offset >= OffsetHi
1321e8d8bef9SDimitry Andric     if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1322e8d8bef9SDimitry Andric         OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1323fe6060f1SDimitry Andric       return AliasResult::NoAlias;
1324e8d8bef9SDimitry Andric   }
13250b57cec5SDimitry Andric 
1326349cc55cSDimitry Andric   if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT))
1327fe6060f1SDimitry Andric     return AliasResult::NoAlias;
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   // Statically, we can see that the base objects are the same, but the
13300b57cec5SDimitry Andric   // pointers have dynamic offsets which we can't resolve. And none of our
13310b57cec5SDimitry Andric   // little tricks above worked.
1332fe6060f1SDimitry Andric   return AliasResult::MayAlias;
13330b57cec5SDimitry Andric }
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
13360b57cec5SDimitry Andric   // If the results agree, take it.
13370b57cec5SDimitry Andric   if (A == B)
13380b57cec5SDimitry Andric     return A;
13390b57cec5SDimitry Andric   // A mix of PartialAlias and MustAlias is PartialAlias.
1340fe6060f1SDimitry Andric   if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||
1341fe6060f1SDimitry Andric       (B == AliasResult::PartialAlias && A == AliasResult::MustAlias))
1342fe6060f1SDimitry Andric     return AliasResult::PartialAlias;
13430b57cec5SDimitry Andric   // Otherwise, we don't know anything.
1344fe6060f1SDimitry Andric   return AliasResult::MayAlias;
13450b57cec5SDimitry Andric }
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
13480b57cec5SDimitry Andric /// against another.
13490b57cec5SDimitry Andric AliasResult
13500b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1351fe6060f1SDimitry Andric                            const Value *V2, LocationSize V2Size,
1352e8d8bef9SDimitry Andric                            AAQueryInfo &AAQI) {
13530b57cec5SDimitry Andric   // If the values are Selects with the same condition, we can do a more precise
13540b57cec5SDimitry Andric   // check: just check for aliases between the values on corresponding arms.
13550b57cec5SDimitry Andric   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
13560b57cec5SDimitry Andric     if (SI->getCondition() == SI2->getCondition()) {
1357e8d8bef9SDimitry Andric       AliasResult Alias = getBestAAResults().alias(
1358fe6060f1SDimitry Andric           MemoryLocation(SI->getTrueValue(), SISize),
1359fe6060f1SDimitry Andric           MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1360fe6060f1SDimitry Andric       if (Alias == AliasResult::MayAlias)
1361fe6060f1SDimitry Andric         return AliasResult::MayAlias;
1362e8d8bef9SDimitry Andric       AliasResult ThisAlias = getBestAAResults().alias(
1363fe6060f1SDimitry Andric           MemoryLocation(SI->getFalseValue(), SISize),
1364fe6060f1SDimitry Andric           MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
13650b57cec5SDimitry Andric       return MergeAliasResults(ThisAlias, Alias);
13660b57cec5SDimitry Andric     }
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // If both arms of the Select node NoAlias or MustAlias V2, then returns
13690b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1370e8d8bef9SDimitry Andric   AliasResult Alias = getBestAAResults().alias(
1371fe6060f1SDimitry Andric       MemoryLocation(V2, V2Size),
1372fe6060f1SDimitry Andric       MemoryLocation(SI->getTrueValue(), SISize), AAQI);
1373fe6060f1SDimitry Andric   if (Alias == AliasResult::MayAlias)
1374fe6060f1SDimitry Andric     return AliasResult::MayAlias;
13750b57cec5SDimitry Andric 
1376e8d8bef9SDimitry Andric   AliasResult ThisAlias = getBestAAResults().alias(
1377fe6060f1SDimitry Andric       MemoryLocation(V2, V2Size),
1378fe6060f1SDimitry Andric       MemoryLocation(SI->getFalseValue(), SISize), AAQI);
13790b57cec5SDimitry Andric   return MergeAliasResults(ThisAlias, Alias);
13800b57cec5SDimitry Andric }
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
13830b57cec5SDimitry Andric /// another.
13840b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1385fe6060f1SDimitry Andric                                     const Value *V2, LocationSize V2Size,
1386e8d8bef9SDimitry Andric                                     AAQueryInfo &AAQI) {
1387fe6060f1SDimitry Andric   if (!PN->getNumIncomingValues())
1388fe6060f1SDimitry Andric     return AliasResult::NoAlias;
13890b57cec5SDimitry Andric   // If the values are PHIs in the same block, we can do a more precise
13900b57cec5SDimitry Andric   // as well as efficient check: just check for aliases between the values
13910b57cec5SDimitry Andric   // on corresponding edges.
13920b57cec5SDimitry Andric   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
13930b57cec5SDimitry Andric     if (PN2->getParent() == PN->getParent()) {
1394e8d8bef9SDimitry Andric       Optional<AliasResult> Alias;
13950b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1396e8d8bef9SDimitry Andric         AliasResult ThisAlias = getBestAAResults().alias(
1397fe6060f1SDimitry Andric             MemoryLocation(PN->getIncomingValue(i), PNSize),
1398e8d8bef9SDimitry Andric             MemoryLocation(
1399fe6060f1SDimitry Andric                 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1400e8d8bef9SDimitry Andric             AAQI);
1401e8d8bef9SDimitry Andric         if (Alias)
1402e8d8bef9SDimitry Andric           *Alias = MergeAliasResults(*Alias, ThisAlias);
1403e8d8bef9SDimitry Andric         else
1404e8d8bef9SDimitry Andric           Alias = ThisAlias;
1405fe6060f1SDimitry Andric         if (*Alias == AliasResult::MayAlias)
14060b57cec5SDimitry Andric           break;
14070b57cec5SDimitry Andric       }
1408e8d8bef9SDimitry Andric       return *Alias;
14090b57cec5SDimitry Andric     }
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   SmallVector<Value *, 4> V1Srcs;
1412e8d8bef9SDimitry Andric   // If a phi operand recurses back to the phi, we can still determine NoAlias
1413e8d8bef9SDimitry Andric   // if we don't alias the underlying objects of the other phi operands, as we
1414e8d8bef9SDimitry Andric   // know that the recursive phi needs to be based on them in some way.
14150b57cec5SDimitry Andric   bool isRecursive = false;
1416979e22ffSDimitry Andric   auto CheckForRecPhi = [&](Value *PV) {
1417979e22ffSDimitry Andric     if (!EnableRecPhiAnalysis)
1418979e22ffSDimitry Andric       return false;
1419e8d8bef9SDimitry Andric     if (getUnderlyingObject(PV) == PN) {
1420979e22ffSDimitry Andric       isRecursive = true;
1421979e22ffSDimitry Andric       return true;
1422979e22ffSDimitry Andric     }
1423979e22ffSDimitry Andric     return false;
1424979e22ffSDimitry Andric   };
1425979e22ffSDimitry Andric 
14260b57cec5SDimitry Andric   if (PV) {
14270b57cec5SDimitry Andric     // If we have PhiValues then use it to get the underlying phi values.
14280b57cec5SDimitry Andric     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
14290b57cec5SDimitry Andric     // If we have more phi values than the search depth then return MayAlias
14300b57cec5SDimitry Andric     // conservatively to avoid compile time explosion. The worst possible case
14310b57cec5SDimitry Andric     // is if both sides are PHI nodes. In which case, this is O(m x n) time
14320b57cec5SDimitry Andric     // where 'm' and 'n' are the number of PHI sources.
14330b57cec5SDimitry Andric     if (PhiValueSet.size() > MaxLookupSearchDepth)
1434fe6060f1SDimitry Andric       return AliasResult::MayAlias;
14350b57cec5SDimitry Andric     // Add the values to V1Srcs
14360b57cec5SDimitry Andric     for (Value *PV1 : PhiValueSet) {
1437979e22ffSDimitry Andric       if (CheckForRecPhi(PV1))
14380b57cec5SDimitry Andric         continue;
14390b57cec5SDimitry Andric       V1Srcs.push_back(PV1);
14400b57cec5SDimitry Andric     }
14410b57cec5SDimitry Andric   } else {
14420b57cec5SDimitry Andric     // If we don't have PhiInfo then just look at the operands of the phi itself
14430b57cec5SDimitry Andric     // FIXME: Remove this once we can guarantee that we have PhiInfo always
14440b57cec5SDimitry Andric     SmallPtrSet<Value *, 4> UniqueSrc;
1445fe6060f1SDimitry Andric     Value *OnePhi = nullptr;
14460b57cec5SDimitry Andric     for (Value *PV1 : PN->incoming_values()) {
1447fe6060f1SDimitry Andric       if (isa<PHINode>(PV1)) {
1448fe6060f1SDimitry Andric         if (OnePhi && OnePhi != PV1) {
1449fe6060f1SDimitry Andric           // To control potential compile time explosion, we choose to be
1450fe6060f1SDimitry Andric           // conserviate when we have more than one Phi input.  It is important
1451fe6060f1SDimitry Andric           // that we handle the single phi case as that lets us handle LCSSA
1452fe6060f1SDimitry Andric           // phi nodes and (combined with the recursive phi handling) simple
1453fe6060f1SDimitry Andric           // pointer induction variable patterns.
1454fe6060f1SDimitry Andric           return AliasResult::MayAlias;
1455fe6060f1SDimitry Andric         }
1456fe6060f1SDimitry Andric         OnePhi = PV1;
1457fe6060f1SDimitry Andric       }
14580b57cec5SDimitry Andric 
1459979e22ffSDimitry Andric       if (CheckForRecPhi(PV1))
14600b57cec5SDimitry Andric         continue;
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric       if (UniqueSrc.insert(PV1).second)
14630b57cec5SDimitry Andric         V1Srcs.push_back(PV1);
14640b57cec5SDimitry Andric     }
1465fe6060f1SDimitry Andric 
1466fe6060f1SDimitry Andric     if (OnePhi && UniqueSrc.size() > 1)
1467fe6060f1SDimitry Andric       // Out of an abundance of caution, allow only the trivial lcssa and
1468fe6060f1SDimitry Andric       // recursive phi cases.
1469fe6060f1SDimitry Andric       return AliasResult::MayAlias;
14700b57cec5SDimitry Andric   }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   // If V1Srcs is empty then that means that the phi has no underlying non-phi
14730b57cec5SDimitry Andric   // value. This should only be possible in blocks unreachable from the entry
14740b57cec5SDimitry Andric   // block, but return MayAlias just in case.
14750b57cec5SDimitry Andric   if (V1Srcs.empty())
1476fe6060f1SDimitry Andric     return AliasResult::MayAlias;
14770b57cec5SDimitry Andric 
1478e8d8bef9SDimitry Andric   // If this PHI node is recursive, indicate that the pointer may be moved
1479e8d8bef9SDimitry Andric   // across iterations. We can only prove NoAlias if different underlying
1480e8d8bef9SDimitry Andric   // objects are involved.
14810b57cec5SDimitry Andric   if (isRecursive)
1482e8d8bef9SDimitry Andric     PNSize = LocationSize::beforeOrAfterPointer();
14830b57cec5SDimitry Andric 
1484e8d8bef9SDimitry Andric   // In the recursive alias queries below, we may compare values from two
1485e8d8bef9SDimitry Andric   // different loop iterations. Keep track of visited phi blocks, which will
1486e8d8bef9SDimitry Andric   // be used when determining value equivalence.
1487e8d8bef9SDimitry Andric   bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second;
1488e8d8bef9SDimitry Andric   auto _ = make_scope_exit([&]() {
1489e8d8bef9SDimitry Andric     if (BlockInserted)
1490e8d8bef9SDimitry Andric       VisitedPhiBBs.erase(PN->getParent());
1491e8d8bef9SDimitry Andric   });
1492e8d8bef9SDimitry Andric 
1493e8d8bef9SDimitry Andric   // If we inserted a block into VisitedPhiBBs, alias analysis results that
1494e8d8bef9SDimitry Andric   // have been cached earlier may no longer be valid. Perform recursive queries
1495e8d8bef9SDimitry Andric   // with a new AAQueryInfo.
1496fe6060f1SDimitry Andric   AAQueryInfo NewAAQI = AAQI.withEmptyCache();
1497e8d8bef9SDimitry Andric   AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI;
1498e8d8bef9SDimitry Andric 
1499e8d8bef9SDimitry Andric   AliasResult Alias = getBestAAResults().alias(
1500fe6060f1SDimitry Andric       MemoryLocation(V2, V2Size),
1501fe6060f1SDimitry Andric       MemoryLocation(V1Srcs[0], PNSize), *UseAAQI);
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   // Early exit if the check of the first PHI source against V2 is MayAlias.
15040b57cec5SDimitry Andric   // Other results are not possible.
1505fe6060f1SDimitry Andric   if (Alias == AliasResult::MayAlias)
1506fe6060f1SDimitry Andric     return AliasResult::MayAlias;
15075ffd83dbSDimitry Andric   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
15085ffd83dbSDimitry Andric   // remain valid to all elements and needs to conservatively return MayAlias.
1509fe6060f1SDimitry Andric   if (isRecursive && Alias != AliasResult::NoAlias)
1510fe6060f1SDimitry Andric     return AliasResult::MayAlias;
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
15130b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
15140b57cec5SDimitry Andric   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
15150b57cec5SDimitry Andric     Value *V = V1Srcs[i];
15160b57cec5SDimitry Andric 
1517e8d8bef9SDimitry Andric     AliasResult ThisAlias = getBestAAResults().alias(
1518fe6060f1SDimitry Andric         MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI);
15190b57cec5SDimitry Andric     Alias = MergeAliasResults(ThisAlias, Alias);
1520fe6060f1SDimitry Andric     if (Alias == AliasResult::MayAlias)
15210b57cec5SDimitry Andric       break;
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric   return Alias;
15250b57cec5SDimitry Andric }
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
15280b57cec5SDimitry Andric /// array references.
15290b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1530e8d8bef9SDimitry Andric                                       const Value *V2, LocationSize V2Size,
1531e8d8bef9SDimitry Andric                                       AAQueryInfo &AAQI) {
15320b57cec5SDimitry Andric   // If either of the memory references is empty, it doesn't matter what the
15330b57cec5SDimitry Andric   // pointer values are.
15340b57cec5SDimitry Andric   if (V1Size.isZero() || V2Size.isZero())
1535fe6060f1SDimitry Andric     return AliasResult::NoAlias;
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric   // Strip off any casts if they exist.
1538fe6060f1SDimitry Andric   V1 = V1->stripPointerCastsForAliasAnalysis();
1539fe6060f1SDimitry Andric   V2 = V2->stripPointerCastsForAliasAnalysis();
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
15420b57cec5SDimitry Andric   // value for undef that aliases nothing in the program.
15430b57cec5SDimitry Andric   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1544fe6060f1SDimitry Andric     return AliasResult::NoAlias;
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric   // Are we checking for alias of the same value?
15470b57cec5SDimitry Andric   // Because we look 'through' phi nodes, we could look at "Value" pointers from
15480b57cec5SDimitry Andric   // different iterations. We must therefore make sure that this is not the
15490b57cec5SDimitry Andric   // case. The function isValueEqualInPotentialCycles ensures that this cannot
15500b57cec5SDimitry Andric   // happen by looking at the visited phi nodes and making sure they cannot
15510b57cec5SDimitry Andric   // reach the value.
15520b57cec5SDimitry Andric   if (isValueEqualInPotentialCycles(V1, V2))
1553fe6060f1SDimitry Andric     return AliasResult::MustAlias;
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1556fe6060f1SDimitry Andric     return AliasResult::NoAlias; // Scalars cannot alias each other
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // Figure out what objects these things are pointing to if we can.
1559e8d8bef9SDimitry Andric   const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1560e8d8bef9SDimitry Andric   const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   // Null values in the default address space don't point to any object, so they
15630b57cec5SDimitry Andric   // don't alias any other pointer.
15640b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
15650b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1566fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15670b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
15680b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1569fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   if (O1 != O2) {
15720b57cec5SDimitry Andric     // If V1/V2 point to two different objects, we know that we have no alias.
15730b57cec5SDimitry Andric     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1574fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric     // Constant pointers can't alias with non-const isIdentifiedObject objects.
15770b57cec5SDimitry Andric     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
15780b57cec5SDimitry Andric         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1579fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric     // Function arguments can't alias with things that are known to be
15820b57cec5SDimitry Andric     // unambigously identified at the function level.
15830b57cec5SDimitry Andric     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
15840b57cec5SDimitry Andric         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1585fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric     // If one pointer is the result of a call/invoke or load and the other is a
15880b57cec5SDimitry Andric     // non-escaping local object within the same function, then we know the
15890b57cec5SDimitry Andric     // object couldn't escape to a point where the call could return it.
15900b57cec5SDimitry Andric     //
15910b57cec5SDimitry Andric     // Note that if the pointers are in different functions, there are a
15920b57cec5SDimitry Andric     // variety of complications. A call with a nocapture argument may still
15930b57cec5SDimitry Andric     // temporary store the nocapture argument's value in a temporary memory
15940b57cec5SDimitry Andric     // location if that memory location doesn't escape. Or it may pass a
15950b57cec5SDimitry Andric     // nocapture value to other functions as long as they don't capture it.
15960b57cec5SDimitry Andric     if (isEscapeSource(O1) &&
1597349cc55cSDimitry Andric         AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1)))
1598fe6060f1SDimitry Andric       return AliasResult::NoAlias;
15990b57cec5SDimitry Andric     if (isEscapeSource(O2) &&
1600349cc55cSDimitry Andric         AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2)))
1601fe6060f1SDimitry Andric       return AliasResult::NoAlias;
16020b57cec5SDimitry Andric   }
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   // If the size of one access is larger than the entire object on the other
16050b57cec5SDimitry Andric   // side, then we know such behavior is undefined and can assume no alias.
16060b57cec5SDimitry Andric   bool NullIsValidLocation = NullPointerIsDefined(&F);
16078bcb0991SDimitry Andric   if ((isObjectSmallerThan(
16088bcb0991SDimitry Andric           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
16098bcb0991SDimitry Andric           TLI, NullIsValidLocation)) ||
16108bcb0991SDimitry Andric       (isObjectSmallerThan(
16118bcb0991SDimitry Andric           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
16128bcb0991SDimitry Andric           TLI, NullIsValidLocation)))
1613fe6060f1SDimitry Andric     return AliasResult::NoAlias;
16140b57cec5SDimitry Andric 
1615e8d8bef9SDimitry Andric   // If one the accesses may be before the accessed pointer, canonicalize this
1616e8d8bef9SDimitry Andric   // by using unknown after-pointer sizes for both accesses. This is
1617e8d8bef9SDimitry Andric   // equivalent, because regardless of which pointer is lower, one of them
1618e8d8bef9SDimitry Andric   // will always came after the other, as long as the underlying objects aren't
1619e8d8bef9SDimitry Andric   // disjoint. We do this so that the rest of BasicAA does not have to deal
1620e8d8bef9SDimitry Andric   // with accesses before the base pointer, and to improve cache utilization by
1621e8d8bef9SDimitry Andric   // merging equivalent states.
1622e8d8bef9SDimitry Andric   if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1623e8d8bef9SDimitry Andric     V1Size = LocationSize::afterPointer();
1624e8d8bef9SDimitry Andric     V2Size = LocationSize::afterPointer();
1625e8d8bef9SDimitry Andric   }
1626e8d8bef9SDimitry Andric 
1627fe6060f1SDimitry Andric   // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1628fe6060f1SDimitry Andric   // for recursive queries. For this reason, this limit is chosen to be large
1629fe6060f1SDimitry Andric   // enough to be very rarely hit, while still being small enough to avoid
1630fe6060f1SDimitry Andric   // stack overflows.
1631fe6060f1SDimitry Andric   if (AAQI.Depth >= 512)
1632fe6060f1SDimitry Andric     return AliasResult::MayAlias;
1633fe6060f1SDimitry Andric 
16340b57cec5SDimitry Andric   // Check the cache before climbing up use-def chains. This also terminates
16350b57cec5SDimitry Andric   // otherwise infinitely recursive queries.
1636fe6060f1SDimitry Andric   AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size});
1637fe6060f1SDimitry Andric   const bool Swapped = V1 > V2;
1638fe6060f1SDimitry Andric   if (Swapped)
16390b57cec5SDimitry Andric     std::swap(Locs.first, Locs.second);
1640e8d8bef9SDimitry Andric   const auto &Pair = AAQI.AliasCache.try_emplace(
1641fe6060f1SDimitry Andric       Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});
1642e8d8bef9SDimitry Andric   if (!Pair.second) {
1643e8d8bef9SDimitry Andric     auto &Entry = Pair.first->second;
1644e8d8bef9SDimitry Andric     if (!Entry.isDefinitive()) {
1645e8d8bef9SDimitry Andric       // Remember that we used an assumption.
1646e8d8bef9SDimitry Andric       ++Entry.NumAssumptionUses;
1647e8d8bef9SDimitry Andric       ++AAQI.NumAssumptionUses;
16480b57cec5SDimitry Andric     }
1649fe6060f1SDimitry Andric     // Cache contains sorted {V1,V2} pairs but we should return original order.
1650fe6060f1SDimitry Andric     auto Result = Entry.Result;
1651fe6060f1SDimitry Andric     Result.swap(Swapped);
1652fe6060f1SDimitry Andric     return Result;
1653e8d8bef9SDimitry Andric   }
1654e8d8bef9SDimitry Andric 
1655e8d8bef9SDimitry Andric   int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1656e8d8bef9SDimitry Andric   unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1657fe6060f1SDimitry Andric   AliasResult Result =
1658fe6060f1SDimitry Andric       aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1659e8d8bef9SDimitry Andric 
1660e8d8bef9SDimitry Andric   auto It = AAQI.AliasCache.find(Locs);
1661e8d8bef9SDimitry Andric   assert(It != AAQI.AliasCache.end() && "Must be in cache");
1662e8d8bef9SDimitry Andric   auto &Entry = It->second;
1663e8d8bef9SDimitry Andric 
1664e8d8bef9SDimitry Andric   // Check whether a NoAlias assumption has been used, but disproven.
1665fe6060f1SDimitry Andric   bool AssumptionDisproven =
1666fe6060f1SDimitry Andric       Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1667e8d8bef9SDimitry Andric   if (AssumptionDisproven)
1668fe6060f1SDimitry Andric     Result = AliasResult::MayAlias;
1669e8d8bef9SDimitry Andric 
1670e8d8bef9SDimitry Andric   // This is a definitive result now, when considered as a root query.
1671e8d8bef9SDimitry Andric   AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1672e8d8bef9SDimitry Andric   Entry.Result = Result;
1673fe6060f1SDimitry Andric   // Cache contains sorted {V1,V2} pairs.
1674fe6060f1SDimitry Andric   Entry.Result.swap(Swapped);
1675e8d8bef9SDimitry Andric   Entry.NumAssumptionUses = -1;
1676e8d8bef9SDimitry Andric 
1677e8d8bef9SDimitry Andric   // If the assumption has been disproven, remove any results that may have
1678e8d8bef9SDimitry Andric   // been based on this assumption. Do this after the Entry updates above to
1679e8d8bef9SDimitry Andric   // avoid iterator invalidation.
1680e8d8bef9SDimitry Andric   if (AssumptionDisproven)
1681e8d8bef9SDimitry Andric     while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1682e8d8bef9SDimitry Andric       AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());
1683e8d8bef9SDimitry Andric 
1684e8d8bef9SDimitry Andric   // The result may still be based on assumptions higher up in the chain.
1685e8d8bef9SDimitry Andric   // Remember it, so it can be purged from the cache later.
1686fe6060f1SDimitry Andric   if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1687fe6060f1SDimitry Andric       Result != AliasResult::MayAlias)
1688e8d8bef9SDimitry Andric     AAQI.AssumptionBasedResults.push_back(Locs);
1689e8d8bef9SDimitry Andric   return Result;
1690e8d8bef9SDimitry Andric }
1691e8d8bef9SDimitry Andric 
1692e8d8bef9SDimitry Andric AliasResult BasicAAResult::aliasCheckRecursive(
1693fe6060f1SDimitry Andric     const Value *V1, LocationSize V1Size,
1694fe6060f1SDimitry Andric     const Value *V2, LocationSize V2Size,
1695e8d8bef9SDimitry Andric     AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
16960b57cec5SDimitry Andric   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1697fe6060f1SDimitry Andric     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1698fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
1699e8d8bef9SDimitry Andric       return Result;
1700e8d8bef9SDimitry Andric   } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1701fe6060f1SDimitry Andric     AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
17020eae32dcSDimitry Andric     Result.swap();
1703fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
17040b57cec5SDimitry Andric       return Result;
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1708fe6060f1SDimitry Andric     AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1709fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
1710e8d8bef9SDimitry Andric       return Result;
1711e8d8bef9SDimitry Andric   } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1712fe6060f1SDimitry Andric     AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
17130eae32dcSDimitry Andric     Result.swap();
1714fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
1715e8d8bef9SDimitry Andric       return Result;
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1719fe6060f1SDimitry Andric     AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1720fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
1721e8d8bef9SDimitry Andric       return Result;
1722e8d8bef9SDimitry Andric   } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1723fe6060f1SDimitry Andric     AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);
17240eae32dcSDimitry Andric     Result.swap();
1725fe6060f1SDimitry Andric     if (Result != AliasResult::MayAlias)
1726e8d8bef9SDimitry Andric       return Result;
17270b57cec5SDimitry Andric   }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   // If both pointers are pointing into the same object and one of them
17300b57cec5SDimitry Andric   // accesses the entire object, then the accesses must overlap in some way.
1731e8d8bef9SDimitry Andric   if (O1 == O2) {
1732e8d8bef9SDimitry Andric     bool NullIsValidLocation = NullPointerIsDefined(&F);
17330b57cec5SDimitry Andric     if (V1Size.isPrecise() && V2Size.isPrecise() &&
17340b57cec5SDimitry Andric         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1735e8d8bef9SDimitry Andric          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1736fe6060f1SDimitry Andric       return AliasResult::PartialAlias;
17370b57cec5SDimitry Andric   }
17380b57cec5SDimitry Andric 
1739fe6060f1SDimitry Andric   return AliasResult::MayAlias;
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent.
17430b57cec5SDimitry Andric ///
17440b57cec5SDimitry Andric /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
17450b57cec5SDimitry Andric /// they can not be part of a cycle in the value graph by looking at all
17460b57cec5SDimitry Andric /// visited phi nodes an making sure that the phis cannot reach the value. We
17470b57cec5SDimitry Andric /// have to do this because we are looking through phi nodes (That is we say
17480b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
17490b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
17500b57cec5SDimitry Andric                                                   const Value *V2) {
17510b57cec5SDimitry Andric   if (V != V2)
17520b57cec5SDimitry Andric     return false;
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric   const Instruction *Inst = dyn_cast<Instruction>(V);
17550b57cec5SDimitry Andric   if (!Inst)
17560b57cec5SDimitry Andric     return true;
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   if (VisitedPhiBBs.empty())
17590b57cec5SDimitry Andric     return true;
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
17620b57cec5SDimitry Andric     return false;
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric   // Make sure that the visited phis cannot reach the Value. This ensures that
17650b57cec5SDimitry Andric   // the Values cannot come from different iterations of a potential cycle the
17660b57cec5SDimitry Andric   // phi nodes could be involved in.
17670b57cec5SDimitry Andric   for (auto *P : VisitedPhiBBs)
1768fe6060f1SDimitry Andric     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT))
17690b57cec5SDimitry Andric       return false;
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   return true;
17720b57cec5SDimitry Andric }
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs.
1775349cc55cSDimitry Andric void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1776349cc55cSDimitry Andric                                            const DecomposedGEP &SrcGEP) {
1777349cc55cSDimitry Andric   DestGEP.Offset -= SrcGEP.Offset;
1778349cc55cSDimitry Andric   for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
17790b57cec5SDimitry Andric     // Find V in Dest.  This is N^2, but pointer indices almost never have more
17800b57cec5SDimitry Andric     // than a few variable indexes.
1781349cc55cSDimitry Andric     bool Found = false;
1782349cc55cSDimitry Andric     for (auto I : enumerate(DestGEP.VarIndices)) {
1783349cc55cSDimitry Andric       VariableGEPIndex &Dest = I.value();
1784349cc55cSDimitry Andric       if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) ||
1785349cc55cSDimitry Andric           !Dest.Val.hasSameCastsAs(Src.Val))
17860b57cec5SDimitry Andric         continue;
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric       // If we found it, subtract off Scale V's from the entry in Dest.  If it
17890b57cec5SDimitry Andric       // goes to zero, remove the entry.
1790349cc55cSDimitry Andric       if (Dest.Scale != Src.Scale) {
1791349cc55cSDimitry Andric         Dest.Scale -= Src.Scale;
1792349cc55cSDimitry Andric         Dest.IsNSW = false;
1793349cc55cSDimitry Andric       } else {
1794349cc55cSDimitry Andric         DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());
1795349cc55cSDimitry Andric       }
1796349cc55cSDimitry Andric       Found = true;
17970b57cec5SDimitry Andric       break;
17980b57cec5SDimitry Andric     }
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric     // If we didn't consume this entry, add it to the end of the Dest list.
1801349cc55cSDimitry Andric     if (!Found) {
1802349cc55cSDimitry Andric       VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW};
1803349cc55cSDimitry Andric       DestGEP.VarIndices.push_back(Entry);
18040b57cec5SDimitry Andric     }
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric }
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric bool BasicAAResult::constantOffsetHeuristic(
1809349cc55cSDimitry Andric     const DecomposedGEP &GEP, LocationSize MaybeV1Size,
1810349cc55cSDimitry Andric     LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) {
1811349cc55cSDimitry Andric   if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
1812e8d8bef9SDimitry Andric       !MaybeV2Size.hasValue())
18130b57cec5SDimitry Andric     return false;
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
18160b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
18170b57cec5SDimitry Andric 
1818349cc55cSDimitry Andric   const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
18190b57cec5SDimitry Andric 
1820349cc55cSDimitry Andric   if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||
1821349cc55cSDimitry Andric       Var0.Scale != -Var1.Scale ||
1822349cc55cSDimitry Andric       Var0.Val.V->getType() != Var1.Val.V->getType())
18230b57cec5SDimitry Andric     return false;
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   // We'll strip off the Extensions of Var0 and Var1 and do another round
18260b57cec5SDimitry Andric   // of GetLinearExpression decomposition. In the example above, if Var0
18270b57cec5SDimitry Andric   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
18280b57cec5SDimitry Andric 
1829fe6060f1SDimitry Andric   LinearExpression E0 =
1830349cc55cSDimitry Andric       GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);
1831fe6060f1SDimitry Andric   LinearExpression E1 =
1832349cc55cSDimitry Andric       GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
1833349cc55cSDimitry Andric   if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
1834fe6060f1SDimitry Andric       !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V))
18350b57cec5SDimitry Andric     return false;
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric   // We have a hit - Var0 and Var1 only differ by a constant offset!
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // If we've been sext'ed then zext'd the maximum difference between Var0 and
18400b57cec5SDimitry Andric   // Var1 is possible to calculate, but we're just interested in the absolute
18410b57cec5SDimitry Andric   // minimum difference between the two. The minimum distance may occur due to
18420b57cec5SDimitry Andric   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
18430b57cec5SDimitry Andric   // the minimum distance between %i and %i + 5 is 3.
1844fe6060f1SDimitry Andric   APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
18450b57cec5SDimitry Andric   MinDiff = APIntOps::umin(MinDiff, Wrapped);
18460b57cec5SDimitry Andric   APInt MinDiffBytes =
18470b57cec5SDimitry Andric     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
18500b57cec5SDimitry Andric   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
18510b57cec5SDimitry Andric   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
18520b57cec5SDimitry Andric   // V2Size can fit in the MinDiffBytes gap.
1853349cc55cSDimitry Andric   return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&
1854349cc55cSDimitry Andric          MinDiffBytes.uge(V2Size + GEP.Offset.abs());
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18580b57cec5SDimitry Andric // BasicAliasAnalysis Pass
18590b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric AnalysisKey BasicAA::Key;
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1864e8d8bef9SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1865e8d8bef9SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1866e8d8bef9SDimitry Andric   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1867e8d8bef9SDimitry Andric   auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F);
1868fe6060f1SDimitry Andric   return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV);
18690b57cec5SDimitry Andric }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
18720b57cec5SDimitry Andric   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
18730b57cec5SDimitry Andric }
18740b57cec5SDimitry Andric 
18750b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0;
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {}
18780b57cec5SDimitry Andric 
18795ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
1880*b32fb2a4SDimitry Andric                       "Basic Alias Analysis (stateless AA impl)", true, true)
18810b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
18820b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
18830b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1884*b32fb2a4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
18855ffd83dbSDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
1886*b32fb2a4SDimitry Andric                     "Basic Alias Analysis (stateless AA impl)", true, true)
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() {
18890b57cec5SDimitry Andric   return new BasicAAWrapperPass();
18900b57cec5SDimitry Andric }
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) {
18930b57cec5SDimitry Andric   auto &ACT = getAnalysis<AssumptionCacheTracker>();
18940b57cec5SDimitry Andric   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
18950b57cec5SDimitry Andric   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
18960b57cec5SDimitry Andric   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
18970b57cec5SDimitry Andric 
18988bcb0991SDimitry Andric   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
18998bcb0991SDimitry Andric                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
19008bcb0991SDimitry Andric                                  &DTWP.getDomTree(),
19010b57cec5SDimitry Andric                                  PVWP ? &PVWP->getResult() : nullptr));
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric   return false;
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
19070b57cec5SDimitry Andric   AU.setPreservesAll();
1908e8d8bef9SDimitry Andric   AU.addRequiredTransitive<AssumptionCacheTracker>();
1909e8d8bef9SDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1910e8d8bef9SDimitry Andric   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
19110b57cec5SDimitry Andric   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
19150b57cec5SDimitry Andric   return BasicAAResult(
19168bcb0991SDimitry Andric       F.getParent()->getDataLayout(), F,
19178bcb0991SDimitry Andric       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
19180b57cec5SDimitry Andric       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
19190b57cec5SDimitry Andric }
1920