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"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.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"
340b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
360b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
370b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
380b57cec5SDimitry Andric #include "llvm/IR/Function.h"
390b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
400b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
410b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
420b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
430b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
450b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
460b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
470b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
480b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
490b57cec5SDimitry Andric #include "llvm/IR/Type.h"
500b57cec5SDimitry Andric #include "llvm/IR/User.h"
510b57cec5SDimitry Andric #include "llvm/IR/Value.h"
52480093f4SDimitry Andric #include "llvm/InitializePasses.h"
530b57cec5SDimitry Andric #include "llvm/Pass.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
570b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
580b57cec5SDimitry Andric #include <cassert>
590b57cec5SDimitry Andric #include <cstdint>
600b57cec5SDimitry Andric #include <cstdlib>
610b57cec5SDimitry Andric #include <utility>
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric #define DEBUG_TYPE "basicaa"
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace llvm;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// Enable analysis of recursive PHI nodes.
680b57cec5SDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
690b57cec5SDimitry Andric                                           cl::init(false));
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric /// By default, even on 32-bit architectures we use 64-bit integers for
720b57cec5SDimitry Andric /// calculations. This will allow us to more-aggressively decompose indexing
730b57cec5SDimitry Andric /// expressions calculated using i64 values (e.g., long long in C) which is
740b57cec5SDimitry Andric /// common enough to worry about.
750b57cec5SDimitry Andric static cl::opt<bool> ForceAtLeast64Bits("basicaa-force-at-least-64b",
760b57cec5SDimitry Andric                                         cl::Hidden, cl::init(true));
770b57cec5SDimitry Andric static cl::opt<bool> DoubleCalcBits("basicaa-double-calc-bits",
780b57cec5SDimitry Andric                                     cl::Hidden, cl::init(false));
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of
810b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision
820b57cec5SDimitry Andric /// of basic alias analysis.
830b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to "
840b57cec5SDimitry Andric                               "decompose GEPs is reached");
850b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric /// Cutoff after which to stop analysing a set of phi nodes potentially involved
880b57cec5SDimitry Andric /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
890b57cec5SDimitry Andric /// careful with value equivalence. We use reachability to make sure a value
900b57cec5SDimitry Andric /// cannot be involved in a cycle.
910b57cec5SDimitry Andric const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and
940b57cec5SDimitry Andric // GetUnderlyingObject(), both functions need to use the same search
950b57cec5SDimitry Andric // depth otherwise the algorithm in aliasGEP will assert.
960b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
990b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
1000b57cec5SDimitry Andric   // We don't care if this analysis itself is preserved, it has no state. But
1010b57cec5SDimitry Andric   // we need to check that the analyses it depends on have been. Note that we
1020b57cec5SDimitry Andric   // may be created without handles to some analyses and in that case don't
1030b57cec5SDimitry Andric   // depend on them.
1040b57cec5SDimitry Andric   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
1050b57cec5SDimitry Andric       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
1060b57cec5SDimitry Andric       (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)) ||
1070b57cec5SDimitry Andric       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
1080b57cec5SDimitry Andric     return true;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // Otherwise this analysis result remains valid.
1110b57cec5SDimitry Andric   return false;
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1150b57cec5SDimitry Andric // Useful predicates
1160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric /// Returns true if the pointer is to a function-local object that never
1190b57cec5SDimitry Andric /// escapes from the function.
1200b57cec5SDimitry Andric static bool isNonEscapingLocalObject(
1210b57cec5SDimitry Andric     const Value *V,
1220b57cec5SDimitry Andric     SmallDenseMap<const Value *, bool, 8> *IsCapturedCache = nullptr) {
1230b57cec5SDimitry Andric   SmallDenseMap<const Value *, bool, 8>::iterator CacheIt;
1240b57cec5SDimitry Andric   if (IsCapturedCache) {
1250b57cec5SDimitry Andric     bool Inserted;
1260b57cec5SDimitry Andric     std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false});
1270b57cec5SDimitry Andric     if (!Inserted)
1280b57cec5SDimitry Andric       // Found cached result, return it!
1290b57cec5SDimitry Andric       return CacheIt->second;
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   // If this is a local allocation, check to see if it escapes.
1330b57cec5SDimitry Andric   if (isa<AllocaInst>(V) || isNoAliasCall(V)) {
1340b57cec5SDimitry Andric     // Set StoreCaptures to True so that we can assume in our callers that the
1350b57cec5SDimitry Andric     // pointer is not the result of a load instruction. Currently
1360b57cec5SDimitry Andric     // PointerMayBeCaptured doesn't have any special analysis for the
1370b57cec5SDimitry Andric     // StoreCaptures=false case; if it did, our callers could be refined to be
1380b57cec5SDimitry Andric     // more precise.
1390b57cec5SDimitry Andric     auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
1400b57cec5SDimitry Andric     if (IsCapturedCache)
1410b57cec5SDimitry Andric       CacheIt->second = Ret;
1420b57cec5SDimitry Andric     return Ret;
1430b57cec5SDimitry Andric   }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   // If this is an argument that corresponds to a byval or noalias argument,
1460b57cec5SDimitry Andric   // then it has not escaped before entering the function.  Check if it escapes
1470b57cec5SDimitry Andric   // inside the function.
1480b57cec5SDimitry Andric   if (const Argument *A = dyn_cast<Argument>(V))
1490b57cec5SDimitry Andric     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
1500b57cec5SDimitry Andric       // Note even if the argument is marked nocapture, we still need to check
1510b57cec5SDimitry Andric       // for copies made inside the function. The nocapture attribute only
1520b57cec5SDimitry Andric       // specifies that there are no copies made that outlive the function.
1530b57cec5SDimitry Andric       auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
1540b57cec5SDimitry Andric       if (IsCapturedCache)
1550b57cec5SDimitry Andric         CacheIt->second = Ret;
1560b57cec5SDimitry Andric       return Ret;
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   return false;
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric /// Returns true if the pointer is one which would have been considered an
1630b57cec5SDimitry Andric /// escape by isNonEscapingLocalObject.
1640b57cec5SDimitry Andric static bool isEscapeSource(const Value *V) {
1650b57cec5SDimitry Andric   if (isa<CallBase>(V))
1660b57cec5SDimitry Andric     return true;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   if (isa<Argument>(V))
1690b57cec5SDimitry Andric     return true;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   // The load case works because isNonEscapingLocalObject considers all
1720b57cec5SDimitry Andric   // stores to be escapes (it passes true for the StoreCaptures argument
1730b57cec5SDimitry Andric   // to PointerMayBeCaptured).
1740b57cec5SDimitry Andric   if (isa<LoadInst>(V))
1750b57cec5SDimitry Andric     return true;
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   return false;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown.
1810b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
1820b57cec5SDimitry Andric                               const TargetLibraryInfo &TLI,
1830b57cec5SDimitry Andric                               bool NullIsValidLoc,
1840b57cec5SDimitry Andric                               bool RoundToAlign = false) {
1850b57cec5SDimitry Andric   uint64_t Size;
1860b57cec5SDimitry Andric   ObjectSizeOpts Opts;
1870b57cec5SDimitry Andric   Opts.RoundToAlign = RoundToAlign;
1880b57cec5SDimitry Andric   Opts.NullIsUnknownSize = NullIsValidLoc;
1890b57cec5SDimitry Andric   if (getObjectSize(V, Size, DL, &TLI, Opts))
1900b57cec5SDimitry Andric     return Size;
1910b57cec5SDimitry Andric   return MemoryLocation::UnknownSize;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than
1950b57cec5SDimitry Andric /// Size.
1960b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size,
1970b57cec5SDimitry Andric                                 const DataLayout &DL,
1980b57cec5SDimitry Andric                                 const TargetLibraryInfo &TLI,
1990b57cec5SDimitry Andric                                 bool NullIsValidLoc) {
2000b57cec5SDimitry Andric   // Note that the meanings of the "object" are slightly different in the
2010b57cec5SDimitry Andric   // following contexts:
2020b57cec5SDimitry Andric   //    c1: llvm::getObjectSize()
2030b57cec5SDimitry Andric   //    c2: llvm.objectsize() intrinsic
2040b57cec5SDimitry Andric   //    c3: isObjectSmallerThan()
2050b57cec5SDimitry Andric   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
2060b57cec5SDimitry Andric   // refers to the "entire object".
2070b57cec5SDimitry Andric   //
2080b57cec5SDimitry Andric   //  Consider this example:
2090b57cec5SDimitry Andric   //     char *p = (char*)malloc(100)
2100b57cec5SDimitry Andric   //     char *q = p+80;
2110b57cec5SDimitry Andric   //
2120b57cec5SDimitry Andric   //  In the context of c1 and c2, the "object" pointed by q refers to the
2130b57cec5SDimitry Andric   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
2140b57cec5SDimitry Andric   //
2150b57cec5SDimitry Andric   //  However, in the context of c3, the "object" refers to the chunk of memory
2160b57cec5SDimitry Andric   // being allocated. So, the "object" has 100 bytes, and q points to the middle
2170b57cec5SDimitry Andric   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
2180b57cec5SDimitry Andric   // parameter, before the llvm::getObjectSize() is called to get the size of
2190b57cec5SDimitry Andric   // entire object, we should:
2200b57cec5SDimitry Andric   //    - either rewind the pointer q to the base-address of the object in
2210b57cec5SDimitry Andric   //      question (in this case rewind to p), or
2220b57cec5SDimitry Andric   //    - just give up. It is up to caller to make sure the pointer is pointing
2230b57cec5SDimitry Andric   //      to the base address the object.
2240b57cec5SDimitry Andric   //
2250b57cec5SDimitry Andric   // We go for 2nd option for simplicity.
2260b57cec5SDimitry Andric   if (!isIdentifiedObject(V))
2270b57cec5SDimitry Andric     return false;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   // This function needs to use the aligned object size because we allow
2300b57cec5SDimitry Andric   // reads a bit past the end given sufficient alignment.
2310b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
2320b57cec5SDimitry Andric                                       /*RoundToAlign*/ true);
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2378bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object,
2388bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query
2398bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here.
2408bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V,
2418bcb0991SDimitry Andric                                      const LocationSize &LocSize,
2428bcb0991SDimitry Andric                                      const DataLayout &DL,
2438bcb0991SDimitry Andric                                      bool NullIsValidLoc) {
2448bcb0991SDimitry Andric   // If we have dereferenceability information we know a lower bound for the
2458bcb0991SDimitry Andric   // extent as accesses for a lower offset would be valid. We need to exclude
2468bcb0991SDimitry Andric   // the "or null" part if null is a valid pointer.
2478bcb0991SDimitry Andric   bool CanBeNull;
2488bcb0991SDimitry Andric   uint64_t DerefBytes = V.getPointerDereferenceableBytes(DL, CanBeNull);
2498bcb0991SDimitry Andric   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
2508bcb0991SDimitry Andric   // If queried with a precise location size, we assume that location size to be
2518bcb0991SDimitry Andric   // accessed, thus valid.
2528bcb0991SDimitry Andric   if (LocSize.isPrecise())
2538bcb0991SDimitry Andric     DerefBytes = std::max(DerefBytes, LocSize.getValue());
2548bcb0991SDimitry Andric   return DerefBytes;
2558bcb0991SDimitry Andric }
2568bcb0991SDimitry Andric 
2570b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size.
2580b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
2590b57cec5SDimitry Andric                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
2600b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
2610b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2650b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis
2660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and
2690b57cec5SDimitry Andric /// B are constant integers.
2700b57cec5SDimitry Andric ///
2710b57cec5SDimitry Andric /// Returns the scale and offset values as APInts and return V as a Value*, and
2720b57cec5SDimitry Andric /// return whether we looked through any sign or zero extends.  The incoming
2730b57cec5SDimitry Andric /// Value is known to have IntegerType, and it may already be sign or zero
2740b57cec5SDimitry Andric /// extended.
2750b57cec5SDimitry Andric ///
2760b57cec5SDimitry Andric /// Note that this looks through extends, so the high bits may not be
2770b57cec5SDimitry Andric /// represented in the result.
2780b57cec5SDimitry Andric /*static*/ const Value *BasicAAResult::GetLinearExpression(
2790b57cec5SDimitry Andric     const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
2800b57cec5SDimitry Andric     unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
2810b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
2820b57cec5SDimitry Andric   assert(V->getType()->isIntegerTy() && "Not an integer value");
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   // Limit our recursion depth.
2850b57cec5SDimitry Andric   if (Depth == 6) {
2860b57cec5SDimitry Andric     Scale = 1;
2870b57cec5SDimitry Andric     Offset = 0;
2880b57cec5SDimitry Andric     return V;
2890b57cec5SDimitry Andric   }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
2920b57cec5SDimitry Andric     // If it's a constant, just convert it to an offset and remove the variable.
2930b57cec5SDimitry Andric     // If we've been called recursively, the Offset bit width will be greater
2940b57cec5SDimitry Andric     // than the constant's (the Offset's always as wide as the outermost call),
2950b57cec5SDimitry Andric     // so we'll zext here and process any extension in the isa<SExtInst> &
2960b57cec5SDimitry Andric     // isa<ZExtInst> cases below.
2970b57cec5SDimitry Andric     Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
2980b57cec5SDimitry Andric     assert(Scale == 0 && "Constant values don't have a scale");
2990b57cec5SDimitry Andric     return V;
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
3030b57cec5SDimitry Andric     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
3040b57cec5SDimitry Andric       // If we've been called recursively, then Offset and Scale will be wider
3050b57cec5SDimitry Andric       // than the BOp operands. We'll always zext it here as we'll process sign
3060b57cec5SDimitry Andric       // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
3070b57cec5SDimitry Andric       APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric       switch (BOp->getOpcode()) {
3100b57cec5SDimitry Andric       default:
3110b57cec5SDimitry Andric         // We don't understand this instruction, so we can't decompose it any
3120b57cec5SDimitry Andric         // further.
3130b57cec5SDimitry Andric         Scale = 1;
3140b57cec5SDimitry Andric         Offset = 0;
3150b57cec5SDimitry Andric         return V;
3160b57cec5SDimitry Andric       case Instruction::Or:
3170b57cec5SDimitry Andric         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
3180b57cec5SDimitry Andric         // analyze it.
3190b57cec5SDimitry Andric         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
3200b57cec5SDimitry Andric                                BOp, DT)) {
3210b57cec5SDimitry Andric           Scale = 1;
3220b57cec5SDimitry Andric           Offset = 0;
3230b57cec5SDimitry Andric           return V;
3240b57cec5SDimitry Andric         }
3250b57cec5SDimitry Andric         LLVM_FALLTHROUGH;
3260b57cec5SDimitry Andric       case Instruction::Add:
3270b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3280b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3290b57cec5SDimitry Andric         Offset += RHS;
3300b57cec5SDimitry Andric         break;
3310b57cec5SDimitry Andric       case Instruction::Sub:
3320b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3330b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3340b57cec5SDimitry Andric         Offset -= RHS;
3350b57cec5SDimitry Andric         break;
3360b57cec5SDimitry Andric       case Instruction::Mul:
3370b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3380b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3390b57cec5SDimitry Andric         Offset *= RHS;
3400b57cec5SDimitry Andric         Scale *= RHS;
3410b57cec5SDimitry Andric         break;
3420b57cec5SDimitry Andric       case Instruction::Shl:
3430b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3440b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric         // We're trying to linearize an expression of the kind:
3470b57cec5SDimitry Andric         //   shl i8 -128, 36
3480b57cec5SDimitry Andric         // where the shift count exceeds the bitwidth of the type.
3490b57cec5SDimitry Andric         // We can't decompose this further (the expression would return
3500b57cec5SDimitry Andric         // a poison value).
3510b57cec5SDimitry Andric         if (Offset.getBitWidth() < RHS.getLimitedValue() ||
3520b57cec5SDimitry Andric             Scale.getBitWidth() < RHS.getLimitedValue()) {
3530b57cec5SDimitry Andric           Scale = 1;
3540b57cec5SDimitry Andric           Offset = 0;
3550b57cec5SDimitry Andric           return V;
3560b57cec5SDimitry Andric         }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric         Offset <<= RHS.getLimitedValue();
3590b57cec5SDimitry Andric         Scale <<= RHS.getLimitedValue();
3600b57cec5SDimitry Andric         // the semantics of nsw and nuw for left shifts don't match those of
3610b57cec5SDimitry Andric         // multiplications, so we won't propagate them.
3620b57cec5SDimitry Andric         NSW = NUW = false;
3630b57cec5SDimitry Andric         return V;
3640b57cec5SDimitry Andric       }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric       if (isa<OverflowingBinaryOperator>(BOp)) {
3670b57cec5SDimitry Andric         NUW &= BOp->hasNoUnsignedWrap();
3680b57cec5SDimitry Andric         NSW &= BOp->hasNoSignedWrap();
3690b57cec5SDimitry Andric       }
3700b57cec5SDimitry Andric       return V;
3710b57cec5SDimitry Andric     }
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // Since GEP indices are sign extended anyway, we don't care about the high
3750b57cec5SDimitry Andric   // bits of a sign or zero extended value - just scales and offsets.  The
3760b57cec5SDimitry Andric   // extensions have to be consistent though.
3770b57cec5SDimitry Andric   if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
3780b57cec5SDimitry Andric     Value *CastOp = cast<CastInst>(V)->getOperand(0);
3790b57cec5SDimitry Andric     unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
3800b57cec5SDimitry Andric     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
3810b57cec5SDimitry Andric     unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
3820b57cec5SDimitry Andric     const Value *Result =
3830b57cec5SDimitry Andric         GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
3840b57cec5SDimitry Andric                             Depth + 1, AC, DT, NSW, NUW);
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
3870b57cec5SDimitry Andric     // by just incrementing the number of bits we've extended by.
3880b57cec5SDimitry Andric     unsigned ExtendedBy = NewWidth - SmallWidth;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     if (isa<SExtInst>(V) && ZExtBits == 0) {
3910b57cec5SDimitry Andric       // sext(sext(%x, a), b) == sext(%x, a + b)
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric       if (NSW) {
3940b57cec5SDimitry Andric         // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
3950b57cec5SDimitry Andric         // into sext(%x) + sext(c). We'll sext the Offset ourselves:
3960b57cec5SDimitry Andric         unsigned OldWidth = Offset.getBitWidth();
3970b57cec5SDimitry Andric         Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
3980b57cec5SDimitry Andric       } else {
3990b57cec5SDimitry Andric         // We may have signed-wrapped, so don't decompose sext(%x + c) into
4000b57cec5SDimitry Andric         // sext(%x) + sext(c)
4010b57cec5SDimitry Andric         Scale = 1;
4020b57cec5SDimitry Andric         Offset = 0;
4030b57cec5SDimitry Andric         Result = CastOp;
4040b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
4050b57cec5SDimitry Andric         SExtBits = OldSExtBits;
4060b57cec5SDimitry Andric       }
4070b57cec5SDimitry Andric       SExtBits += ExtendedBy;
4080b57cec5SDimitry Andric     } else {
4090b57cec5SDimitry Andric       // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric       if (!NUW) {
4120b57cec5SDimitry Andric         // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
4130b57cec5SDimitry Andric         // zext(%x) + zext(c)
4140b57cec5SDimitry Andric         Scale = 1;
4150b57cec5SDimitry Andric         Offset = 0;
4160b57cec5SDimitry Andric         Result = CastOp;
4170b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
4180b57cec5SDimitry Andric         SExtBits = OldSExtBits;
4190b57cec5SDimitry Andric       }
4200b57cec5SDimitry Andric       ZExtBits += ExtendedBy;
4210b57cec5SDimitry Andric     }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric     return Result;
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   Scale = 1;
4270b57cec5SDimitry Andric   Offset = 0;
4280b57cec5SDimitry Andric   return V;
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric /// To ensure a pointer offset fits in an integer of size PointerSize
4320b57cec5SDimitry Andric /// (in bits) when that size is smaller than the maximum pointer size. This is
4330b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices
4340b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information
4350b57cec5SDimitry Andric /// where the maximum pointer size is 64b.
4360b57cec5SDimitry Andric static APInt adjustToPointerSize(APInt Offset, unsigned PointerSize) {
4370b57cec5SDimitry Andric   assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!");
4380b57cec5SDimitry Andric   unsigned ShiftBits = Offset.getBitWidth() - PointerSize;
4390b57cec5SDimitry Andric   return (Offset << ShiftBits).ashr(ShiftBits);
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric static unsigned getMaxPointerSize(const DataLayout &DL) {
4430b57cec5SDimitry Andric   unsigned MaxPointerSize = DL.getMaxPointerSizeInBits();
4440b57cec5SDimitry Andric   if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64;
4450b57cec5SDimitry Andric   if (DoubleCalcBits) MaxPointerSize *= 2;
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   return MaxPointerSize;
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer
4510b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets.
4520b57cec5SDimitry Andric ///
4530b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
4540b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the
4550b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As
4560b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form.
4570b57cec5SDimitry Andric ///
4580b57cec5SDimitry Andric /// When DataLayout is around, this function is capable of analyzing everything
4590b57cec5SDimitry Andric /// that GetUnderlyingObject can look through. To be able to do that
4600b57cec5SDimitry Andric /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
4610b57cec5SDimitry Andric /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
4620b57cec5SDimitry Andric /// through pointer casts.
4630b57cec5SDimitry Andric bool BasicAAResult::DecomposeGEPExpression(const Value *V,
4640b57cec5SDimitry Andric        DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
4650b57cec5SDimitry Andric        DominatorTree *DT) {
4660b57cec5SDimitry Andric   // Limit recursion depth to limit compile time in crazy cases.
4670b57cec5SDimitry Andric   unsigned MaxLookup = MaxLookupSearchDepth;
4680b57cec5SDimitry Andric   SearchTimes++;
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   unsigned MaxPointerSize = getMaxPointerSize(DL);
4710b57cec5SDimitry Andric   Decomposed.VarIndices.clear();
4720b57cec5SDimitry Andric   do {
4730b57cec5SDimitry Andric     // See if this is a bitcast or GEP.
4740b57cec5SDimitry Andric     const Operator *Op = dyn_cast<Operator>(V);
4750b57cec5SDimitry Andric     if (!Op) {
4760b57cec5SDimitry Andric       // The only non-operator case we can handle are GlobalAliases.
4770b57cec5SDimitry Andric       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
4780b57cec5SDimitry Andric         if (!GA->isInterposable()) {
4790b57cec5SDimitry Andric           V = GA->getAliasee();
4800b57cec5SDimitry Andric           continue;
4810b57cec5SDimitry Andric         }
4820b57cec5SDimitry Andric       }
4830b57cec5SDimitry Andric       Decomposed.Base = V;
4840b57cec5SDimitry Andric       return false;
4850b57cec5SDimitry Andric     }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric     if (Op->getOpcode() == Instruction::BitCast ||
4880b57cec5SDimitry Andric         Op->getOpcode() == Instruction::AddrSpaceCast) {
4890b57cec5SDimitry Andric       V = Op->getOperand(0);
4900b57cec5SDimitry Andric       continue;
4910b57cec5SDimitry Andric     }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
4940b57cec5SDimitry Andric     if (!GEPOp) {
4950b57cec5SDimitry Andric       if (const auto *Call = dyn_cast<CallBase>(V)) {
4960b57cec5SDimitry Andric         // CaptureTracking can know about special capturing properties of some
4970b57cec5SDimitry Andric         // intrinsics like launder.invariant.group, that can't be expressed with
4980b57cec5SDimitry Andric         // the attributes, but have properties like returning aliasing pointer.
4990b57cec5SDimitry Andric         // Because some analysis may assume that nocaptured pointer is not
5000b57cec5SDimitry Andric         // returned from some special intrinsic (because function would have to
5010b57cec5SDimitry Andric         // be marked with returns attribute), it is crucial to use this function
5020b57cec5SDimitry Andric         // because it should be in sync with CaptureTracking. Not using it may
5030b57cec5SDimitry Andric         // cause weird miscompilations where 2 aliasing pointers are assumed to
5040b57cec5SDimitry Andric         // noalias.
5058bcb0991SDimitry Andric         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
5060b57cec5SDimitry Andric           V = RP;
5070b57cec5SDimitry Andric           continue;
5080b57cec5SDimitry Andric         }
5090b57cec5SDimitry Andric       }
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
5120b57cec5SDimitry Andric       // can come up with something. This matches what GetUnderlyingObject does.
5130b57cec5SDimitry Andric       if (const Instruction *I = dyn_cast<Instruction>(V))
5140b57cec5SDimitry Andric         // TODO: Get a DominatorTree and AssumptionCache and use them here
5150b57cec5SDimitry Andric         // (these are both now available in this function, but this should be
5160b57cec5SDimitry Andric         // updated when GetUnderlyingObject is updated). TLI should be
5170b57cec5SDimitry Andric         // provided also.
5180b57cec5SDimitry Andric         if (const Value *Simplified =
5190b57cec5SDimitry Andric                 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
5200b57cec5SDimitry Andric           V = Simplified;
5210b57cec5SDimitry Andric           continue;
5220b57cec5SDimitry Andric         }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric       Decomposed.Base = V;
5250b57cec5SDimitry Andric       return false;
5260b57cec5SDimitry Andric     }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric     // Don't attempt to analyze GEPs over unsized objects.
5290b57cec5SDimitry Andric     if (!GEPOp->getSourceElementType()->isSized()) {
5300b57cec5SDimitry Andric       Decomposed.Base = V;
5310b57cec5SDimitry Andric       return false;
5320b57cec5SDimitry Andric     }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric     unsigned AS = GEPOp->getPointerAddressSpace();
5350b57cec5SDimitry Andric     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
5360b57cec5SDimitry Andric     gep_type_iterator GTI = gep_type_begin(GEPOp);
5370b57cec5SDimitry Andric     unsigned PointerSize = DL.getPointerSizeInBits(AS);
5380b57cec5SDimitry Andric     // Assume all GEP operands are constants until proven otherwise.
5390b57cec5SDimitry Andric     bool GepHasConstantOffset = true;
5400b57cec5SDimitry Andric     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
5410b57cec5SDimitry Andric          I != E; ++I, ++GTI) {
5420b57cec5SDimitry Andric       const Value *Index = *I;
5430b57cec5SDimitry Andric       // Compute the (potentially symbolic) offset in bytes for this index.
5440b57cec5SDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
5450b57cec5SDimitry Andric         // For a struct, add the member offset.
5460b57cec5SDimitry Andric         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
5470b57cec5SDimitry Andric         if (FieldNo == 0)
5480b57cec5SDimitry Andric           continue;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric         Decomposed.StructOffset +=
5510b57cec5SDimitry Andric           DL.getStructLayout(STy)->getElementOffset(FieldNo);
5520b57cec5SDimitry Andric         continue;
5530b57cec5SDimitry Andric       }
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric       // For an array/pointer, add the element offset, explicitly scaled.
5560b57cec5SDimitry Andric       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
5570b57cec5SDimitry Andric         if (CIdx->isZero())
5580b57cec5SDimitry Andric           continue;
5590b57cec5SDimitry Andric         Decomposed.OtherOffset +=
5600b57cec5SDimitry Andric           (DL.getTypeAllocSize(GTI.getIndexedType()) *
5610b57cec5SDimitry Andric             CIdx->getValue().sextOrSelf(MaxPointerSize))
5620b57cec5SDimitry Andric               .sextOrTrunc(MaxPointerSize);
5630b57cec5SDimitry Andric         continue;
5640b57cec5SDimitry Andric       }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric       GepHasConstantOffset = false;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric       APInt Scale(MaxPointerSize, DL.getTypeAllocSize(GTI.getIndexedType()));
5690b57cec5SDimitry Andric       unsigned ZExtBits = 0, SExtBits = 0;
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric       // If the integer type is smaller than the pointer size, it is implicitly
5720b57cec5SDimitry Andric       // sign extended to pointer size.
5730b57cec5SDimitry Andric       unsigned Width = Index->getType()->getIntegerBitWidth();
5740b57cec5SDimitry Andric       if (PointerSize > Width)
5750b57cec5SDimitry Andric         SExtBits += PointerSize - Width;
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
5780b57cec5SDimitry Andric       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
5790b57cec5SDimitry Andric       bool NSW = true, NUW = true;
5800b57cec5SDimitry Andric       const Value *OrigIndex = Index;
5810b57cec5SDimitry Andric       Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
5820b57cec5SDimitry Andric                                   SExtBits, DL, 0, AC, DT, NSW, NUW);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
5850b57cec5SDimitry Andric       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric       // It can be the case that, even through C1*V+C2 does not overflow for
5880b57cec5SDimitry Andric       // relevant values of V, (C2*Scale) can overflow. In that case, we cannot
5890b57cec5SDimitry Andric       // decompose the expression in this way.
5900b57cec5SDimitry Andric       //
5910b57cec5SDimitry Andric       // FIXME: C1*Scale and the other operations in the decomposed
5920b57cec5SDimitry Andric       // (C1*Scale)*V+C2*Scale can also overflow. We should check for this
5930b57cec5SDimitry Andric       // possibility.
5940b57cec5SDimitry Andric       APInt WideScaledOffset = IndexOffset.sextOrTrunc(MaxPointerSize*2) *
5950b57cec5SDimitry Andric                                  Scale.sext(MaxPointerSize*2);
5960b57cec5SDimitry Andric       if (WideScaledOffset.getMinSignedBits() > MaxPointerSize) {
5970b57cec5SDimitry Andric         Index = OrigIndex;
5980b57cec5SDimitry Andric         IndexScale = 1;
5990b57cec5SDimitry Andric         IndexOffset = 0;
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric         ZExtBits = SExtBits = 0;
6020b57cec5SDimitry Andric         if (PointerSize > Width)
6030b57cec5SDimitry Andric           SExtBits += PointerSize - Width;
6040b57cec5SDimitry Andric       } else {
6050b57cec5SDimitry Andric         Decomposed.OtherOffset += IndexOffset.sextOrTrunc(MaxPointerSize) * Scale;
6060b57cec5SDimitry Andric         Scale *= IndexScale.sextOrTrunc(MaxPointerSize);
6070b57cec5SDimitry Andric       }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric       // If we already had an occurrence of this index variable, merge this
6100b57cec5SDimitry Andric       // scale into it.  For example, we want to handle:
6110b57cec5SDimitry Andric       //   A[x][x] -> x*16 + x*4 -> x*20
6120b57cec5SDimitry Andric       // This also ensures that 'x' only appears in the index list once.
6130b57cec5SDimitry Andric       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
6140b57cec5SDimitry Andric         if (Decomposed.VarIndices[i].V == Index &&
6150b57cec5SDimitry Andric             Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
6160b57cec5SDimitry Andric             Decomposed.VarIndices[i].SExtBits == SExtBits) {
6170b57cec5SDimitry Andric           Scale += Decomposed.VarIndices[i].Scale;
6180b57cec5SDimitry Andric           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
6190b57cec5SDimitry Andric           break;
6200b57cec5SDimitry Andric         }
6210b57cec5SDimitry Andric       }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric       // Make sure that we have a scale that makes sense for this target's
6240b57cec5SDimitry Andric       // pointer size.
6250b57cec5SDimitry Andric       Scale = adjustToPointerSize(Scale, PointerSize);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric       if (!!Scale) {
6280b57cec5SDimitry Andric         VariableGEPIndex Entry = {Index, ZExtBits, SExtBits, Scale};
6290b57cec5SDimitry Andric         Decomposed.VarIndices.push_back(Entry);
6300b57cec5SDimitry Andric       }
6310b57cec5SDimitry Andric     }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric     // Take care of wrap-arounds
6340b57cec5SDimitry Andric     if (GepHasConstantOffset) {
6350b57cec5SDimitry Andric       Decomposed.StructOffset =
6360b57cec5SDimitry Andric           adjustToPointerSize(Decomposed.StructOffset, PointerSize);
6370b57cec5SDimitry Andric       Decomposed.OtherOffset =
6380b57cec5SDimitry Andric           adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
6390b57cec5SDimitry Andric     }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric     // Analyze the base pointer next.
6420b57cec5SDimitry Andric     V = GEPOp->getOperand(0);
6430b57cec5SDimitry Andric   } while (--MaxLookup);
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   // If the chain of expressions is too deep, just return early.
6460b57cec5SDimitry Andric   Decomposed.Base = V;
6470b57cec5SDimitry Andric   SearchLimitReached++;
6480b57cec5SDimitry Andric   return true;
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric /// Returns whether the given pointer value points to memory that is local to
6520b57cec5SDimitry Andric /// the function, with global constants being considered local to all
6530b57cec5SDimitry Andric /// functions.
6540b57cec5SDimitry Andric bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
6550b57cec5SDimitry Andric                                            AAQueryInfo &AAQI, bool OrLocal) {
6560b57cec5SDimitry Andric   assert(Visited.empty() && "Visited must be cleared after use!");
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   unsigned MaxLookup = 8;
6590b57cec5SDimitry Andric   SmallVector<const Value *, 16> Worklist;
6600b57cec5SDimitry Andric   Worklist.push_back(Loc.Ptr);
6610b57cec5SDimitry Andric   do {
6620b57cec5SDimitry Andric     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
6630b57cec5SDimitry Andric     if (!Visited.insert(V).second) {
6640b57cec5SDimitry Andric       Visited.clear();
6650b57cec5SDimitry Andric       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6660b57cec5SDimitry Andric     }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric     // An alloca instruction defines local memory.
6690b57cec5SDimitry Andric     if (OrLocal && isa<AllocaInst>(V))
6700b57cec5SDimitry Andric       continue;
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric     // A global constant counts as local memory for our purposes.
6730b57cec5SDimitry Andric     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6740b57cec5SDimitry Andric       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
6750b57cec5SDimitry Andric       // global to be marked constant in some modules and non-constant in
6760b57cec5SDimitry Andric       // others.  GV may even be a declaration, not a definition.
6770b57cec5SDimitry Andric       if (!GV->isConstant()) {
6780b57cec5SDimitry Andric         Visited.clear();
6790b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6800b57cec5SDimitry Andric       }
6810b57cec5SDimitry Andric       continue;
6820b57cec5SDimitry Andric     }
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric     // If both select values point to local memory, then so does the select.
6850b57cec5SDimitry Andric     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6860b57cec5SDimitry Andric       Worklist.push_back(SI->getTrueValue());
6870b57cec5SDimitry Andric       Worklist.push_back(SI->getFalseValue());
6880b57cec5SDimitry Andric       continue;
6890b57cec5SDimitry Andric     }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     // If all values incoming to a phi node point to local memory, then so does
6920b57cec5SDimitry Andric     // the phi.
6930b57cec5SDimitry Andric     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
6940b57cec5SDimitry Andric       // Don't bother inspecting phi nodes with many operands.
6950b57cec5SDimitry Andric       if (PN->getNumIncomingValues() > MaxLookup) {
6960b57cec5SDimitry Andric         Visited.clear();
6970b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6980b57cec5SDimitry Andric       }
6990b57cec5SDimitry Andric       for (Value *IncValue : PN->incoming_values())
7000b57cec5SDimitry Andric         Worklist.push_back(IncValue);
7010b57cec5SDimitry Andric       continue;
7020b57cec5SDimitry Andric     }
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric     // Otherwise be conservative.
7050b57cec5SDimitry Andric     Visited.clear();
7060b57cec5SDimitry Andric     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7070b57cec5SDimitry Andric   } while (!Worklist.empty() && --MaxLookup);
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   Visited.clear();
7100b57cec5SDimitry Andric   return Worklist.empty();
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric /// Returns the behavior when calling the given call site.
7140b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
7150b57cec5SDimitry Andric   if (Call->doesNotAccessMemory())
7160b57cec5SDimitry Andric     // Can't do better than this.
7170b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   // If the callsite knows it only reads memory, don't return worse
7220b57cec5SDimitry Andric   // than that.
7230b57cec5SDimitry Andric   if (Call->onlyReadsMemory())
7240b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7250b57cec5SDimitry Andric   else if (Call->doesNotReadMemory())
7260b57cec5SDimitry Andric     Min = FMRB_DoesNotReadMemory;
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   if (Call->onlyAccessesArgMemory())
7290b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7300b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemory())
7310b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7320b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
7330b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   // If the call has operand bundles then aliasing attributes from the function
7360b57cec5SDimitry Andric   // it calls do not directly apply to the call.  This can be made more precise
7370b57cec5SDimitry Andric   // in the future.
7380b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
7390b57cec5SDimitry Andric     if (const Function *F = Call->getCalledFunction())
7400b57cec5SDimitry Andric       Min =
7410b57cec5SDimitry Andric           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   return Min;
7440b57cec5SDimitry Andric }
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call
7470b57cec5SDimitry Andric /// site is not known.
7480b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
7490b57cec5SDimitry Andric   // If the function declares it doesn't access memory, we can't do better.
7500b57cec5SDimitry Andric   if (F->doesNotAccessMemory())
7510b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   // If the function declares it only reads memory, go with that.
7560b57cec5SDimitry Andric   if (F->onlyReadsMemory())
7570b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7580b57cec5SDimitry Andric   else if (F->doesNotReadMemory())
7590b57cec5SDimitry Andric     Min = FMRB_DoesNotReadMemory;
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   if (F->onlyAccessesArgMemory())
7620b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7630b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemory())
7640b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7650b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemOrArgMem())
7660b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   return Min;
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric /// Returns true if this is a writeonly (i.e Mod only) parameter.
7720b57cec5SDimitry Andric static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
7730b57cec5SDimitry Andric                              const TargetLibraryInfo &TLI) {
7740b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
7750b57cec5SDimitry Andric     return true;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   // We can bound the aliasing properties of memset_pattern16 just as we can
7780b57cec5SDimitry Andric   // for memcpy/memset.  This is particularly important because the
7790b57cec5SDimitry Andric   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
7800b57cec5SDimitry Andric   // whenever possible.
7810b57cec5SDimitry Andric   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
7820b57cec5SDimitry Andric   // attributes.
7830b57cec5SDimitry Andric   LibFunc F;
7840b57cec5SDimitry Andric   if (Call->getCalledFunction() &&
7850b57cec5SDimitry Andric       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
7860b57cec5SDimitry Andric       F == LibFunc_memset_pattern16 && TLI.has(F))
7870b57cec5SDimitry Andric     if (ArgIdx == 0)
7880b57cec5SDimitry Andric       return true;
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   // TODO: memset_pattern4, memset_pattern8
7910b57cec5SDimitry Andric   // TODO: _chk variants
7920b57cec5SDimitry Andric   // TODO: strcmp, strcpy
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   return false;
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
7980b57cec5SDimitry Andric                                            unsigned ArgIdx) {
7990b57cec5SDimitry Andric   // Checking for known builtin intrinsics and target library functions.
8000b57cec5SDimitry Andric   if (isWriteOnlyParam(Call, ArgIdx, TLI))
8010b57cec5SDimitry Andric     return ModRefInfo::Mod;
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
8040b57cec5SDimitry Andric     return ModRefInfo::Ref;
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
8070b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
8130b57cec5SDimitry Andric   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
8140b57cec5SDimitry Andric   return II && II->getIntrinsicID() == IID;
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric #ifndef NDEBUG
8180b57cec5SDimitry Andric static const Function *getParent(const Value *V) {
8190b57cec5SDimitry Andric   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
8200b57cec5SDimitry Andric     if (!inst->getParent())
8210b57cec5SDimitry Andric       return nullptr;
8220b57cec5SDimitry Andric     return inst->getParent()->getParent();
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   if (const Argument *arg = dyn_cast<Argument>(V))
8260b57cec5SDimitry Andric     return arg->getParent();
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   return nullptr;
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) {
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   const Function *F1 = getParent(O1);
8340b57cec5SDimitry Andric   const Function *F2 = getParent(O2);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   return !F1 || !F2 || F1 == F2;
8370b57cec5SDimitry Andric }
8380b57cec5SDimitry Andric #endif
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
8410b57cec5SDimitry Andric                                  const MemoryLocation &LocB,
8420b57cec5SDimitry Andric                                  AAQueryInfo &AAQI) {
8430b57cec5SDimitry Andric   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
8440b57cec5SDimitry Andric          "BasicAliasAnalysis doesn't support interprocedural queries.");
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // If we have a directly cached entry for these locations, we have recursed
8470b57cec5SDimitry Andric   // through this once, so just return the cached results. Notably, when this
8480b57cec5SDimitry Andric   // happens, we don't clear the cache.
8490b57cec5SDimitry Andric   auto CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocA, LocB));
8500b57cec5SDimitry Andric   if (CacheIt != AAQI.AliasCache.end())
8510b57cec5SDimitry Andric     return CacheIt->second;
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocB, LocA));
8540b57cec5SDimitry Andric   if (CacheIt != AAQI.AliasCache.end())
8550b57cec5SDimitry Andric     return CacheIt->second;
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
8580b57cec5SDimitry Andric                                  LocB.Size, LocB.AATags, AAQI);
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   VisitedPhiBBs.clear();
8610b57cec5SDimitry Andric   return Alias;
8620b57cec5SDimitry Andric }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory
8650b57cec5SDimitry Andric /// object.
8660b57cec5SDimitry Andric ///
8670b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't
8680b57cec5SDimitry Andric /// say much about this query.  We do, however, use simple "address taken"
8690b57cec5SDimitry Andric /// analysis on local objects.
8700b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
8710b57cec5SDimitry Andric                                         const MemoryLocation &Loc,
8720b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
8730b57cec5SDimitry Andric   assert(notDifferentParent(Call, Loc.Ptr) &&
8740b57cec5SDimitry Andric          "AliasAnalysis query involving multiple functions!");
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   // Calls marked 'tail' cannot read or write allocas from the current frame
8790b57cec5SDimitry Andric   // because the current frame might be destroyed by the time they run. However,
8800b57cec5SDimitry Andric   // a tail call may use an alloca with byval. Calling with byval copies the
8810b57cec5SDimitry Andric   // contents of the alloca into argument registers or stack slots, so there is
8820b57cec5SDimitry Andric   // no lifetime issue.
8830b57cec5SDimitry Andric   if (isa<AllocaInst>(Object))
8840b57cec5SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(Call))
8850b57cec5SDimitry Andric       if (CI->isTailCall() &&
8860b57cec5SDimitry Andric           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
8870b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
8900b57cec5SDimitry Andric   // modify them even though the alloca is not escaped.
8910b57cec5SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(Object))
8920b57cec5SDimitry Andric     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
8930b57cec5SDimitry Andric       return ModRefInfo::Mod;
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric   // If the pointer is to a locally allocated object that does not escape,
8960b57cec5SDimitry Andric   // then the call can not mod/ref the pointer unless the call takes the pointer
8970b57cec5SDimitry Andric   // as an argument, and itself doesn't capture it.
8980b57cec5SDimitry Andric   if (!isa<Constant>(Object) && Call != Object &&
8990b57cec5SDimitry Andric       isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) {
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric     // Optimistically assume that call doesn't touch Object and check this
9020b57cec5SDimitry Andric     // assumption in the following loop.
9030b57cec5SDimitry Andric     ModRefInfo Result = ModRefInfo::NoModRef;
9040b57cec5SDimitry Andric     bool IsMustAlias = true;
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric     unsigned OperandNo = 0;
9070b57cec5SDimitry Andric     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
9080b57cec5SDimitry Andric          CI != CE; ++CI, ++OperandNo) {
9090b57cec5SDimitry Andric       // Only look at the no-capture or byval pointer arguments.  If this
9100b57cec5SDimitry Andric       // pointer were passed to arguments that were neither of these, then it
9110b57cec5SDimitry Andric       // couldn't be no-capture.
9120b57cec5SDimitry Andric       if (!(*CI)->getType()->isPointerTy() ||
9130b57cec5SDimitry Andric           (!Call->doesNotCapture(OperandNo) &&
9140b57cec5SDimitry Andric            OperandNo < Call->getNumArgOperands() &&
9150b57cec5SDimitry Andric            !Call->isByValArgument(OperandNo)))
9160b57cec5SDimitry Andric         continue;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric       // Call doesn't access memory through this operand, so we don't care
9190b57cec5SDimitry Andric       // if it aliases with Object.
9200b57cec5SDimitry Andric       if (Call->doesNotAccessMemory(OperandNo))
9210b57cec5SDimitry Andric         continue;
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric       // If this is a no-capture pointer argument, see if we can tell that it
9240b57cec5SDimitry Andric       // is impossible to alias the pointer we're checking.
9250b57cec5SDimitry Andric       AliasResult AR = getBestAAResults().alias(MemoryLocation(*CI),
9260b57cec5SDimitry Andric                                                 MemoryLocation(Object), AAQI);
9270b57cec5SDimitry Andric       if (AR != MustAlias)
9280b57cec5SDimitry Andric         IsMustAlias = false;
9290b57cec5SDimitry Andric       // Operand doesn't alias 'Object', continue looking for other aliases
9300b57cec5SDimitry Andric       if (AR == NoAlias)
9310b57cec5SDimitry Andric         continue;
9320b57cec5SDimitry Andric       // Operand aliases 'Object', but call doesn't modify it. Strengthen
9330b57cec5SDimitry Andric       // initial assumption and keep looking in case if there are more aliases.
9340b57cec5SDimitry Andric       if (Call->onlyReadsMemory(OperandNo)) {
9350b57cec5SDimitry Andric         Result = setRef(Result);
9360b57cec5SDimitry Andric         continue;
9370b57cec5SDimitry Andric       }
9380b57cec5SDimitry Andric       // Operand aliases 'Object' but call only writes into it.
9390b57cec5SDimitry Andric       if (Call->doesNotReadMemory(OperandNo)) {
9400b57cec5SDimitry Andric         Result = setMod(Result);
9410b57cec5SDimitry Andric         continue;
9420b57cec5SDimitry Andric       }
9430b57cec5SDimitry Andric       // This operand aliases 'Object' and call reads and writes into it.
9440b57cec5SDimitry Andric       // Setting ModRef will not yield an early return below, MustAlias is not
9450b57cec5SDimitry Andric       // used further.
9460b57cec5SDimitry Andric       Result = ModRefInfo::ModRef;
9470b57cec5SDimitry Andric       break;
9480b57cec5SDimitry Andric     }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric     // No operand aliases, reset Must bit. Add below if at least one aliases
9510b57cec5SDimitry Andric     // and all aliases found are MustAlias.
9520b57cec5SDimitry Andric     if (isNoModRef(Result))
9530b57cec5SDimitry Andric       IsMustAlias = false;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric     // Early return if we improved mod ref information
9560b57cec5SDimitry Andric     if (!isModAndRefSet(Result)) {
9570b57cec5SDimitry Andric       if (isNoModRef(Result))
9580b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
9590b57cec5SDimitry Andric       return IsMustAlias ? setMust(Result) : clearMust(Result);
9600b57cec5SDimitry Andric     }
9610b57cec5SDimitry Andric   }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   // If the call is to malloc or calloc, we can assume that it doesn't
9640b57cec5SDimitry Andric   // modify any IR visible value.  This is only valid because we assume these
9650b57cec5SDimitry Andric   // routines do not read values visible in the IR.  TODO: Consider special
9660b57cec5SDimitry Andric   // casing realloc and strdup routines which access only their arguments as
9670b57cec5SDimitry Andric   // well.  Or alternatively, replace all of this with inaccessiblememonly once
9680b57cec5SDimitry Andric   // that's implemented fully.
9690b57cec5SDimitry Andric   if (isMallocOrCallocLikeFn(Call, &TLI)) {
9700b57cec5SDimitry Andric     // Be conservative if the accessed pointer may alias the allocation -
9710b57cec5SDimitry Andric     // fallback to the generic handling below.
9720b57cec5SDimitry Andric     if (getBestAAResults().alias(MemoryLocation(Call), Loc, AAQI) == NoAlias)
9730b57cec5SDimitry Andric       return ModRefInfo::NoModRef;
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // The semantics of memcpy intrinsics forbid overlap between their respective
9770b57cec5SDimitry Andric   // operands, i.e., source and destination of any given memcpy must no-alias.
9780b57cec5SDimitry Andric   // If Loc must-aliases either one of these two locations, then it necessarily
9790b57cec5SDimitry Andric   // no-aliases the other.
9800b57cec5SDimitry Andric   if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
9810b57cec5SDimitry Andric     AliasResult SrcAA, DestAA;
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     if ((SrcAA = getBestAAResults().alias(MemoryLocation::getForSource(Inst),
9840b57cec5SDimitry Andric                                           Loc, AAQI)) == MustAlias)
9850b57cec5SDimitry Andric       // Loc is exactly the memcpy source thus disjoint from memcpy dest.
9860b57cec5SDimitry Andric       return ModRefInfo::Ref;
9870b57cec5SDimitry Andric     if ((DestAA = getBestAAResults().alias(MemoryLocation::getForDest(Inst),
9880b57cec5SDimitry Andric                                            Loc, AAQI)) == MustAlias)
9890b57cec5SDimitry Andric       // The converse case.
9900b57cec5SDimitry Andric       return ModRefInfo::Mod;
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric     // It's also possible for Loc to alias both src and dest, or neither.
9930b57cec5SDimitry Andric     ModRefInfo rv = ModRefInfo::NoModRef;
9940b57cec5SDimitry Andric     if (SrcAA != NoAlias)
9950b57cec5SDimitry Andric       rv = setRef(rv);
9960b57cec5SDimitry Andric     if (DestAA != NoAlias)
9970b57cec5SDimitry Andric       rv = setMod(rv);
9980b57cec5SDimitry Andric     return rv;
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
10020b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
10030b57cec5SDimitry Andric   // particular memory location.
10040b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::assume))
10050b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
10080b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mods any
10090b57cec5SDimitry Andric   // particular memory location.
10100b57cec5SDimitry Andric   //
10110b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10120b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10130b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10140b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
10150b57cec5SDimitry Andric     return ModRefInfo::Ref;
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
10180b57cec5SDimitry Andric   // writing so that proper control dependencies are maintained but they never
10190b57cec5SDimitry Andric   // mod any particular memory location visible to the IR.
10200b57cec5SDimitry Andric   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
10210b57cec5SDimitry Andric   // intrinsic is now modeled as reading memory. This prevents hoisting the
10220b57cec5SDimitry Andric   // invariant.start intrinsic over stores. Consider:
10230b57cec5SDimitry Andric   // *ptr = 40;
10240b57cec5SDimitry Andric   // *ptr = 50;
10250b57cec5SDimitry Andric   // invariant_start(ptr)
10260b57cec5SDimitry Andric   // int val = *ptr;
10270b57cec5SDimitry Andric   // print(val);
10280b57cec5SDimitry Andric   //
10290b57cec5SDimitry Andric   // This cannot be transformed to:
10300b57cec5SDimitry Andric   //
10310b57cec5SDimitry Andric   // *ptr = 40;
10320b57cec5SDimitry Andric   // invariant_start(ptr)
10330b57cec5SDimitry Andric   // *ptr = 50;
10340b57cec5SDimitry Andric   // int val = *ptr;
10350b57cec5SDimitry Andric   // print(val);
10360b57cec5SDimitry Andric   //
10370b57cec5SDimitry Andric   // The transformation will cause the second store to be ignored (based on
10380b57cec5SDimitry Andric   // rules of invariant.start)  and print 40, while the first program always
10390b57cec5SDimitry Andric   // prints 50.
10400b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
10410b57cec5SDimitry Andric     return ModRefInfo::Ref;
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10440b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
10450b57cec5SDimitry Andric }
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
10480b57cec5SDimitry Andric                                         const CallBase *Call2,
10490b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
10500b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
10510b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
10520b57cec5SDimitry Andric   // particular memory location.
10530b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::assume) ||
10540b57cec5SDimitry Andric       isIntrinsicCall(Call2, Intrinsic::assume))
10550b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
10580b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mod any
10590b57cec5SDimitry Andric   // particular memory location.
10600b57cec5SDimitry Andric   //
10610b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10620b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10630b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   // NB! This function is *not* commutative, so we special case two
10660b57cec5SDimitry Andric   // possibilities for guard intrinsics.
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
10690b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
10700b57cec5SDimitry Andric                ? ModRefInfo::Ref
10710b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
10740b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
10750b57cec5SDimitry Andric                ? ModRefInfo::Mod
10760b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10790b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
10830b57cec5SDimitry Andric /// both having the exact same pointer operand.
10840b57cec5SDimitry Andric static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
10850b57cec5SDimitry Andric                                             LocationSize MaybeV1Size,
10860b57cec5SDimitry Andric                                             const GEPOperator *GEP2,
10870b57cec5SDimitry Andric                                             LocationSize MaybeV2Size,
10880b57cec5SDimitry Andric                                             const DataLayout &DL) {
10890b57cec5SDimitry Andric   assert(GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
10900b57cec5SDimitry Andric              GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
10910b57cec5SDimitry Andric          GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&
10920b57cec5SDimitry Andric          "Expected GEPs with the same pointer operand");
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
10950b57cec5SDimitry Andric   // such that the struct field accesses provably cannot alias.
10960b57cec5SDimitry Andric   // We also need at least two indices (the pointer, and the struct field).
10970b57cec5SDimitry Andric   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
10980b57cec5SDimitry Andric       GEP1->getNumIndices() < 2)
10990b57cec5SDimitry Andric     return MayAlias;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   // If we don't know the size of the accesses through both GEPs, we can't
11020b57cec5SDimitry Andric   // determine whether the struct fields accessed can't alias.
11030b57cec5SDimitry Andric   if (MaybeV1Size == LocationSize::unknown() ||
11040b57cec5SDimitry Andric       MaybeV2Size == LocationSize::unknown())
11050b57cec5SDimitry Andric     return MayAlias;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
11080b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric   ConstantInt *C1 =
11110b57cec5SDimitry Andric       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
11120b57cec5SDimitry Andric   ConstantInt *C2 =
11130b57cec5SDimitry Andric       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   // If the last (struct) indices are constants and are equal, the other indices
11160b57cec5SDimitry Andric   // might be also be dynamically equal, so the GEPs can alias.
11170b57cec5SDimitry Andric   if (C1 && C2) {
11180b57cec5SDimitry Andric     unsigned BitWidth = std::max(C1->getBitWidth(), C2->getBitWidth());
11190b57cec5SDimitry Andric     if (C1->getValue().sextOrSelf(BitWidth) ==
11200b57cec5SDimitry Andric         C2->getValue().sextOrSelf(BitWidth))
11210b57cec5SDimitry Andric       return MayAlias;
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   // Find the last-indexed type of the GEP, i.e., the type you'd get if
11250b57cec5SDimitry Andric   // you stripped the last index.
11260b57cec5SDimitry Andric   // On the way, look at each indexed type.  If there's something other
11270b57cec5SDimitry Andric   // than an array, different indices can lead to different final types.
11280b57cec5SDimitry Andric   SmallVector<Value *, 8> IntermediateIndices;
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   // Insert the first index; we don't need to check the type indexed
11310b57cec5SDimitry Andric   // through it as it only drops the pointer indirection.
11320b57cec5SDimitry Andric   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
11330b57cec5SDimitry Andric   IntermediateIndices.push_back(GEP1->getOperand(1));
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   // Insert all the remaining indices but the last one.
11360b57cec5SDimitry Andric   // Also, check that they all index through arrays.
11370b57cec5SDimitry Andric   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
11380b57cec5SDimitry Andric     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
11390b57cec5SDimitry Andric             GEP1->getSourceElementType(), IntermediateIndices)))
11400b57cec5SDimitry Andric       return MayAlias;
11410b57cec5SDimitry Andric     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
11420b57cec5SDimitry Andric   }
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric   auto *Ty = GetElementPtrInst::getIndexedType(
11450b57cec5SDimitry Andric     GEP1->getSourceElementType(), IntermediateIndices);
11460b57cec5SDimitry Andric   StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   if (isa<SequentialType>(Ty)) {
11490b57cec5SDimitry Andric     // We know that:
11500b57cec5SDimitry Andric     // - both GEPs begin indexing from the exact same pointer;
11510b57cec5SDimitry Andric     // - the last indices in both GEPs are constants, indexing into a sequential
11520b57cec5SDimitry Andric     //   type (array or pointer);
11530b57cec5SDimitry Andric     // - both GEPs only index through arrays prior to that.
11540b57cec5SDimitry Andric     //
11550b57cec5SDimitry Andric     // Because array indices greater than the number of elements are valid in
11560b57cec5SDimitry Andric     // GEPs, unless we know the intermediate indices are identical between
11570b57cec5SDimitry Andric     // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
11580b57cec5SDimitry Andric     // partially overlap. We also need to check that the loaded size matches
11590b57cec5SDimitry Andric     // the element size, otherwise we could still have overlap.
11600b57cec5SDimitry Andric     const uint64_t ElementSize =
11610b57cec5SDimitry Andric         DL.getTypeStoreSize(cast<SequentialType>(Ty)->getElementType());
11620b57cec5SDimitry Andric     if (V1Size != ElementSize || V2Size != ElementSize)
11630b57cec5SDimitry Andric       return MayAlias;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric     for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
11660b57cec5SDimitry Andric       if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
11670b57cec5SDimitry Andric         return MayAlias;
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric     // Now we know that the array/pointer that GEP1 indexes into and that
11700b57cec5SDimitry Andric     // that GEP2 indexes into must either precisely overlap or be disjoint.
11710b57cec5SDimitry Andric     // Because they cannot partially overlap and because fields in an array
11720b57cec5SDimitry Andric     // cannot overlap, if we can prove the final indices are different between
11730b57cec5SDimitry Andric     // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric     // If the last indices are constants, we've already checked they don't
11760b57cec5SDimitry Andric     // equal each other so we can exit early.
11770b57cec5SDimitry Andric     if (C1 && C2)
11780b57cec5SDimitry Andric       return NoAlias;
11790b57cec5SDimitry Andric     {
11800b57cec5SDimitry Andric       Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
11810b57cec5SDimitry Andric       Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
11820b57cec5SDimitry Andric       if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
11830b57cec5SDimitry Andric         // If one of the indices is a PHI node, be safe and only use
11840b57cec5SDimitry Andric         // computeKnownBits so we don't make any assumptions about the
11850b57cec5SDimitry Andric         // relationships between the two indices. This is important if we're
11860b57cec5SDimitry Andric         // asking about values from different loop iterations. See PR32314.
11870b57cec5SDimitry Andric         // TODO: We may be able to change the check so we only do this when
11880b57cec5SDimitry Andric         // we definitely looked through a PHINode.
11890b57cec5SDimitry Andric         if (GEP1LastIdx != GEP2LastIdx &&
11900b57cec5SDimitry Andric             GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
11910b57cec5SDimitry Andric           KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
11920b57cec5SDimitry Andric           KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
11930b57cec5SDimitry Andric           if (Known1.Zero.intersects(Known2.One) ||
11940b57cec5SDimitry Andric               Known1.One.intersects(Known2.Zero))
11950b57cec5SDimitry Andric             return NoAlias;
11960b57cec5SDimitry Andric         }
11970b57cec5SDimitry Andric       } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
11980b57cec5SDimitry Andric         return NoAlias;
11990b57cec5SDimitry Andric     }
12000b57cec5SDimitry Andric     return MayAlias;
12010b57cec5SDimitry Andric   } else if (!LastIndexedStruct || !C1 || !C2) {
12020b57cec5SDimitry Andric     return MayAlias;
12030b57cec5SDimitry Andric   }
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric   if (C1->getValue().getActiveBits() > 64 ||
12060b57cec5SDimitry Andric       C2->getValue().getActiveBits() > 64)
12070b57cec5SDimitry Andric     return MayAlias;
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric   // We know that:
12100b57cec5SDimitry Andric   // - both GEPs begin indexing from the exact same pointer;
12110b57cec5SDimitry Andric   // - the last indices in both GEPs are constants, indexing into a struct;
12120b57cec5SDimitry Andric   // - said indices are different, hence, the pointed-to fields are different;
12130b57cec5SDimitry Andric   // - both GEPs only index through arrays prior to that.
12140b57cec5SDimitry Andric   //
12150b57cec5SDimitry Andric   // This lets us determine that the struct that GEP1 indexes into and the
12160b57cec5SDimitry Andric   // struct that GEP2 indexes into must either precisely overlap or be
12170b57cec5SDimitry Andric   // completely disjoint.  Because they cannot partially overlap, indexing into
12180b57cec5SDimitry Andric   // different non-overlapping fields of the struct will never alias.
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric   // Therefore, the only remaining thing needed to show that both GEPs can't
12210b57cec5SDimitry Andric   // alias is that the fields are not overlapping.
12220b57cec5SDimitry Andric   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
12230b57cec5SDimitry Andric   const uint64_t StructSize = SL->getSizeInBytes();
12240b57cec5SDimitry Andric   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
12250b57cec5SDimitry Andric   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
12280b57cec5SDimitry Andric                                       uint64_t V2Off, uint64_t V2Size) {
12290b57cec5SDimitry Andric     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
12300b57cec5SDimitry Andric            ((V2Off + V2Size <= StructSize) ||
12310b57cec5SDimitry Andric             (V2Off + V2Size - StructSize <= V1Off));
12320b57cec5SDimitry Andric   };
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
12350b57cec5SDimitry Andric       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
12360b57cec5SDimitry Andric     return NoAlias;
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   return MayAlias;
12390b57cec5SDimitry Andric }
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric // If a we have (a) a GEP and (b) a pointer based on an alloca, and the
12420b57cec5SDimitry Andric // beginning of the object the GEP points would have a negative offset with
12430b57cec5SDimitry Andric // repsect to the alloca, that means the GEP can not alias pointer (b).
12440b57cec5SDimitry Andric // Note that the pointer based on the alloca may not be a GEP. For
12450b57cec5SDimitry Andric // example, it may be the alloca itself.
12460b57cec5SDimitry Andric // The same applies if (b) is based on a GlobalVariable. Note that just being
12470b57cec5SDimitry Andric // based on isIdentifiedObject() is not enough - we need an identified object
12480b57cec5SDimitry Andric // that does not permit access to negative offsets. For example, a negative
12490b57cec5SDimitry Andric // offset from a noalias argument or call can be inbounds w.r.t the actual
12500b57cec5SDimitry Andric // underlying object.
12510b57cec5SDimitry Andric //
12520b57cec5SDimitry Andric // For example, consider:
12530b57cec5SDimitry Andric //
12540b57cec5SDimitry Andric //   struct { int f0, int f1, ...} foo;
12550b57cec5SDimitry Andric //   foo alloca;
12560b57cec5SDimitry Andric //   foo* random = bar(alloca);
12570b57cec5SDimitry Andric //   int *f0 = &alloca.f0
12580b57cec5SDimitry Andric //   int *f1 = &random->f1;
12590b57cec5SDimitry Andric //
12600b57cec5SDimitry Andric // Which is lowered, approximately, to:
12610b57cec5SDimitry Andric //
12620b57cec5SDimitry Andric //  %alloca = alloca %struct.foo
12630b57cec5SDimitry Andric //  %random = call %struct.foo* @random(%struct.foo* %alloca)
12640b57cec5SDimitry Andric //  %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
12650b57cec5SDimitry Andric //  %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
12660b57cec5SDimitry Andric //
12670b57cec5SDimitry Andric // Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
12680b57cec5SDimitry Andric // by %alloca. Since the %f1 GEP is inbounds, that means %random must also
12690b57cec5SDimitry Andric // point into the same object. But since %f0 points to the beginning of %alloca,
12700b57cec5SDimitry Andric // the highest %f1 can be is (%alloca + 3). This means %random can not be higher
12710b57cec5SDimitry Andric // than (%alloca - 1), and so is not inbounds, a contradiction.
12720b57cec5SDimitry Andric bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
12730b57cec5SDimitry Andric       const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
12740b57cec5SDimitry Andric       LocationSize MaybeObjectAccessSize) {
12750b57cec5SDimitry Andric   // If the object access size is unknown, or the GEP isn't inbounds, bail.
12760b57cec5SDimitry Andric   if (MaybeObjectAccessSize == LocationSize::unknown() || !GEPOp->isInBounds())
12770b57cec5SDimitry Andric     return false;
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric   const uint64_t ObjectAccessSize = MaybeObjectAccessSize.getValue();
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   // We need the object to be an alloca or a globalvariable, and want to know
12820b57cec5SDimitry Andric   // the offset of the pointer from the object precisely, so no variable
12830b57cec5SDimitry Andric   // indices are allowed.
12840b57cec5SDimitry Andric   if (!(isa<AllocaInst>(DecompObject.Base) ||
12850b57cec5SDimitry Andric         isa<GlobalVariable>(DecompObject.Base)) ||
12860b57cec5SDimitry Andric       !DecompObject.VarIndices.empty())
12870b57cec5SDimitry Andric     return false;
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric   APInt ObjectBaseOffset = DecompObject.StructOffset +
12900b57cec5SDimitry Andric                            DecompObject.OtherOffset;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   // If the GEP has no variable indices, we know the precise offset
12930b57cec5SDimitry Andric   // from the base, then use it. If the GEP has variable indices,
12940b57cec5SDimitry Andric   // we can't get exact GEP offset to identify pointer alias. So return
12950b57cec5SDimitry Andric   // false in that case.
12960b57cec5SDimitry Andric   if (!DecompGEP.VarIndices.empty())
12970b57cec5SDimitry Andric     return false;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   APInt GEPBaseOffset = DecompGEP.StructOffset;
13000b57cec5SDimitry Andric   GEPBaseOffset += DecompGEP.OtherOffset;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   return GEPBaseOffset.sge(ObjectBaseOffset + (int64_t)ObjectAccessSize);
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
13060b57cec5SDimitry Andric /// another pointer.
13070b57cec5SDimitry Andric ///
13080b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2.
13090b57cec5SDimitry Andric /// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
13100b57cec5SDimitry Andric /// V2.
13110b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP(
13120b57cec5SDimitry Andric     const GEPOperator *GEP1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
13130b57cec5SDimitry Andric     const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
13140b57cec5SDimitry Andric     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
13150b57cec5SDimitry Andric   DecomposedGEP DecompGEP1, DecompGEP2;
13160b57cec5SDimitry Andric   unsigned MaxPointerSize = getMaxPointerSize(DL);
13170b57cec5SDimitry Andric   DecompGEP1.StructOffset = DecompGEP1.OtherOffset = APInt(MaxPointerSize, 0);
13180b57cec5SDimitry Andric   DecompGEP2.StructOffset = DecompGEP2.OtherOffset = APInt(MaxPointerSize, 0);
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric   bool GEP1MaxLookupReached =
13210b57cec5SDimitry Andric     DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
13220b57cec5SDimitry Andric   bool GEP2MaxLookupReached =
13230b57cec5SDimitry Andric     DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   APInt GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
13260b57cec5SDimitry Andric   APInt GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&
13290b57cec5SDimitry Andric          "DecomposeGEPExpression returned a result different from "
13300b57cec5SDimitry Andric          "GetUnderlyingObject");
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric   // If the GEP's offset relative to its base is such that the base would
13330b57cec5SDimitry Andric   // fall below the start of the object underlying V2, then the GEP and V2
13340b57cec5SDimitry Andric   // cannot alias.
13350b57cec5SDimitry Andric   if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
13360b57cec5SDimitry Andric       isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
13370b57cec5SDimitry Andric     return NoAlias;
13380b57cec5SDimitry Andric   // If we have two gep instructions with must-alias or not-alias'ing base
13390b57cec5SDimitry Andric   // pointers, figure out if the indexes to the GEP tell us anything about the
13400b57cec5SDimitry Andric   // derived pointer.
13410b57cec5SDimitry Andric   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
13420b57cec5SDimitry Andric     // Check for the GEP base being at a negative offset, this time in the other
13430b57cec5SDimitry Andric     // direction.
13440b57cec5SDimitry Andric     if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
13450b57cec5SDimitry Andric         isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
13460b57cec5SDimitry Andric       return NoAlias;
13470b57cec5SDimitry Andric     // Do the base pointers alias?
13480b57cec5SDimitry Andric     AliasResult BaseAlias =
13490b57cec5SDimitry Andric         aliasCheck(UnderlyingV1, LocationSize::unknown(), AAMDNodes(),
13500b57cec5SDimitry Andric                    UnderlyingV2, LocationSize::unknown(), AAMDNodes(), AAQI);
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric     // Check for geps of non-aliasing underlying pointers where the offsets are
13530b57cec5SDimitry Andric     // identical.
13540b57cec5SDimitry Andric     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
13550b57cec5SDimitry Andric       // Do the base pointers alias assuming type and size.
13560b57cec5SDimitry Andric       AliasResult PreciseBaseAlias = aliasCheck(
13570b57cec5SDimitry Andric           UnderlyingV1, V1Size, V1AAInfo, UnderlyingV2, V2Size, V2AAInfo, AAQI);
13580b57cec5SDimitry Andric       if (PreciseBaseAlias == NoAlias) {
13590b57cec5SDimitry Andric         // See if the computed offset from the common pointer tells us about the
13600b57cec5SDimitry Andric         // relation of the resulting pointer.
13610b57cec5SDimitry Andric         // If the max search depth is reached the result is undefined
13620b57cec5SDimitry Andric         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
13630b57cec5SDimitry Andric           return MayAlias;
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric         // Same offsets.
13660b57cec5SDimitry Andric         if (GEP1BaseOffset == GEP2BaseOffset &&
13670b57cec5SDimitry Andric             DecompGEP1.VarIndices == DecompGEP2.VarIndices)
13680b57cec5SDimitry Andric           return NoAlias;
13690b57cec5SDimitry Andric       }
13700b57cec5SDimitry Andric     }
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric     // If we get a No or May, then return it immediately, no amount of analysis
13730b57cec5SDimitry Andric     // will improve this situation.
13740b57cec5SDimitry Andric     if (BaseAlias != MustAlias) {
13750b57cec5SDimitry Andric       assert(BaseAlias == NoAlias || BaseAlias == MayAlias);
13760b57cec5SDimitry Andric       return BaseAlias;
13770b57cec5SDimitry Andric     }
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
13800b57cec5SDimitry Andric     // exactly, see if the computed offset from the common pointer tells us
13810b57cec5SDimitry Andric     // about the relation of the resulting pointer.
13820b57cec5SDimitry Andric     // If we know the two GEPs are based off of the exact same pointer (and not
13830b57cec5SDimitry Andric     // just the same underlying object), see if that tells us anything about
13840b57cec5SDimitry Andric     // the resulting pointers.
13850b57cec5SDimitry Andric     if (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
13860b57cec5SDimitry Andric             GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
13870b57cec5SDimitry Andric         GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
13880b57cec5SDimitry Andric       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
13890b57cec5SDimitry Andric       // If we couldn't find anything interesting, don't abandon just yet.
13900b57cec5SDimitry Andric       if (R != MayAlias)
13910b57cec5SDimitry Andric         return R;
13920b57cec5SDimitry Andric     }
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric     // If the max search depth is reached, the result is undefined
13950b57cec5SDimitry Andric     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
13960b57cec5SDimitry Andric       return MayAlias;
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
13990b57cec5SDimitry Andric     // symbolic difference.
14000b57cec5SDimitry Andric     GEP1BaseOffset -= GEP2BaseOffset;
14010b57cec5SDimitry Andric     GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   } else {
14040b57cec5SDimitry Andric     // Check to see if these two pointers are related by the getelementptr
14050b57cec5SDimitry Andric     // instruction.  If one pointer is a GEP with a non-zero index of the other
14060b57cec5SDimitry Andric     // pointer, we know they cannot alias.
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric     // If both accesses are unknown size, we can't do anything useful here.
14090b57cec5SDimitry Andric     if (V1Size == LocationSize::unknown() && V2Size == LocationSize::unknown())
14100b57cec5SDimitry Andric       return MayAlias;
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric     AliasResult R = aliasCheck(UnderlyingV1, LocationSize::unknown(),
14130b57cec5SDimitry Andric                                AAMDNodes(), V2, LocationSize::unknown(),
14140b57cec5SDimitry Andric                                V2AAInfo, AAQI, nullptr, UnderlyingV2);
14150b57cec5SDimitry Andric     if (R != MustAlias) {
14160b57cec5SDimitry Andric       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
14170b57cec5SDimitry Andric       // If V2 is known not to alias GEP base pointer, then the two values
14180b57cec5SDimitry Andric       // cannot alias per GEP semantics: "Any memory access must be done through
14190b57cec5SDimitry Andric       // a pointer value associated with an address range of the memory access,
14200b57cec5SDimitry Andric       // otherwise the behavior is undefined.".
14210b57cec5SDimitry Andric       assert(R == NoAlias || R == MayAlias);
14220b57cec5SDimitry Andric       return R;
14230b57cec5SDimitry Andric     }
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric     // If the max search depth is reached the result is undefined
14260b57cec5SDimitry Andric     if (GEP1MaxLookupReached)
14270b57cec5SDimitry Andric       return MayAlias;
14280b57cec5SDimitry Andric   }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   // In the two GEP Case, if there is no difference in the offsets of the
14310b57cec5SDimitry Andric   // computed pointers, the resultant pointers are a must alias.  This
14320b57cec5SDimitry Andric   // happens when we have two lexically identical GEP's (for example).
14330b57cec5SDimitry Andric   //
14340b57cec5SDimitry Andric   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
14350b57cec5SDimitry Andric   // must aliases the GEP, the end result is a must alias also.
14360b57cec5SDimitry Andric   if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
14370b57cec5SDimitry Andric     return MustAlias;
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   // If there is a constant difference between the pointers, but the difference
14400b57cec5SDimitry Andric   // is less than the size of the associated memory object, then we know
14410b57cec5SDimitry Andric   // that the objects are partially overlapping.  If the difference is
14420b57cec5SDimitry Andric   // greater, we know they do not overlap.
14430b57cec5SDimitry Andric   if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
14440b57cec5SDimitry Andric     if (GEP1BaseOffset.sge(0)) {
14450b57cec5SDimitry Andric       if (V2Size != LocationSize::unknown()) {
14460b57cec5SDimitry Andric         if (GEP1BaseOffset.ult(V2Size.getValue()))
14470b57cec5SDimitry Andric           return PartialAlias;
14480b57cec5SDimitry Andric         return NoAlias;
14490b57cec5SDimitry Andric       }
14500b57cec5SDimitry Andric     } else {
14510b57cec5SDimitry Andric       // We have the situation where:
14520b57cec5SDimitry Andric       // +                +
14530b57cec5SDimitry Andric       // | BaseOffset     |
14540b57cec5SDimitry Andric       // ---------------->|
14550b57cec5SDimitry Andric       // |-->V1Size       |-------> V2Size
14560b57cec5SDimitry Andric       // GEP1             V2
14570b57cec5SDimitry Andric       // We need to know that V2Size is not unknown, otherwise we might have
14580b57cec5SDimitry Andric       // stripped a gep with negative index ('gep <ptr>, -1, ...).
14590b57cec5SDimitry Andric       if (V1Size != LocationSize::unknown() &&
14600b57cec5SDimitry Andric           V2Size != LocationSize::unknown()) {
14610b57cec5SDimitry Andric         if ((-GEP1BaseOffset).ult(V1Size.getValue()))
14620b57cec5SDimitry Andric           return PartialAlias;
14630b57cec5SDimitry Andric         return NoAlias;
14640b57cec5SDimitry Andric       }
14650b57cec5SDimitry Andric     }
14660b57cec5SDimitry Andric   }
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   if (!DecompGEP1.VarIndices.empty()) {
14690b57cec5SDimitry Andric     APInt Modulo(MaxPointerSize, 0);
14700b57cec5SDimitry Andric     bool AllPositive = true;
14710b57cec5SDimitry Andric     for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric       // Try to distinguish something like &A[i][1] against &A[42][0].
14740b57cec5SDimitry Andric       // Grab the least significant bit set in any of the scales. We
14750b57cec5SDimitry Andric       // don't need std::abs here (even if the scale's negative) as we'll
14760b57cec5SDimitry Andric       // be ^'ing Modulo with itself later.
14770b57cec5SDimitry Andric       Modulo |= DecompGEP1.VarIndices[i].Scale;
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric       if (AllPositive) {
14800b57cec5SDimitry Andric         // If the Value could change between cycles, then any reasoning about
14810b57cec5SDimitry Andric         // the Value this cycle may not hold in the next cycle. We'll just
14820b57cec5SDimitry Andric         // give up if we can't determine conditions that hold for every cycle:
14830b57cec5SDimitry Andric         const Value *V = DecompGEP1.VarIndices[i].V;
14840b57cec5SDimitry Andric 
1485480093f4SDimitry Andric         KnownBits Known =
1486480093f4SDimitry Andric             computeKnownBits(V, DL, 0, &AC, dyn_cast<Instruction>(GEP1), DT);
14870b57cec5SDimitry Andric         bool SignKnownZero = Known.isNonNegative();
14880b57cec5SDimitry Andric         bool SignKnownOne = Known.isNegative();
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric         // Zero-extension widens the variable, and so forces the sign
14910b57cec5SDimitry Andric         // bit to zero.
14920b57cec5SDimitry Andric         bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
14930b57cec5SDimitry Andric         SignKnownZero |= IsZExt;
14940b57cec5SDimitry Andric         SignKnownOne &= !IsZExt;
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric         // If the variable begins with a zero then we know it's
14970b57cec5SDimitry Andric         // positive, regardless of whether the value is signed or
14980b57cec5SDimitry Andric         // unsigned.
14990b57cec5SDimitry Andric         APInt Scale = DecompGEP1.VarIndices[i].Scale;
15000b57cec5SDimitry Andric         AllPositive =
15010b57cec5SDimitry Andric             (SignKnownZero && Scale.sge(0)) || (SignKnownOne && Scale.slt(0));
15020b57cec5SDimitry Andric       }
15030b57cec5SDimitry Andric     }
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric     Modulo = Modulo ^ (Modulo & (Modulo - 1));
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric     // We can compute the difference between the two addresses
15080b57cec5SDimitry Andric     // mod Modulo. Check whether that difference guarantees that the
15090b57cec5SDimitry Andric     // two locations do not alias.
15100b57cec5SDimitry Andric     APInt ModOffset = GEP1BaseOffset & (Modulo - 1);
15110b57cec5SDimitry Andric     if (V1Size != LocationSize::unknown() &&
15120b57cec5SDimitry Andric         V2Size != LocationSize::unknown() && ModOffset.uge(V2Size.getValue()) &&
15130b57cec5SDimitry Andric         (Modulo - ModOffset).uge(V1Size.getValue()))
15140b57cec5SDimitry Andric       return NoAlias;
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
15170b57cec5SDimitry Andric     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
15180b57cec5SDimitry Andric     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
15190b57cec5SDimitry Andric     if (AllPositive && GEP1BaseOffset.sgt(0) &&
15200b57cec5SDimitry Andric         V2Size != LocationSize::unknown() &&
15210b57cec5SDimitry Andric         GEP1BaseOffset.uge(V2Size.getValue()))
15220b57cec5SDimitry Andric       return NoAlias;
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric     if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
15250b57cec5SDimitry Andric                                 GEP1BaseOffset, &AC, DT))
15260b57cec5SDimitry Andric       return NoAlias;
15270b57cec5SDimitry Andric   }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   // Statically, we can see that the base objects are the same, but the
15300b57cec5SDimitry Andric   // pointers have dynamic offsets which we can't resolve. And none of our
15310b57cec5SDimitry Andric   // little tricks above worked.
15320b57cec5SDimitry Andric   return MayAlias;
15330b57cec5SDimitry Andric }
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
15360b57cec5SDimitry Andric   // If the results agree, take it.
15370b57cec5SDimitry Andric   if (A == B)
15380b57cec5SDimitry Andric     return A;
15390b57cec5SDimitry Andric   // A mix of PartialAlias and MustAlias is PartialAlias.
15400b57cec5SDimitry Andric   if ((A == PartialAlias && B == MustAlias) ||
15410b57cec5SDimitry Andric       (B == PartialAlias && A == MustAlias))
15420b57cec5SDimitry Andric     return PartialAlias;
15430b57cec5SDimitry Andric   // Otherwise, we don't know anything.
15440b57cec5SDimitry Andric   return MayAlias;
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
15480b57cec5SDimitry Andric /// against another.
15490b57cec5SDimitry Andric AliasResult
15500b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
15510b57cec5SDimitry Andric                            const AAMDNodes &SIAAInfo, const Value *V2,
15520b57cec5SDimitry Andric                            LocationSize V2Size, const AAMDNodes &V2AAInfo,
15530b57cec5SDimitry Andric                            const Value *UnderV2, AAQueryInfo &AAQI) {
15540b57cec5SDimitry Andric   // If the values are Selects with the same condition, we can do a more precise
15550b57cec5SDimitry Andric   // check: just check for aliases between the values on corresponding arms.
15560b57cec5SDimitry Andric   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
15570b57cec5SDimitry Andric     if (SI->getCondition() == SI2->getCondition()) {
15580b57cec5SDimitry Andric       AliasResult Alias =
15590b57cec5SDimitry Andric           aliasCheck(SI->getTrueValue(), SISize, SIAAInfo, SI2->getTrueValue(),
15600b57cec5SDimitry Andric                      V2Size, V2AAInfo, AAQI);
15610b57cec5SDimitry Andric       if (Alias == MayAlias)
15620b57cec5SDimitry Andric         return MayAlias;
15630b57cec5SDimitry Andric       AliasResult ThisAlias =
15640b57cec5SDimitry Andric           aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
15650b57cec5SDimitry Andric                      SI2->getFalseValue(), V2Size, V2AAInfo, AAQI);
15660b57cec5SDimitry Andric       return MergeAliasResults(ThisAlias, Alias);
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric   // If both arms of the Select node NoAlias or MustAlias V2, then returns
15700b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
15710b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
15720b57cec5SDimitry Andric                                  SISize, SIAAInfo, AAQI, UnderV2);
15730b57cec5SDimitry Andric   if (Alias == MayAlias)
15740b57cec5SDimitry Andric     return MayAlias;
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric   AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(),
15770b57cec5SDimitry Andric                                      SISize, SIAAInfo, AAQI, UnderV2);
15780b57cec5SDimitry Andric   return MergeAliasResults(ThisAlias, Alias);
15790b57cec5SDimitry Andric }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
15820b57cec5SDimitry Andric /// another.
15830b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
15840b57cec5SDimitry Andric                                     const AAMDNodes &PNAAInfo, const Value *V2,
15850b57cec5SDimitry Andric                                     LocationSize V2Size,
15860b57cec5SDimitry Andric                                     const AAMDNodes &V2AAInfo,
15870b57cec5SDimitry Andric                                     const Value *UnderV2, AAQueryInfo &AAQI) {
15880b57cec5SDimitry Andric   // Track phi nodes we have visited. We use this information when we determine
15890b57cec5SDimitry Andric   // value equivalence.
15900b57cec5SDimitry Andric   VisitedPhiBBs.insert(PN->getParent());
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   // If the values are PHIs in the same block, we can do a more precise
15930b57cec5SDimitry Andric   // as well as efficient check: just check for aliases between the values
15940b57cec5SDimitry Andric   // on corresponding edges.
15950b57cec5SDimitry Andric   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
15960b57cec5SDimitry Andric     if (PN2->getParent() == PN->getParent()) {
15970b57cec5SDimitry Andric       AAQueryInfo::LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
15980b57cec5SDimitry Andric                                 MemoryLocation(V2, V2Size, V2AAInfo));
15990b57cec5SDimitry Andric       if (PN > V2)
16000b57cec5SDimitry Andric         std::swap(Locs.first, Locs.second);
16010b57cec5SDimitry Andric       // Analyse the PHIs' inputs under the assumption that the PHIs are
16020b57cec5SDimitry Andric       // NoAlias.
16030b57cec5SDimitry Andric       // If the PHIs are May/MustAlias there must be (recursively) an input
16040b57cec5SDimitry Andric       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
16050b57cec5SDimitry Andric       // there must be an operation on the PHIs within the PHIs' value cycle
16060b57cec5SDimitry Andric       // that causes a MayAlias.
16070b57cec5SDimitry Andric       // Pretend the phis do not alias.
16080b57cec5SDimitry Andric       AliasResult Alias = NoAlias;
16090b57cec5SDimitry Andric       AliasResult OrigAliasResult;
16100b57cec5SDimitry Andric       {
16110b57cec5SDimitry Andric         // Limited lifetime iterator invalidated by the aliasCheck call below.
16120b57cec5SDimitry Andric         auto CacheIt = AAQI.AliasCache.find(Locs);
16130b57cec5SDimitry Andric         assert((CacheIt != AAQI.AliasCache.end()) &&
16140b57cec5SDimitry Andric                "There must exist an entry for the phi node");
16150b57cec5SDimitry Andric         OrigAliasResult = CacheIt->second;
16160b57cec5SDimitry Andric         CacheIt->second = NoAlias;
16170b57cec5SDimitry Andric       }
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
16200b57cec5SDimitry Andric         AliasResult ThisAlias =
16210b57cec5SDimitry Andric             aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
16220b57cec5SDimitry Andric                        PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
16230b57cec5SDimitry Andric                        V2Size, V2AAInfo, AAQI);
16240b57cec5SDimitry Andric         Alias = MergeAliasResults(ThisAlias, Alias);
16250b57cec5SDimitry Andric         if (Alias == MayAlias)
16260b57cec5SDimitry Andric           break;
16270b57cec5SDimitry Andric       }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric       // Reset if speculation failed.
16300b57cec5SDimitry Andric       if (Alias != NoAlias) {
16310b57cec5SDimitry Andric         auto Pair =
16320b57cec5SDimitry Andric             AAQI.AliasCache.insert(std::make_pair(Locs, OrigAliasResult));
16330b57cec5SDimitry Andric         assert(!Pair.second && "Entry must have existed");
16340b57cec5SDimitry Andric         Pair.first->second = OrigAliasResult;
16350b57cec5SDimitry Andric       }
16360b57cec5SDimitry Andric       return Alias;
16370b57cec5SDimitry Andric     }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   SmallVector<Value *, 4> V1Srcs;
16400b57cec5SDimitry Andric   bool isRecursive = false;
16410b57cec5SDimitry Andric   if (PV)  {
16420b57cec5SDimitry Andric     // If we have PhiValues then use it to get the underlying phi values.
16430b57cec5SDimitry Andric     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
16440b57cec5SDimitry Andric     // If we have more phi values than the search depth then return MayAlias
16450b57cec5SDimitry Andric     // conservatively to avoid compile time explosion. The worst possible case
16460b57cec5SDimitry Andric     // is if both sides are PHI nodes. In which case, this is O(m x n) time
16470b57cec5SDimitry Andric     // where 'm' and 'n' are the number of PHI sources.
16480b57cec5SDimitry Andric     if (PhiValueSet.size() > MaxLookupSearchDepth)
16490b57cec5SDimitry Andric       return MayAlias;
16500b57cec5SDimitry Andric     // Add the values to V1Srcs
16510b57cec5SDimitry Andric     for (Value *PV1 : PhiValueSet) {
16520b57cec5SDimitry Andric       if (EnableRecPhiAnalysis) {
16530b57cec5SDimitry Andric         if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
16540b57cec5SDimitry Andric           // Check whether the incoming value is a GEP that advances the pointer
16550b57cec5SDimitry Andric           // result of this PHI node (e.g. in a loop). If this is the case, we
16560b57cec5SDimitry Andric           // would recurse and always get a MayAlias. Handle this case specially
16570b57cec5SDimitry Andric           // below.
16580b57cec5SDimitry Andric           if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
16590b57cec5SDimitry Andric               isa<ConstantInt>(PV1GEP->idx_begin())) {
16600b57cec5SDimitry Andric             isRecursive = true;
16610b57cec5SDimitry Andric             continue;
16620b57cec5SDimitry Andric           }
16630b57cec5SDimitry Andric         }
16640b57cec5SDimitry Andric       }
16650b57cec5SDimitry Andric       V1Srcs.push_back(PV1);
16660b57cec5SDimitry Andric     }
16670b57cec5SDimitry Andric   } else {
16680b57cec5SDimitry Andric     // If we don't have PhiInfo then just look at the operands of the phi itself
16690b57cec5SDimitry Andric     // FIXME: Remove this once we can guarantee that we have PhiInfo always
16700b57cec5SDimitry Andric     SmallPtrSet<Value *, 4> UniqueSrc;
16710b57cec5SDimitry Andric     for (Value *PV1 : PN->incoming_values()) {
16720b57cec5SDimitry Andric       if (isa<PHINode>(PV1))
16730b57cec5SDimitry Andric         // If any of the source itself is a PHI, return MayAlias conservatively
16740b57cec5SDimitry Andric         // to avoid compile time explosion. The worst possible case is if both
16750b57cec5SDimitry Andric         // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
16760b57cec5SDimitry Andric         // and 'n' are the number of PHI sources.
16770b57cec5SDimitry Andric         return MayAlias;
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric       if (EnableRecPhiAnalysis)
16800b57cec5SDimitry Andric         if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
16810b57cec5SDimitry Andric           // Check whether the incoming value is a GEP that advances the pointer
16820b57cec5SDimitry Andric           // result of this PHI node (e.g. in a loop). If this is the case, we
16830b57cec5SDimitry Andric           // would recurse and always get a MayAlias. Handle this case specially
16840b57cec5SDimitry Andric           // below.
16850b57cec5SDimitry Andric           if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
16860b57cec5SDimitry Andric               isa<ConstantInt>(PV1GEP->idx_begin())) {
16870b57cec5SDimitry Andric             isRecursive = true;
16880b57cec5SDimitry Andric             continue;
16890b57cec5SDimitry Andric           }
16900b57cec5SDimitry Andric         }
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric       if (UniqueSrc.insert(PV1).second)
16930b57cec5SDimitry Andric         V1Srcs.push_back(PV1);
16940b57cec5SDimitry Andric     }
16950b57cec5SDimitry Andric   }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   // If V1Srcs is empty then that means that the phi has no underlying non-phi
16980b57cec5SDimitry Andric   // value. This should only be possible in blocks unreachable from the entry
16990b57cec5SDimitry Andric   // block, but return MayAlias just in case.
17000b57cec5SDimitry Andric   if (V1Srcs.empty())
17010b57cec5SDimitry Andric     return MayAlias;
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   // If this PHI node is recursive, set the size of the accessed memory to
17040b57cec5SDimitry Andric   // unknown to represent all the possible values the GEP could advance the
17050b57cec5SDimitry Andric   // pointer to.
17060b57cec5SDimitry Andric   if (isRecursive)
17070b57cec5SDimitry Andric     PNSize = LocationSize::unknown();
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize,
17100b57cec5SDimitry Andric                                  PNAAInfo, AAQI, UnderV2);
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   // Early exit if the check of the first PHI source against V2 is MayAlias.
17130b57cec5SDimitry Andric   // Other results are not possible.
17140b57cec5SDimitry Andric   if (Alias == MayAlias)
17150b57cec5SDimitry Andric     return MayAlias;
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
17180b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
17190b57cec5SDimitry Andric   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
17200b57cec5SDimitry Andric     Value *V = V1Srcs[i];
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric     AliasResult ThisAlias =
17230b57cec5SDimitry Andric         aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, AAQI, UnderV2);
17240b57cec5SDimitry Andric     Alias = MergeAliasResults(ThisAlias, Alias);
17250b57cec5SDimitry Andric     if (Alias == MayAlias)
17260b57cec5SDimitry Andric       break;
17270b57cec5SDimitry Andric   }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   return Alias;
17300b57cec5SDimitry Andric }
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
17330b57cec5SDimitry Andric /// array references.
17340b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
17350b57cec5SDimitry Andric                                       AAMDNodes V1AAInfo, const Value *V2,
17360b57cec5SDimitry Andric                                       LocationSize V2Size, AAMDNodes V2AAInfo,
17370b57cec5SDimitry Andric                                       AAQueryInfo &AAQI, const Value *O1,
17380b57cec5SDimitry Andric                                       const Value *O2) {
17390b57cec5SDimitry Andric   // If either of the memory references is empty, it doesn't matter what the
17400b57cec5SDimitry Andric   // pointer values are.
17410b57cec5SDimitry Andric   if (V1Size.isZero() || V2Size.isZero())
17420b57cec5SDimitry Andric     return NoAlias;
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric   // Strip off any casts if they exist.
17450b57cec5SDimitry Andric   V1 = V1->stripPointerCastsAndInvariantGroups();
17460b57cec5SDimitry Andric   V2 = V2->stripPointerCastsAndInvariantGroups();
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
17490b57cec5SDimitry Andric   // value for undef that aliases nothing in the program.
17500b57cec5SDimitry Andric   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
17510b57cec5SDimitry Andric     return NoAlias;
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   // Are we checking for alias of the same value?
17540b57cec5SDimitry Andric   // Because we look 'through' phi nodes, we could look at "Value" pointers from
17550b57cec5SDimitry Andric   // different iterations. We must therefore make sure that this is not the
17560b57cec5SDimitry Andric   // case. The function isValueEqualInPotentialCycles ensures that this cannot
17570b57cec5SDimitry Andric   // happen by looking at the visited phi nodes and making sure they cannot
17580b57cec5SDimitry Andric   // reach the value.
17590b57cec5SDimitry Andric   if (isValueEqualInPotentialCycles(V1, V2))
17600b57cec5SDimitry Andric     return MustAlias;
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
17630b57cec5SDimitry Andric     return NoAlias; // Scalars cannot alias each other
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   // Figure out what objects these things are pointing to if we can.
17660b57cec5SDimitry Andric   if (O1 == nullptr)
17670b57cec5SDimitry Andric     O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   if (O2 == nullptr)
17700b57cec5SDimitry Andric     O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   // Null values in the default address space don't point to any object, so they
17730b57cec5SDimitry Andric   // don't alias any other pointer.
17740b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
17750b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
17760b57cec5SDimitry Andric       return NoAlias;
17770b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
17780b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
17790b57cec5SDimitry Andric       return NoAlias;
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   if (O1 != O2) {
17820b57cec5SDimitry Andric     // If V1/V2 point to two different objects, we know that we have no alias.
17830b57cec5SDimitry Andric     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
17840b57cec5SDimitry Andric       return NoAlias;
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric     // Constant pointers can't alias with non-const isIdentifiedObject objects.
17870b57cec5SDimitry Andric     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
17880b57cec5SDimitry Andric         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
17890b57cec5SDimitry Andric       return NoAlias;
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric     // Function arguments can't alias with things that are known to be
17920b57cec5SDimitry Andric     // unambigously identified at the function level.
17930b57cec5SDimitry Andric     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
17940b57cec5SDimitry Andric         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
17950b57cec5SDimitry Andric       return NoAlias;
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric     // If one pointer is the result of a call/invoke or load and the other is a
17980b57cec5SDimitry Andric     // non-escaping local object within the same function, then we know the
17990b57cec5SDimitry Andric     // object couldn't escape to a point where the call could return it.
18000b57cec5SDimitry Andric     //
18010b57cec5SDimitry Andric     // Note that if the pointers are in different functions, there are a
18020b57cec5SDimitry Andric     // variety of complications. A call with a nocapture argument may still
18030b57cec5SDimitry Andric     // temporary store the nocapture argument's value in a temporary memory
18040b57cec5SDimitry Andric     // location if that memory location doesn't escape. Or it may pass a
18050b57cec5SDimitry Andric     // nocapture value to other functions as long as they don't capture it.
18060b57cec5SDimitry Andric     if (isEscapeSource(O1) &&
18070b57cec5SDimitry Andric         isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache))
18080b57cec5SDimitry Andric       return NoAlias;
18090b57cec5SDimitry Andric     if (isEscapeSource(O2) &&
18100b57cec5SDimitry Andric         isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache))
18110b57cec5SDimitry Andric       return NoAlias;
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // If the size of one access is larger than the entire object on the other
18150b57cec5SDimitry Andric   // side, then we know such behavior is undefined and can assume no alias.
18160b57cec5SDimitry Andric   bool NullIsValidLocation = NullPointerIsDefined(&F);
18178bcb0991SDimitry Andric   if ((isObjectSmallerThan(
18188bcb0991SDimitry Andric           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
18198bcb0991SDimitry Andric           TLI, NullIsValidLocation)) ||
18208bcb0991SDimitry Andric       (isObjectSmallerThan(
18218bcb0991SDimitry Andric           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
18228bcb0991SDimitry Andric           TLI, NullIsValidLocation)))
18230b57cec5SDimitry Andric     return NoAlias;
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   // Check the cache before climbing up use-def chains. This also terminates
18260b57cec5SDimitry Andric   // otherwise infinitely recursive queries.
18270b57cec5SDimitry Andric   AAQueryInfo::LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
18280b57cec5SDimitry Andric                             MemoryLocation(V2, V2Size, V2AAInfo));
18290b57cec5SDimitry Andric   if (V1 > V2)
18300b57cec5SDimitry Andric     std::swap(Locs.first, Locs.second);
18310b57cec5SDimitry Andric   std::pair<AAQueryInfo::AliasCacheT::iterator, bool> Pair =
18320b57cec5SDimitry Andric       AAQI.AliasCache.try_emplace(Locs, MayAlias);
18330b57cec5SDimitry Andric   if (!Pair.second)
18340b57cec5SDimitry Andric     return Pair.first->second;
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
18370b57cec5SDimitry Andric   // GEP can't simplify, we don't even look at the PHI cases.
18380b57cec5SDimitry Andric   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
18390b57cec5SDimitry Andric     std::swap(V1, V2);
18400b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18410b57cec5SDimitry Andric     std::swap(O1, O2);
18420b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18430b57cec5SDimitry Andric   }
18440b57cec5SDimitry Andric   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
18450b57cec5SDimitry Andric     AliasResult Result =
18460b57cec5SDimitry Andric         aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2, AAQI);
18470b57cec5SDimitry Andric     if (Result != MayAlias) {
18480b57cec5SDimitry Andric       auto ItInsPair = AAQI.AliasCache.insert(std::make_pair(Locs, Result));
18490b57cec5SDimitry Andric       assert(!ItInsPair.second && "Entry must have existed");
18500b57cec5SDimitry Andric       ItInsPair.first->second = Result;
18510b57cec5SDimitry Andric       return Result;
18520b57cec5SDimitry Andric     }
18530b57cec5SDimitry Andric   }
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
18560b57cec5SDimitry Andric     std::swap(V1, V2);
18570b57cec5SDimitry Andric     std::swap(O1, O2);
18580b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18590b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18600b57cec5SDimitry Andric   }
18610b57cec5SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
18620b57cec5SDimitry Andric     AliasResult Result =
18630b57cec5SDimitry Andric         aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
18640b57cec5SDimitry Andric     if (Result != MayAlias) {
18650b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
18660b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
18670b57cec5SDimitry Andric       return Pair.first->second = Result;
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
18720b57cec5SDimitry Andric     std::swap(V1, V2);
18730b57cec5SDimitry Andric     std::swap(O1, O2);
18740b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18750b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18760b57cec5SDimitry Andric   }
18770b57cec5SDimitry Andric   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
18780b57cec5SDimitry Andric     AliasResult Result =
18790b57cec5SDimitry Andric         aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
18800b57cec5SDimitry Andric     if (Result != MayAlias) {
18810b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
18820b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
18830b57cec5SDimitry Andric       return Pair.first->second = Result;
18840b57cec5SDimitry Andric     }
18850b57cec5SDimitry Andric   }
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric   // If both pointers are pointing into the same object and one of them
18880b57cec5SDimitry Andric   // accesses the entire object, then the accesses must overlap in some way.
18890b57cec5SDimitry Andric   if (O1 == O2)
18900b57cec5SDimitry Andric     if (V1Size.isPrecise() && V2Size.isPrecise() &&
18910b57cec5SDimitry Andric         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
18920b57cec5SDimitry Andric          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) {
18930b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, PartialAlias);
18940b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
18950b57cec5SDimitry Andric       return Pair.first->second = PartialAlias;
18960b57cec5SDimitry Andric     }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric   // Recurse back into the best AA results we have, potentially with refined
18990b57cec5SDimitry Andric   // memory locations. We have already ensured that BasicAA has a MayAlias
19000b57cec5SDimitry Andric   // cache result for these, so any recursion back into BasicAA won't loop.
19010b57cec5SDimitry Andric   AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second, AAQI);
19020b57cec5SDimitry Andric   Pair = AAQI.AliasCache.try_emplace(Locs, Result);
19030b57cec5SDimitry Andric   assert(!Pair.second && "Entry must have existed");
19040b57cec5SDimitry Andric   return Pair.first->second = Result;
19050b57cec5SDimitry Andric }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent.
19080b57cec5SDimitry Andric ///
19090b57cec5SDimitry Andric /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
19100b57cec5SDimitry Andric /// they can not be part of a cycle in the value graph by looking at all
19110b57cec5SDimitry Andric /// visited phi nodes an making sure that the phis cannot reach the value. We
19120b57cec5SDimitry Andric /// have to do this because we are looking through phi nodes (That is we say
19130b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
19140b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
19150b57cec5SDimitry Andric                                                   const Value *V2) {
19160b57cec5SDimitry Andric   if (V != V2)
19170b57cec5SDimitry Andric     return false;
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric   const Instruction *Inst = dyn_cast<Instruction>(V);
19200b57cec5SDimitry Andric   if (!Inst)
19210b57cec5SDimitry Andric     return true;
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   if (VisitedPhiBBs.empty())
19240b57cec5SDimitry Andric     return true;
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
19270b57cec5SDimitry Andric     return false;
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   // Make sure that the visited phis cannot reach the Value. This ensures that
19300b57cec5SDimitry Andric   // the Values cannot come from different iterations of a potential cycle the
19310b57cec5SDimitry Andric   // phi nodes could be involved in.
19320b57cec5SDimitry Andric   for (auto *P : VisitedPhiBBs)
19330b57cec5SDimitry Andric     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT, LI))
19340b57cec5SDimitry Andric       return false;
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric   return true;
19370b57cec5SDimitry Andric }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs.
19400b57cec5SDimitry Andric ///
19410b57cec5SDimitry Andric /// Dest and Src are the variable indices from two decomposed GetElementPtr
19420b57cec5SDimitry Andric /// instructions GEP1 and GEP2 which have common base pointers.
19430b57cec5SDimitry Andric void BasicAAResult::GetIndexDifference(
19440b57cec5SDimitry Andric     SmallVectorImpl<VariableGEPIndex> &Dest,
19450b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &Src) {
19460b57cec5SDimitry Andric   if (Src.empty())
19470b57cec5SDimitry Andric     return;
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
19500b57cec5SDimitry Andric     const Value *V = Src[i].V;
19510b57cec5SDimitry Andric     unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
19520b57cec5SDimitry Andric     APInt Scale = Src[i].Scale;
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric     // Find V in Dest.  This is N^2, but pointer indices almost never have more
19550b57cec5SDimitry Andric     // than a few variable indexes.
19560b57cec5SDimitry Andric     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
19570b57cec5SDimitry Andric       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
19580b57cec5SDimitry Andric           Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
19590b57cec5SDimitry Andric         continue;
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric       // If we found it, subtract off Scale V's from the entry in Dest.  If it
19620b57cec5SDimitry Andric       // goes to zero, remove the entry.
19630b57cec5SDimitry Andric       if (Dest[j].Scale != Scale)
19640b57cec5SDimitry Andric         Dest[j].Scale -= Scale;
19650b57cec5SDimitry Andric       else
19660b57cec5SDimitry Andric         Dest.erase(Dest.begin() + j);
19670b57cec5SDimitry Andric       Scale = 0;
19680b57cec5SDimitry Andric       break;
19690b57cec5SDimitry Andric     }
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric     // If we didn't consume this entry, add it to the end of the Dest list.
19720b57cec5SDimitry Andric     if (!!Scale) {
19730b57cec5SDimitry Andric       VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
19740b57cec5SDimitry Andric       Dest.push_back(Entry);
19750b57cec5SDimitry Andric     }
19760b57cec5SDimitry Andric   }
19770b57cec5SDimitry Andric }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric bool BasicAAResult::constantOffsetHeuristic(
19800b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &VarIndices,
19810b57cec5SDimitry Andric     LocationSize MaybeV1Size, LocationSize MaybeV2Size, APInt BaseOffset,
19820b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT) {
19830b57cec5SDimitry Andric   if (VarIndices.size() != 2 || MaybeV1Size == LocationSize::unknown() ||
19840b57cec5SDimitry Andric       MaybeV2Size == LocationSize::unknown())
19850b57cec5SDimitry Andric     return false;
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
19880b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric   const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric   if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
19930b57cec5SDimitry Andric       Var0.Scale != -Var1.Scale)
19940b57cec5SDimitry Andric     return false;
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric   unsigned Width = Var1.V->getType()->getIntegerBitWidth();
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   // We'll strip off the Extensions of Var0 and Var1 and do another round
19990b57cec5SDimitry Andric   // of GetLinearExpression decomposition. In the example above, if Var0
20000b57cec5SDimitry Andric   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
20030b57cec5SDimitry Andric       V1Offset(Width, 0);
20040b57cec5SDimitry Andric   bool NSW = true, NUW = true;
20050b57cec5SDimitry Andric   unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
20060b57cec5SDimitry Andric   const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
20070b57cec5SDimitry Andric                                         V0SExtBits, DL, 0, AC, DT, NSW, NUW);
20080b57cec5SDimitry Andric   NSW = true;
20090b57cec5SDimitry Andric   NUW = true;
20100b57cec5SDimitry Andric   const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
20110b57cec5SDimitry Andric                                         V1SExtBits, DL, 0, AC, DT, NSW, NUW);
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
20140b57cec5SDimitry Andric       V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
20150b57cec5SDimitry Andric     return false;
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   // We have a hit - Var0 and Var1 only differ by a constant offset!
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric   // If we've been sext'ed then zext'd the maximum difference between Var0 and
20200b57cec5SDimitry Andric   // Var1 is possible to calculate, but we're just interested in the absolute
20210b57cec5SDimitry Andric   // minimum difference between the two. The minimum distance may occur due to
20220b57cec5SDimitry Andric   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
20230b57cec5SDimitry Andric   // the minimum distance between %i and %i + 5 is 3.
20240b57cec5SDimitry Andric   APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
20250b57cec5SDimitry Andric   MinDiff = APIntOps::umin(MinDiff, Wrapped);
20260b57cec5SDimitry Andric   APInt MinDiffBytes =
20270b57cec5SDimitry Andric     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
20300b57cec5SDimitry Andric   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
20310b57cec5SDimitry Andric   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
20320b57cec5SDimitry Andric   // V2Size can fit in the MinDiffBytes gap.
20330b57cec5SDimitry Andric   return MinDiffBytes.uge(V1Size + BaseOffset.abs()) &&
20340b57cec5SDimitry Andric          MinDiffBytes.uge(V2Size + BaseOffset.abs());
20350b57cec5SDimitry Andric }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20380b57cec5SDimitry Andric // BasicAliasAnalysis Pass
20390b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric AnalysisKey BasicAA::Key;
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
20440b57cec5SDimitry Andric   return BasicAAResult(F.getParent()->getDataLayout(),
20450b57cec5SDimitry Andric                        F,
20460b57cec5SDimitry Andric                        AM.getResult<TargetLibraryAnalysis>(F),
20470b57cec5SDimitry Andric                        AM.getResult<AssumptionAnalysis>(F),
20480b57cec5SDimitry Andric                        &AM.getResult<DominatorTreeAnalysis>(F),
20490b57cec5SDimitry Andric                        AM.getCachedResult<LoopAnalysis>(F),
20500b57cec5SDimitry Andric                        AM.getCachedResult<PhiValuesAnalysis>(F));
20510b57cec5SDimitry Andric }
20520b57cec5SDimitry Andric 
20530b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
20540b57cec5SDimitry Andric   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
20550b57cec5SDimitry Andric }
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0;
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {}
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basicaa",
2062*b32fb2a4SDimitry Andric                       "Basic Alias Analysis (stateless AA impl)", true, true)
20630b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
20640b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
20650b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2066*b32fb2a4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
20670b57cec5SDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basicaa",
2068*b32fb2a4SDimitry Andric                     "Basic Alias Analysis (stateless AA impl)", true, true)
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() {
20710b57cec5SDimitry Andric   return new BasicAAWrapperPass();
20720b57cec5SDimitry Andric }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) {
20750b57cec5SDimitry Andric   auto &ACT = getAnalysis<AssumptionCacheTracker>();
20760b57cec5SDimitry Andric   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
20770b57cec5SDimitry Andric   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
20780b57cec5SDimitry Andric   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
20790b57cec5SDimitry Andric   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
20800b57cec5SDimitry Andric 
20818bcb0991SDimitry Andric   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
20828bcb0991SDimitry Andric                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
20838bcb0991SDimitry Andric                                  &DTWP.getDomTree(),
20840b57cec5SDimitry Andric                                  LIWP ? &LIWP->getLoopInfo() : nullptr,
20850b57cec5SDimitry Andric                                  PVWP ? &PVWP->getResult() : nullptr));
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric   return false;
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
20910b57cec5SDimitry Andric   AU.setPreservesAll();
20920b57cec5SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
20930b57cec5SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
20940b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
20950b57cec5SDimitry Andric   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
20960b57cec5SDimitry Andric }
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
20990b57cec5SDimitry Andric   return BasicAAResult(
21008bcb0991SDimitry Andric       F.getParent()->getDataLayout(), F,
21018bcb0991SDimitry Andric       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
21020b57cec5SDimitry Andric       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
21030b57cec5SDimitry Andric }
2104