LLVM  mainline
BasicAliasAnalysis.cpp
Go to the documentation of this file.
00001 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the primary stateless implementation of the
00011 // Alias Analysis interface that implements identities (two different
00012 // globals cannot alias, etc), but does no stateful analysis.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/Passes.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/AssumptionCache.h"
00021 #include "llvm/Analysis/CFG.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/LoopInfo.h"
00025 #include "llvm/Analysis/MemoryBuiltins.h"
00026 #include "llvm/Analysis/TargetLibraryInfo.h"
00027 #include "llvm/Analysis/ValueTracking.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DerivedTypes.h"
00031 #include "llvm/IR/Dominators.h"
00032 #include "llvm/IR/Function.h"
00033 #include "llvm/IR/GetElementPtrTypeIterator.h"
00034 #include "llvm/IR/GlobalAlias.h"
00035 #include "llvm/IR/GlobalVariable.h"
00036 #include "llvm/IR/Instructions.h"
00037 #include "llvm/IR/IntrinsicInst.h"
00038 #include "llvm/IR/LLVMContext.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/Pass.h"
00041 #include "llvm/Support/ErrorHandling.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
00046 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
00047 /// careful with value equivalence. We use reachability to make sure a value
00048 /// cannot be involved in a cycle.
00049 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
00050 
00051 // The max limit of the search depth in DecomposeGEPExpression() and
00052 // GetUnderlyingObject(), both functions need to use the same search
00053 // depth otherwise the algorithm in aliasGEP will assert.
00054 static const unsigned MaxLookupSearchDepth = 6;
00055 
00056 //===----------------------------------------------------------------------===//
00057 // Useful predicates
00058 //===----------------------------------------------------------------------===//
00059 
00060 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
00061 /// object that never escapes from the function.
00062 static bool isNonEscapingLocalObject(const Value *V) {
00063   // If this is a local allocation, check to see if it escapes.
00064   if (isa<AllocaInst>(V) || isNoAliasCall(V))
00065     // Set StoreCaptures to True so that we can assume in our callers that the
00066     // pointer is not the result of a load instruction. Currently
00067     // PointerMayBeCaptured doesn't have any special analysis for the
00068     // StoreCaptures=false case; if it did, our callers could be refined to be
00069     // more precise.
00070     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
00071 
00072   // If this is an argument that corresponds to a byval or noalias argument,
00073   // then it has not escaped before entering the function.  Check if it escapes
00074   // inside the function.
00075   if (const Argument *A = dyn_cast<Argument>(V))
00076     if (A->hasByValAttr() || A->hasNoAliasAttr())
00077       // Note even if the argument is marked nocapture we still need to check
00078       // for copies made inside the function. The nocapture attribute only
00079       // specifies that there are no copies made that outlive the function.
00080       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
00081 
00082   return false;
00083 }
00084 
00085 /// isEscapeSource - Return true if the pointer is one which would have
00086 /// been considered an escape by isNonEscapingLocalObject.
00087 static bool isEscapeSource(const Value *V) {
00088   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
00089     return true;
00090 
00091   // The load case works because isNonEscapingLocalObject considers all
00092   // stores to be escapes (it passes true for the StoreCaptures argument
00093   // to PointerMayBeCaptured).
00094   if (isa<LoadInst>(V))
00095     return true;
00096 
00097   return false;
00098 }
00099 
00100 /// getObjectSize - Return the size of the object specified by V, or
00101 /// UnknownSize if unknown.
00102 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
00103                               const TargetLibraryInfo &TLI,
00104                               bool RoundToAlign = false) {
00105   uint64_t Size;
00106   if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
00107     return Size;
00108   return MemoryLocation::UnknownSize;
00109 }
00110 
00111 /// isObjectSmallerThan - Return true if we can prove that the object specified
00112 /// by V is smaller than Size.
00113 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
00114                                 const DataLayout &DL,
00115                                 const TargetLibraryInfo &TLI) {
00116   // Note that the meanings of the "object" are slightly different in the
00117   // following contexts:
00118   //    c1: llvm::getObjectSize()
00119   //    c2: llvm.objectsize() intrinsic
00120   //    c3: isObjectSmallerThan()
00121   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
00122   // refers to the "entire object".
00123   //
00124   //  Consider this example:
00125   //     char *p = (char*)malloc(100)
00126   //     char *q = p+80;
00127   //
00128   //  In the context of c1 and c2, the "object" pointed by q refers to the
00129   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
00130   //
00131   //  However, in the context of c3, the "object" refers to the chunk of memory
00132   // being allocated. So, the "object" has 100 bytes, and q points to the middle
00133   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
00134   // parameter, before the llvm::getObjectSize() is called to get the size of
00135   // entire object, we should:
00136   //    - either rewind the pointer q to the base-address of the object in
00137   //      question (in this case rewind to p), or
00138   //    - just give up. It is up to caller to make sure the pointer is pointing
00139   //      to the base address the object.
00140   //
00141   // We go for 2nd option for simplicity.
00142   if (!isIdentifiedObject(V))
00143     return false;
00144 
00145   // This function needs to use the aligned object size because we allow
00146   // reads a bit past the end given sufficient alignment.
00147   uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
00148 
00149   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
00150 }
00151 
00152 /// isObjectSize - Return true if we can prove that the object specified
00153 /// by V has size Size.
00154 static bool isObjectSize(const Value *V, uint64_t Size,
00155                          const DataLayout &DL, const TargetLibraryInfo &TLI) {
00156   uint64_t ObjectSize = getObjectSize(V, DL, TLI);
00157   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
00158 }
00159 
00160 //===----------------------------------------------------------------------===//
00161 // GetElementPtr Instruction Decomposition and Analysis
00162 //===----------------------------------------------------------------------===//
00163 
00164 namespace {
00165   enum ExtensionKind {
00166     EK_NotExtended,
00167     EK_SignExt,
00168     EK_ZeroExt
00169   };
00170 
00171   struct VariableGEPIndex {
00172     const Value *V;
00173     ExtensionKind Extension;
00174     int64_t Scale;
00175 
00176     bool operator==(const VariableGEPIndex &Other) const {
00177       return V == Other.V && Extension == Other.Extension &&
00178         Scale == Other.Scale;
00179     }
00180 
00181     bool operator!=(const VariableGEPIndex &Other) const {
00182       return !operator==(Other);
00183     }
00184   };
00185 }
00186 
00187 
00188 /// GetLinearExpression - Analyze the specified value as a linear expression:
00189 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
00190 /// values as APInts and return V as a Value*, and return whether we looked
00191 /// through any sign or zero extends.  The incoming Value is known to have
00192 /// IntegerType and it may already be sign or zero extended.
00193 ///
00194 /// Note that this looks through extends, so the high bits may not be
00195 /// represented in the result.
00196 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
00197                                   ExtensionKind &Extension,
00198                                   const DataLayout &DL, unsigned Depth,
00199                                   AssumptionCache *AC, DominatorTree *DT) {
00200   assert(V->getType()->isIntegerTy() && "Not an integer value");
00201 
00202   // Limit our recursion depth.
00203   if (Depth == 6) {
00204     Scale = 1;
00205     Offset = 0;
00206     return V;
00207   }
00208 
00209   if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
00210     // if it's a constant, just convert it to an offset
00211     // and remove the variable.
00212     Offset += Const->getValue();
00213     assert(Scale == 0 && "Constant values don't have a scale");
00214     return V;
00215   }
00216 
00217   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
00218     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
00219       switch (BOp->getOpcode()) {
00220       default: break;
00221       case Instruction::Or:
00222         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
00223         // analyze it.
00224         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
00225                                BOp, DT))
00226           break;
00227         // FALL THROUGH.
00228       case Instruction::Add:
00229         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00230                                 DL, Depth + 1, AC, DT);
00231         Offset += RHSC->getValue();
00232         return V;
00233       case Instruction::Mul:
00234         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00235                                 DL, Depth + 1, AC, DT);
00236         Offset *= RHSC->getValue();
00237         Scale *= RHSC->getValue();
00238         return V;
00239       case Instruction::Shl:
00240         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
00241                                 DL, Depth + 1, AC, DT);
00242         Offset <<= RHSC->getValue().getLimitedValue();
00243         Scale <<= RHSC->getValue().getLimitedValue();
00244         return V;
00245       }
00246     }
00247   }
00248 
00249   // Since GEP indices are sign extended anyway, we don't care about the high
00250   // bits of a sign or zero extended value - just scales and offsets.  The
00251   // extensions have to be consistent though.
00252   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
00253       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
00254     Value *CastOp = cast<CastInst>(V)->getOperand(0);
00255     unsigned OldWidth = Scale.getBitWidth();
00256     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
00257     Scale = Scale.trunc(SmallWidth);
00258     Offset = Offset.trunc(SmallWidth);
00259     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
00260 
00261     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
00262                                         Depth + 1, AC, DT);
00263     Scale = Scale.zext(OldWidth);
00264 
00265     // We have to sign-extend even if Extension == EK_ZeroExt as we can't
00266     // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
00267     Offset = Offset.sext(OldWidth);
00268 
00269     return Result;
00270   }
00271 
00272   Scale = 1;
00273   Offset = 0;
00274   return V;
00275 }
00276 
00277 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
00278 /// into a base pointer with a constant offset and a number of scaled symbolic
00279 /// offsets.
00280 ///
00281 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
00282 /// the VarIndices vector) are Value*'s that are known to be scaled by the
00283 /// specified amount, but which may have other unrepresented high bits. As such,
00284 /// the gep cannot necessarily be reconstructed from its decomposed form.
00285 ///
00286 /// When DataLayout is around, this function is capable of analyzing everything
00287 /// that GetUnderlyingObject can look through. To be able to do that
00288 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
00289 /// depth (MaxLookupSearchDepth).
00290 /// When DataLayout not is around, it just looks through pointer casts.
00291 ///
00292 static const Value *
00293 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
00294                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
00295                        bool &MaxLookupReached, const DataLayout &DL,
00296                        AssumptionCache *AC, DominatorTree *DT) {
00297   // Limit recursion depth to limit compile time in crazy cases.
00298   unsigned MaxLookup = MaxLookupSearchDepth;
00299   MaxLookupReached = false;
00300 
00301   BaseOffs = 0;
00302   do {
00303     // See if this is a bitcast or GEP.
00304     const Operator *Op = dyn_cast<Operator>(V);
00305     if (!Op) {
00306       // The only non-operator case we can handle are GlobalAliases.
00307       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00308         if (!GA->mayBeOverridden()) {
00309           V = GA->getAliasee();
00310           continue;
00311         }
00312       }
00313       return V;
00314     }
00315 
00316     if (Op->getOpcode() == Instruction::BitCast ||
00317         Op->getOpcode() == Instruction::AddrSpaceCast) {
00318       V = Op->getOperand(0);
00319       continue;
00320     }
00321 
00322     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
00323     if (!GEPOp) {
00324       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
00325       // can come up with something. This matches what GetUnderlyingObject does.
00326       if (const Instruction *I = dyn_cast<Instruction>(V))
00327         // TODO: Get a DominatorTree and AssumptionCache and use them here
00328         // (these are both now available in this function, but this should be
00329         // updated when GetUnderlyingObject is updated). TLI should be
00330         // provided also.
00331         if (const Value *Simplified =
00332               SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
00333           V = Simplified;
00334           continue;
00335         }
00336 
00337       return V;
00338     }
00339 
00340     // Don't attempt to analyze GEPs over unsized objects.
00341     if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
00342       return V;
00343 
00344     unsigned AS = GEPOp->getPointerAddressSpace();
00345     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
00346     gep_type_iterator GTI = gep_type_begin(GEPOp);
00347     for (User::const_op_iterator I = GEPOp->op_begin()+1,
00348          E = GEPOp->op_end(); I != E; ++I) {
00349       Value *Index = *I;
00350       // Compute the (potentially symbolic) offset in bytes for this index.
00351       if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
00352         // For a struct, add the member offset.
00353         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
00354         if (FieldNo == 0) continue;
00355 
00356         BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
00357         continue;
00358       }
00359 
00360       // For an array/pointer, add the element offset, explicitly scaled.
00361       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
00362         if (CIdx->isZero()) continue;
00363         BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
00364         continue;
00365       }
00366 
00367       uint64_t Scale = DL.getTypeAllocSize(*GTI);
00368       ExtensionKind Extension = EK_NotExtended;
00369 
00370       // If the integer type is smaller than the pointer size, it is implicitly
00371       // sign extended to pointer size.
00372       unsigned Width = Index->getType()->getIntegerBitWidth();
00373       if (DL.getPointerSizeInBits(AS) > Width)
00374         Extension = EK_SignExt;
00375 
00376       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
00377       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
00378       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
00379                                   0, AC, DT);
00380 
00381       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
00382       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
00383       BaseOffs += IndexOffset.getSExtValue()*Scale;
00384       Scale *= IndexScale.getSExtValue();
00385 
00386       // If we already had an occurrence of this index variable, merge this
00387       // scale into it.  For example, we want to handle:
00388       //   A[x][x] -> x*16 + x*4 -> x*20
00389       // This also ensures that 'x' only appears in the index list once.
00390       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
00391         if (VarIndices[i].V == Index &&
00392             VarIndices[i].Extension == Extension) {
00393           Scale += VarIndices[i].Scale;
00394           VarIndices.erase(VarIndices.begin()+i);
00395           break;
00396         }
00397       }
00398 
00399       // Make sure that we have a scale that makes sense for this target's
00400       // pointer size.
00401       if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
00402         Scale <<= ShiftBits;
00403         Scale = (int64_t)Scale >> ShiftBits;
00404       }
00405 
00406       if (Scale) {
00407         VariableGEPIndex Entry = {Index, Extension,
00408                                   static_cast<int64_t>(Scale)};
00409         VarIndices.push_back(Entry);
00410       }
00411     }
00412 
00413     // Analyze the base pointer next.
00414     V = GEPOp->getOperand(0);
00415   } while (--MaxLookup);
00416 
00417   // If the chain of expressions is too deep, just return early.
00418   MaxLookupReached = true;
00419   return V;
00420 }
00421 
00422 //===----------------------------------------------------------------------===//
00423 // BasicAliasAnalysis Pass
00424 //===----------------------------------------------------------------------===//
00425 
00426 #ifndef NDEBUG
00427 static const Function *getParent(const Value *V) {
00428   if (const Instruction *inst = dyn_cast<Instruction>(V))
00429     return inst->getParent()->getParent();
00430 
00431   if (const Argument *arg = dyn_cast<Argument>(V))
00432     return arg->getParent();
00433 
00434   return nullptr;
00435 }
00436 
00437 static bool notDifferentParent(const Value *O1, const Value *O2) {
00438 
00439   const Function *F1 = getParent(O1);
00440   const Function *F2 = getParent(O2);
00441 
00442   return !F1 || !F2 || F1 == F2;
00443 }
00444 #endif
00445 
00446 namespace {
00447   /// BasicAliasAnalysis - This is the primary alias analysis implementation.
00448   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
00449     static char ID; // Class identification, replacement for typeinfo
00450     BasicAliasAnalysis() : ImmutablePass(ID) {
00451       initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
00452     }
00453 
00454     bool doInitialization(Module &M) override;
00455 
00456     void getAnalysisUsage(AnalysisUsage &AU) const override {
00457       AU.addRequired<AliasAnalysis>();
00458       AU.addRequired<AssumptionCacheTracker>();
00459       AU.addRequired<TargetLibraryInfoWrapperPass>();
00460     }
00461 
00462     AliasResult alias(const MemoryLocation &LocA,
00463                       const MemoryLocation &LocB) override {
00464       assert(AliasCache.empty() && "AliasCache must be cleared after use!");
00465       assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
00466              "BasicAliasAnalysis doesn't support interprocedural queries.");
00467       AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
00468                                      LocB.Ptr, LocB.Size, LocB.AATags);
00469       // AliasCache rarely has more than 1 or 2 elements, always use
00470       // shrink_and_clear so it quickly returns to the inline capacity of the
00471       // SmallDenseMap if it ever grows larger.
00472       // FIXME: This should really be shrink_to_inline_capacity_and_clear().
00473       AliasCache.shrink_and_clear();
00474       VisitedPhiBBs.clear();
00475       return Alias;
00476     }
00477 
00478     ModRefResult getModRefInfo(ImmutableCallSite CS,
00479                                const MemoryLocation &Loc) override;
00480 
00481     ModRefResult getModRefInfo(ImmutableCallSite CS1,
00482                                ImmutableCallSite CS2) override;
00483 
00484     /// pointsToConstantMemory - Chase pointers until we find a (constant
00485     /// global) or not.
00486     bool pointsToConstantMemory(const MemoryLocation &Loc,
00487                                 bool OrLocal) override;
00488 
00489     /// Get the location associated with a pointer argument of a callsite.
00490     ModRefResult getArgModRefInfo(ImmutableCallSite CS,
00491                                   unsigned ArgIdx) override;
00492 
00493     /// getModRefBehavior - Return the behavior when calling the given
00494     /// call site.
00495     ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
00496 
00497     /// getModRefBehavior - Return the behavior when calling the given function.
00498     /// For use when the call site is not known.
00499     ModRefBehavior getModRefBehavior(const Function *F) override;
00500 
00501     /// getAdjustedAnalysisPointer - This method is used when a pass implements
00502     /// an analysis interface through multiple inheritance.  If needed, it
00503     /// should override this to adjust the this pointer as needed for the
00504     /// specified pass info.
00505     void *getAdjustedAnalysisPointer(const void *ID) override {
00506       if (ID == &AliasAnalysis::ID)
00507         return (AliasAnalysis*)this;
00508       return this;
00509     }
00510 
00511   private:
00512     // AliasCache - Track alias queries to guard against recursion.
00513     typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
00514     typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
00515     AliasCacheTy AliasCache;
00516 
00517     /// \brief Track phi nodes we have visited. When interpret "Value" pointer
00518     /// equality as value equality we need to make sure that the "Value" is not
00519     /// part of a cycle. Otherwise, two uses could come from different
00520     /// "iterations" of a cycle and see different values for the same "Value"
00521     /// pointer.
00522     /// The following example shows the problem:
00523     ///   %p = phi(%alloca1, %addr2)
00524     ///   %l = load %ptr
00525     ///   %addr1 = gep, %alloca2, 0, %l
00526     ///   %addr2 = gep  %alloca2, 0, (%l + 1)
00527     ///      alias(%p, %addr1) -> MayAlias !
00528     ///   store %l, ...
00529     SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
00530 
00531     // Visited - Track instructions visited by pointsToConstantMemory.
00532     SmallPtrSet<const Value*, 16> Visited;
00533 
00534     /// \brief Check whether two Values can be considered equivalent.
00535     ///
00536     /// In addition to pointer equivalence of \p V1 and \p V2 this checks
00537     /// whether they can not be part of a cycle in the value graph by looking at
00538     /// all visited phi nodes an making sure that the phis cannot reach the
00539     /// value. We have to do this because we are looking through phi nodes (That
00540     /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
00541     bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
00542 
00543     /// \brief Dest and Src are the variable indices from two decomposed
00544     /// GetElementPtr instructions GEP1 and GEP2 which have common base
00545     /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
00546     /// difference between the two pointers.
00547     void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
00548                             const SmallVectorImpl<VariableGEPIndex> &Src);
00549 
00550     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
00551     // instruction against another.
00552     AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
00553                          const AAMDNodes &V1AAInfo,
00554                          const Value *V2, uint64_t V2Size,
00555                          const AAMDNodes &V2AAInfo,
00556                          const Value *UnderlyingV1, const Value *UnderlyingV2);
00557 
00558     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
00559     // instruction against another.
00560     AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
00561                          const AAMDNodes &PNAAInfo,
00562                          const Value *V2, uint64_t V2Size,
00563                          const AAMDNodes &V2AAInfo);
00564 
00565     /// aliasSelect - Disambiguate a Select instruction against another value.
00566     AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
00567                             const AAMDNodes &SIAAInfo,
00568                             const Value *V2, uint64_t V2Size,
00569                             const AAMDNodes &V2AAInfo);
00570 
00571     AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
00572                            AAMDNodes V1AATag,
00573                            const Value *V2, uint64_t V2Size,
00574                            AAMDNodes V2AATag);
00575   };
00576 }  // End of anonymous namespace
00577 
00578 // Register this pass...
00579 char BasicAliasAnalysis::ID = 0;
00580 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
00581                    "Basic Alias Analysis (stateless AA impl)",
00582                    false, true, false)
00583 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00584 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00585 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
00586                    "Basic Alias Analysis (stateless AA impl)",
00587                    false, true, false)
00588 
00589 
00590 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
00591   return new BasicAliasAnalysis();
00592 }
00593 
00594 /// pointsToConstantMemory - Returns whether the given pointer value
00595 /// points to memory that is local to the function, with global constants being
00596 /// considered local to all functions.
00597 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
00598                                                 bool OrLocal) {
00599   assert(Visited.empty() && "Visited must be cleared after use!");
00600 
00601   unsigned MaxLookup = 8;
00602   SmallVector<const Value *, 16> Worklist;
00603   Worklist.push_back(Loc.Ptr);
00604   do {
00605     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
00606     if (!Visited.insert(V).second) {
00607       Visited.clear();
00608       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00609     }
00610 
00611     // An alloca instruction defines local memory.
00612     if (OrLocal && isa<AllocaInst>(V))
00613       continue;
00614 
00615     // A global constant counts as local memory for our purposes.
00616     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
00617       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
00618       // global to be marked constant in some modules and non-constant in
00619       // others.  GV may even be a declaration, not a definition.
00620       if (!GV->isConstant()) {
00621         Visited.clear();
00622         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00623       }
00624       continue;
00625     }
00626 
00627     // If both select values point to local memory, then so does the select.
00628     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
00629       Worklist.push_back(SI->getTrueValue());
00630       Worklist.push_back(SI->getFalseValue());
00631       continue;
00632     }
00633 
00634     // If all values incoming to a phi node point to local memory, then so does
00635     // the phi.
00636     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
00637       // Don't bother inspecting phi nodes with many operands.
00638       if (PN->getNumIncomingValues() > MaxLookup) {
00639         Visited.clear();
00640         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00641       }
00642       for (Value *IncValue : PN->incoming_values())
00643         Worklist.push_back(IncValue);
00644       continue;
00645     }
00646 
00647     // Otherwise be conservative.
00648     Visited.clear();
00649     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
00650 
00651   } while (!Worklist.empty() && --MaxLookup);
00652 
00653   Visited.clear();
00654   return Worklist.empty();
00655 }
00656 
00657 // FIXME: This code is duplicated with MemoryLocation and should be hoisted to
00658 // some common utility location.
00659 static bool isMemsetPattern16(const Function *MS,
00660                               const TargetLibraryInfo &TLI) {
00661   if (TLI.has(LibFunc::memset_pattern16) &&
00662       MS->getName() == "memset_pattern16") {
00663     FunctionType *MemsetType = MS->getFunctionType();
00664     if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
00665         isa<PointerType>(MemsetType->getParamType(0)) &&
00666         isa<PointerType>(MemsetType->getParamType(1)) &&
00667         isa<IntegerType>(MemsetType->getParamType(2)))
00668       return true;
00669   }
00670 
00671   return false;
00672 }
00673 
00674 /// getModRefBehavior - Return the behavior when calling the given call site.
00675 AliasAnalysis::ModRefBehavior
00676 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
00677   if (CS.doesNotAccessMemory())
00678     // Can't do better than this.
00679     return DoesNotAccessMemory;
00680 
00681   ModRefBehavior Min = UnknownModRefBehavior;
00682 
00683   // If the callsite knows it only reads memory, don't return worse
00684   // than that.
00685   if (CS.onlyReadsMemory())
00686     Min = OnlyReadsMemory;
00687 
00688   // The AliasAnalysis base class has some smarts, lets use them.
00689   return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
00690 }
00691 
00692 /// getModRefBehavior - Return the behavior when calling the given function.
00693 /// For use when the call site is not known.
00694 AliasAnalysis::ModRefBehavior
00695 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
00696   // If the function declares it doesn't access memory, we can't do better.
00697   if (F->doesNotAccessMemory())
00698     return DoesNotAccessMemory;
00699 
00700   // For intrinsics, we can check the table.
00701   if (Intrinsic::ID iid = F->getIntrinsicID()) {
00702 #define GET_INTRINSIC_MODREF_BEHAVIOR
00703 #include "llvm/IR/Intrinsics.gen"
00704 #undef GET_INTRINSIC_MODREF_BEHAVIOR
00705   }
00706 
00707   ModRefBehavior Min = UnknownModRefBehavior;
00708 
00709   // If the function declares it only reads memory, go with that.
00710   if (F->onlyReadsMemory())
00711     Min = OnlyReadsMemory;
00712 
00713   const TargetLibraryInfo &TLI =
00714       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00715   if (isMemsetPattern16(F, TLI))
00716     Min = OnlyAccessesArgumentPointees;
00717 
00718   // Otherwise be conservative.
00719   return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
00720 }
00721 
00722 AliasAnalysis::ModRefResult
00723 BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
00724   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
00725     switch (II->getIntrinsicID()) {
00726     default:
00727       break;
00728     case Intrinsic::memset:
00729     case Intrinsic::memcpy:
00730     case Intrinsic::memmove:
00731       assert((ArgIdx == 0 || ArgIdx == 1) &&
00732              "Invalid argument index for memory intrinsic");
00733       return ArgIdx ? Ref : Mod;
00734     }
00735 
00736   // We can bound the aliasing properties of memset_pattern16 just as we can
00737   // for memcpy/memset.  This is particularly important because the
00738   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
00739   // whenever possible.
00740   if (CS.getCalledFunction() &&
00741       isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
00742     assert((ArgIdx == 0 || ArgIdx == 1) &&
00743            "Invalid argument index for memset_pattern16");
00744     return ArgIdx ? Ref : Mod;
00745   }
00746   // FIXME: Handle memset_pattern4 and memset_pattern8 also.
00747 
00748   return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
00749 }
00750 
00751 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
00752   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
00753   if (II && II->getIntrinsicID() == Intrinsic::assume)
00754     return true;
00755 
00756   return false;
00757 }
00758 
00759 bool BasicAliasAnalysis::doInitialization(Module &M) {
00760   InitializeAliasAnalysis(this, &M.getDataLayout());
00761   return true;
00762 }
00763 
00764 /// getModRefInfo - Check to see if the specified callsite can clobber the
00765 /// specified memory object.  Since we only look at local properties of this
00766 /// function, we really can't say much about this query.  We do, however, use
00767 /// simple "address taken" analysis on local objects.
00768 AliasAnalysis::ModRefResult
00769 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
00770                                   const MemoryLocation &Loc) {
00771   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
00772          "AliasAnalysis query involving multiple functions!");
00773 
00774   const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
00775 
00776   // If this is a tail call and Loc.Ptr points to a stack location, we know that
00777   // the tail call cannot access or modify the local stack.
00778   // We cannot exclude byval arguments here; these belong to the caller of
00779   // the current function not to the current function, and a tail callee
00780   // may reference them.
00781   if (isa<AllocaInst>(Object))
00782     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
00783       if (CI->isTailCall())
00784         return NoModRef;
00785 
00786   // If the pointer is to a locally allocated object that does not escape,
00787   // then the call can not mod/ref the pointer unless the call takes the pointer
00788   // as an argument, and itself doesn't capture it.
00789   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
00790       isNonEscapingLocalObject(Object)) {
00791     bool PassedAsArg = false;
00792     unsigned ArgNo = 0;
00793     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
00794          CI != CE; ++CI, ++ArgNo) {
00795       // Only look at the no-capture or byval pointer arguments.  If this
00796       // pointer were passed to arguments that were neither of these, then it
00797       // couldn't be no-capture.
00798       if (!(*CI)->getType()->isPointerTy() ||
00799           (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
00800         continue;
00801 
00802       // If this is a no-capture pointer argument, see if we can tell that it
00803       // is impossible to alias the pointer we're checking.  If not, we have to
00804       // assume that the call could touch the pointer, even though it doesn't
00805       // escape.
00806       if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
00807         PassedAsArg = true;
00808         break;
00809       }
00810     }
00811 
00812     if (!PassedAsArg)
00813       return NoModRef;
00814   }
00815 
00816   // While the assume intrinsic is marked as arbitrarily writing so that
00817   // proper control dependencies will be maintained, it never aliases any
00818   // particular memory location.
00819   if (isAssumeIntrinsic(CS))
00820     return NoModRef;
00821 
00822   // The AliasAnalysis base class has some smarts, lets use them.
00823   return AliasAnalysis::getModRefInfo(CS, Loc);
00824 }
00825 
00826 AliasAnalysis::ModRefResult
00827 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
00828                                   ImmutableCallSite CS2) {
00829   // While the assume intrinsic is marked as arbitrarily writing so that
00830   // proper control dependencies will be maintained, it never aliases any
00831   // particular memory location.
00832   if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
00833     return NoModRef;
00834 
00835   // The AliasAnalysis base class has some smarts, lets use them.
00836   return AliasAnalysis::getModRefInfo(CS1, CS2);
00837 }
00838 
00839 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
00840 /// operators, both having the exact same pointer operand.
00841 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
00842                                             uint64_t V1Size,
00843                                             const GEPOperator *GEP2,
00844                                             uint64_t V2Size,
00845                                             const DataLayout &DL) {
00846 
00847   assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
00848          "Expected GEPs with the same pointer operand");
00849 
00850   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
00851   // such that the struct field accesses provably cannot alias.
00852   // We also need at least two indices (the pointer, and the struct field).
00853   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
00854       GEP1->getNumIndices() < 2)
00855     return MayAlias;
00856 
00857   // If we don't know the size of the accesses through both GEPs, we can't
00858   // determine whether the struct fields accessed can't alias.
00859   if (V1Size == MemoryLocation::UnknownSize ||
00860       V2Size == MemoryLocation::UnknownSize)
00861     return MayAlias;
00862 
00863   ConstantInt *C1 =
00864       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
00865   ConstantInt *C2 =
00866       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
00867 
00868   // If the last (struct) indices aren't constants, we can't say anything.
00869   // If they're identical, the other indices might be also be dynamically
00870   // equal, so the GEPs can alias.
00871   if (!C1 || !C2 || C1 == C2)
00872     return MayAlias;
00873 
00874   // Find the last-indexed type of the GEP, i.e., the type you'd get if
00875   // you stripped the last index.
00876   // On the way, look at each indexed type.  If there's something other
00877   // than an array, different indices can lead to different final types.
00878   SmallVector<Value *, 8> IntermediateIndices;
00879 
00880   // Insert the first index; we don't need to check the type indexed
00881   // through it as it only drops the pointer indirection.
00882   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
00883   IntermediateIndices.push_back(GEP1->getOperand(1));
00884 
00885   // Insert all the remaining indices but the last one.
00886   // Also, check that they all index through arrays.
00887   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
00888     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
00889             GEP1->getSourceElementType(), IntermediateIndices)))
00890       return MayAlias;
00891     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
00892   }
00893 
00894   StructType *LastIndexedStruct =
00895       dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
00896           GEP1->getSourceElementType(), IntermediateIndices));
00897 
00898   if (!LastIndexedStruct)
00899     return MayAlias;
00900 
00901   // We know that:
00902   // - both GEPs begin indexing from the exact same pointer;
00903   // - the last indices in both GEPs are constants, indexing into a struct;
00904   // - said indices are different, hence, the pointed-to fields are different;
00905   // - both GEPs only index through arrays prior to that.
00906   //
00907   // This lets us determine that the struct that GEP1 indexes into and the
00908   // struct that GEP2 indexes into must either precisely overlap or be
00909   // completely disjoint.  Because they cannot partially overlap, indexing into
00910   // different non-overlapping fields of the struct will never alias.
00911 
00912   // Therefore, the only remaining thing needed to show that both GEPs can't
00913   // alias is that the fields are not overlapping.
00914   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
00915   const uint64_t StructSize = SL->getSizeInBytes();
00916   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
00917   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
00918 
00919   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
00920                                       uint64_t V2Off, uint64_t V2Size) {
00921     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
00922            ((V2Off + V2Size <= StructSize) ||
00923             (V2Off + V2Size - StructSize <= V1Off));
00924   };
00925 
00926   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
00927       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
00928     return NoAlias;
00929 
00930   return MayAlias;
00931 }
00932 
00933 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
00934 /// against another pointer.  We know that V1 is a GEP, but we don't know
00935 /// anything about V2.  UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
00936 /// UnderlyingV2 is the same for V2.
00937 ///
00938 AliasResult BasicAliasAnalysis::aliasGEP(
00939     const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
00940     const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
00941     const Value *UnderlyingV1, const Value *UnderlyingV2) {
00942   int64_t GEP1BaseOffset;
00943   bool GEP1MaxLookupReached;
00944   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
00945 
00946   // We have to get two AssumptionCaches here because GEP1 and V2 may be from
00947   // different functions.
00948   // FIXME: This really doesn't make any sense. We get a dominator tree below
00949   // that can only refer to a single function. But this function (aliasGEP) is
00950   // a method on an immutable pass that can be called when there *isn't*
00951   // a single function. The old pass management layer makes this "work", but
00952   // this isn't really a clean solution.
00953   AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
00954   AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
00955   if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
00956     AC1 = &ACT.getAssumptionCache(
00957         const_cast<Function &>(*GEP1I->getParent()->getParent()));
00958   if (auto *I2 = dyn_cast<Instruction>(V2))
00959     AC2 = &ACT.getAssumptionCache(
00960         const_cast<Function &>(*I2->getParent()->getParent()));
00961 
00962   DominatorTreeWrapperPass *DTWP =
00963       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00964   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00965 
00966   // If we have two gep instructions with must-alias or not-alias'ing base
00967   // pointers, figure out if the indexes to the GEP tell us anything about the
00968   // derived pointer.
00969   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
00970     // Do the base pointers alias?
00971     AliasResult BaseAlias =
00972         aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
00973                    UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
00974 
00975     // Check for geps of non-aliasing underlying pointers where the offsets are
00976     // identical.
00977     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
00978       // Do the base pointers alias assuming type and size.
00979       AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
00980                                                 V1AAInfo, UnderlyingV2,
00981                                                 V2Size, V2AAInfo);
00982       if (PreciseBaseAlias == NoAlias) {
00983         // See if the computed offset from the common pointer tells us about the
00984         // relation of the resulting pointer.
00985         int64_t GEP2BaseOffset;
00986         bool GEP2MaxLookupReached;
00987         SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
00988         const Value *GEP2BasePtr =
00989             DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
00990                                    GEP2MaxLookupReached, *DL, AC2, DT);
00991         const Value *GEP1BasePtr =
00992             DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
00993                                    GEP1MaxLookupReached, *DL, AC1, DT);
00994         // DecomposeGEPExpression and GetUnderlyingObject should return the
00995         // same result except when DecomposeGEPExpression has no DataLayout.
00996         if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
00997           assert(!DL &&
00998                  "DecomposeGEPExpression and GetUnderlyingObject disagree!");
00999           return MayAlias;
01000         }
01001         // If the max search depth is reached the result is undefined
01002         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
01003           return MayAlias;
01004 
01005         // Same offsets.
01006         if (GEP1BaseOffset == GEP2BaseOffset &&
01007             GEP1VariableIndices == GEP2VariableIndices)
01008           return NoAlias;
01009         GEP1VariableIndices.clear();
01010       }
01011     }
01012 
01013     // If we get a No or May, then return it immediately, no amount of analysis
01014     // will improve this situation.
01015     if (BaseAlias != MustAlias) return BaseAlias;
01016 
01017     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
01018     // exactly, see if the computed offset from the common pointer tells us
01019     // about the relation of the resulting pointer.
01020     const Value *GEP1BasePtr =
01021         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
01022                                GEP1MaxLookupReached, *DL, AC1, DT);
01023 
01024     int64_t GEP2BaseOffset;
01025     bool GEP2MaxLookupReached;
01026     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
01027     const Value *GEP2BasePtr =
01028         DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
01029                                GEP2MaxLookupReached, *DL, AC2, DT);
01030 
01031     // DecomposeGEPExpression and GetUnderlyingObject should return the
01032     // same result except when DecomposeGEPExpression has no DataLayout.
01033     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
01034       assert(!DL &&
01035              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
01036       return MayAlias;
01037     }
01038 
01039     // If we know the two GEPs are based off of the exact same pointer (and not
01040     // just the same underlying object), see if that tells us anything about
01041     // the resulting pointers.
01042     if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
01043       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
01044       // If we couldn't find anything interesting, don't abandon just yet.
01045       if (R != MayAlias)
01046         return R;
01047     }
01048 
01049     // If the max search depth is reached the result is undefined
01050     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
01051       return MayAlias;
01052 
01053     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
01054     // symbolic difference.
01055     GEP1BaseOffset -= GEP2BaseOffset;
01056     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
01057 
01058   } else {
01059     // Check to see if these two pointers are related by the getelementptr
01060     // instruction.  If one pointer is a GEP with a non-zero index of the other
01061     // pointer, we know they cannot alias.
01062 
01063     // If both accesses are unknown size, we can't do anything useful here.
01064     if (V1Size == MemoryLocation::UnknownSize &&
01065         V2Size == MemoryLocation::UnknownSize)
01066       return MayAlias;
01067 
01068     AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
01069                                AAMDNodes(), V2, V2Size, V2AAInfo);
01070     if (R != MustAlias)
01071       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
01072       // If V2 is known not to alias GEP base pointer, then the two values
01073       // cannot alias per GEP semantics: "A pointer value formed from a
01074       // getelementptr instruction is associated with the addresses associated
01075       // with the first operand of the getelementptr".
01076       return R;
01077 
01078     const Value *GEP1BasePtr =
01079         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
01080                                GEP1MaxLookupReached, *DL, AC1, DT);
01081 
01082     // DecomposeGEPExpression and GetUnderlyingObject should return the
01083     // same result except when DecomposeGEPExpression has no DataLayout.
01084     if (GEP1BasePtr != UnderlyingV1) {
01085       assert(!DL &&
01086              "DecomposeGEPExpression and GetUnderlyingObject disagree!");
01087       return MayAlias;
01088     }
01089     // If the max search depth is reached the result is undefined
01090     if (GEP1MaxLookupReached)
01091       return MayAlias;
01092   }
01093 
01094   // In the two GEP Case, if there is no difference in the offsets of the
01095   // computed pointers, the resultant pointers are a must alias.  This
01096   // hapens when we have two lexically identical GEP's (for example).
01097   //
01098   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
01099   // must aliases the GEP, the end result is a must alias also.
01100   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
01101     return MustAlias;
01102 
01103   // If there is a constant difference between the pointers, but the difference
01104   // is less than the size of the associated memory object, then we know
01105   // that the objects are partially overlapping.  If the difference is
01106   // greater, we know they do not overlap.
01107   if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
01108     if (GEP1BaseOffset >= 0) {
01109       if (V2Size != MemoryLocation::UnknownSize) {
01110         if ((uint64_t)GEP1BaseOffset < V2Size)
01111           return PartialAlias;
01112         return NoAlias;
01113       }
01114     } else {
01115       // We have the situation where:
01116       // +                +
01117       // | BaseOffset     |
01118       // ---------------->|
01119       // |-->V1Size       |-------> V2Size
01120       // GEP1             V2
01121       // We need to know that V2Size is not unknown, otherwise we might have
01122       // stripped a gep with negative index ('gep <ptr>, -1, ...).
01123       if (V1Size != MemoryLocation::UnknownSize &&
01124           V2Size != MemoryLocation::UnknownSize) {
01125         if (-(uint64_t)GEP1BaseOffset < V1Size)
01126           return PartialAlias;
01127         return NoAlias;
01128       }
01129     }
01130   }
01131 
01132   if (!GEP1VariableIndices.empty()) {
01133     uint64_t Modulo = 0;
01134     bool AllPositive = true;
01135     for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
01136 
01137       // Try to distinguish something like &A[i][1] against &A[42][0].
01138       // Grab the least significant bit set in any of the scales. We
01139       // don't need std::abs here (even if the scale's negative) as we'll
01140       // be ^'ing Modulo with itself later.
01141       Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
01142 
01143       if (AllPositive) {
01144         // If the Value could change between cycles, then any reasoning about
01145         // the Value this cycle may not hold in the next cycle. We'll just
01146         // give up if we can't determine conditions that hold for every cycle:
01147         const Value *V = GEP1VariableIndices[i].V;
01148 
01149         bool SignKnownZero, SignKnownOne;
01150         ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
01151                        0, AC1, nullptr, DT);
01152 
01153         // Zero-extension widens the variable, and so forces the sign
01154         // bit to zero.
01155         bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
01156         SignKnownZero |= IsZExt;
01157         SignKnownOne &= !IsZExt;
01158 
01159         // If the variable begins with a zero then we know it's
01160         // positive, regardless of whether the value is signed or
01161         // unsigned.
01162         int64_t Scale = GEP1VariableIndices[i].Scale;
01163         AllPositive =
01164           (SignKnownZero && Scale >= 0) ||
01165           (SignKnownOne && Scale < 0);
01166       }
01167     }
01168 
01169     Modulo = Modulo ^ (Modulo & (Modulo - 1));
01170 
01171     // We can compute the difference between the two addresses
01172     // mod Modulo. Check whether that difference guarantees that the
01173     // two locations do not alias.
01174     uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
01175     if (V1Size != MemoryLocation::UnknownSize &&
01176         V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
01177         V1Size <= Modulo - ModOffset)
01178       return NoAlias;
01179 
01180     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
01181     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
01182     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
01183     if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
01184       return NoAlias;
01185   }
01186 
01187   // Statically, we can see that the base objects are the same, but the
01188   // pointers have dynamic offsets which we can't resolve. And none of our
01189   // little tricks above worked.
01190   //
01191   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
01192   // practical effect of this is protecting TBAA in the case of dynamic
01193   // indices into arrays of unions or malloc'd memory.
01194   return PartialAlias;
01195 }
01196 
01197 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
01198   // If the results agree, take it.
01199   if (A == B)
01200     return A;
01201   // A mix of PartialAlias and MustAlias is PartialAlias.
01202   if ((A == PartialAlias && B == MustAlias) ||
01203       (B == PartialAlias && A == MustAlias))
01204     return PartialAlias;
01205   // Otherwise, we don't know anything.
01206   return MayAlias;
01207 }
01208 
01209 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
01210 /// instruction against another.
01211 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
01212                                             uint64_t SISize,
01213                                             const AAMDNodes &SIAAInfo,
01214                                             const Value *V2, uint64_t V2Size,
01215                                             const AAMDNodes &V2AAInfo) {
01216   // If the values are Selects with the same condition, we can do a more precise
01217   // check: just check for aliases between the values on corresponding arms.
01218   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
01219     if (SI->getCondition() == SI2->getCondition()) {
01220       AliasResult Alias =
01221         aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
01222                    SI2->getTrueValue(), V2Size, V2AAInfo);
01223       if (Alias == MayAlias)
01224         return MayAlias;
01225       AliasResult ThisAlias =
01226         aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
01227                    SI2->getFalseValue(), V2Size, V2AAInfo);
01228       return MergeAliasResults(ThisAlias, Alias);
01229     }
01230 
01231   // If both arms of the Select node NoAlias or MustAlias V2, then returns
01232   // NoAlias / MustAlias. Otherwise, returns MayAlias.
01233   AliasResult Alias =
01234     aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
01235   if (Alias == MayAlias)
01236     return MayAlias;
01237 
01238   AliasResult ThisAlias =
01239     aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
01240   return MergeAliasResults(ThisAlias, Alias);
01241 }
01242 
01243 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
01244 // against another.
01245 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
01246                                          const AAMDNodes &PNAAInfo,
01247                                          const Value *V2, uint64_t V2Size,
01248                                          const AAMDNodes &V2AAInfo) {
01249   // Track phi nodes we have visited. We use this information when we determine
01250   // value equivalence.
01251   VisitedPhiBBs.insert(PN->getParent());
01252 
01253   // If the values are PHIs in the same block, we can do a more precise
01254   // as well as efficient check: just check for aliases between the values
01255   // on corresponding edges.
01256   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
01257     if (PN2->getParent() == PN->getParent()) {
01258       LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
01259                    MemoryLocation(V2, V2Size, V2AAInfo));
01260       if (PN > V2)
01261         std::swap(Locs.first, Locs.second);
01262       // Analyse the PHIs' inputs under the assumption that the PHIs are
01263       // NoAlias.
01264       // If the PHIs are May/MustAlias there must be (recursively) an input
01265       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
01266       // there must be an operation on the PHIs within the PHIs' value cycle
01267       // that causes a MayAlias.
01268       // Pretend the phis do not alias.
01269       AliasResult Alias = NoAlias;
01270       assert(AliasCache.count(Locs) &&
01271              "There must exist an entry for the phi node");
01272       AliasResult OrigAliasResult = AliasCache[Locs];
01273       AliasCache[Locs] = NoAlias;
01274 
01275       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01276         AliasResult ThisAlias =
01277           aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
01278                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
01279                      V2Size, V2AAInfo);
01280         Alias = MergeAliasResults(ThisAlias, Alias);
01281         if (Alias == MayAlias)
01282           break;
01283       }
01284 
01285       // Reset if speculation failed.
01286       if (Alias != NoAlias)
01287         AliasCache[Locs] = OrigAliasResult;
01288 
01289       return Alias;
01290     }
01291 
01292   SmallPtrSet<Value*, 4> UniqueSrc;
01293   SmallVector<Value*, 4> V1Srcs;
01294   for (Value *PV1 : PN->incoming_values()) {
01295     if (isa<PHINode>(PV1))
01296       // If any of the source itself is a PHI, return MayAlias conservatively
01297       // to avoid compile time explosion. The worst possible case is if both
01298       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
01299       // and 'n' are the number of PHI sources.
01300       return MayAlias;
01301     if (UniqueSrc.insert(PV1).second)
01302       V1Srcs.push_back(PV1);
01303   }
01304 
01305   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
01306                                  V1Srcs[0], PNSize, PNAAInfo);
01307   // Early exit if the check of the first PHI source against V2 is MayAlias.
01308   // Other results are not possible.
01309   if (Alias == MayAlias)
01310     return MayAlias;
01311 
01312   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
01313   // NoAlias / MustAlias. Otherwise, returns MayAlias.
01314   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
01315     Value *V = V1Srcs[i];
01316 
01317     AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
01318                                        V, PNSize, PNAAInfo);
01319     Alias = MergeAliasResults(ThisAlias, Alias);
01320     if (Alias == MayAlias)
01321       break;
01322   }
01323 
01324   return Alias;
01325 }
01326 
01327 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
01328 // such as array references.
01329 //
01330 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
01331                                            AAMDNodes V1AAInfo, const Value *V2,
01332                                            uint64_t V2Size,
01333                                            AAMDNodes V2AAInfo) {
01334   // If either of the memory references is empty, it doesn't matter what the
01335   // pointer values are.
01336   if (V1Size == 0 || V2Size == 0)
01337     return NoAlias;
01338 
01339   // Strip off any casts if they exist.
01340   V1 = V1->stripPointerCasts();
01341   V2 = V2->stripPointerCasts();
01342 
01343   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
01344   // value for undef that aliases nothing in the program.
01345   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
01346     return NoAlias;
01347 
01348   // Are we checking for alias of the same value?
01349   // Because we look 'through' phi nodes we could look at "Value" pointers from
01350   // different iterations. We must therefore make sure that this is not the
01351   // case. The function isValueEqualInPotentialCycles ensures that this cannot
01352   // happen by looking at the visited phi nodes and making sure they cannot
01353   // reach the value.
01354   if (isValueEqualInPotentialCycles(V1, V2))
01355     return MustAlias;
01356 
01357   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
01358     return NoAlias;  // Scalars cannot alias each other
01359 
01360   // Figure out what objects these things are pointing to if we can.
01361   const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
01362   const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
01363 
01364   // Null values in the default address space don't point to any object, so they
01365   // don't alias any other pointer.
01366   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
01367     if (CPN->getType()->getAddressSpace() == 0)
01368       return NoAlias;
01369   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
01370     if (CPN->getType()->getAddressSpace() == 0)
01371       return NoAlias;
01372 
01373   if (O1 != O2) {
01374     // If V1/V2 point to two different objects we know that we have no alias.
01375     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
01376       return NoAlias;
01377 
01378     // Constant pointers can't alias with non-const isIdentifiedObject objects.
01379     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
01380         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
01381       return NoAlias;
01382 
01383     // Function arguments can't alias with things that are known to be
01384     // unambigously identified at the function level.
01385     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
01386         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
01387       return NoAlias;
01388 
01389     // Most objects can't alias null.
01390     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
01391         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
01392       return NoAlias;
01393 
01394     // If one pointer is the result of a call/invoke or load and the other is a
01395     // non-escaping local object within the same function, then we know the
01396     // object couldn't escape to a point where the call could return it.
01397     //
01398     // Note that if the pointers are in different functions, there are a
01399     // variety of complications. A call with a nocapture argument may still
01400     // temporary store the nocapture argument's value in a temporary memory
01401     // location if that memory location doesn't escape. Or it may pass a
01402     // nocapture value to other functions as long as they don't capture it.
01403     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
01404       return NoAlias;
01405     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
01406       return NoAlias;
01407   }
01408 
01409   // If the size of one access is larger than the entire object on the other
01410   // side, then we know such behavior is undefined and can assume no alias.
01411   if (DL)
01412     if ((V1Size != MemoryLocation::UnknownSize &&
01413          isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
01414         (V2Size != MemoryLocation::UnknownSize &&
01415          isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
01416       return NoAlias;
01417 
01418   // Check the cache before climbing up use-def chains. This also terminates
01419   // otherwise infinitely recursive queries.
01420   LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
01421                MemoryLocation(V2, V2Size, V2AAInfo));
01422   if (V1 > V2)
01423     std::swap(Locs.first, Locs.second);
01424   std::pair<AliasCacheTy::iterator, bool> Pair =
01425     AliasCache.insert(std::make_pair(Locs, MayAlias));
01426   if (!Pair.second)
01427     return Pair.first->second;
01428 
01429   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
01430   // GEP can't simplify, we don't even look at the PHI cases.
01431   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
01432     std::swap(V1, V2);
01433     std::swap(V1Size, V2Size);
01434     std::swap(O1, O2);
01435     std::swap(V1AAInfo, V2AAInfo);
01436   }
01437   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
01438     AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
01439     if (Result != MayAlias) return AliasCache[Locs] = Result;
01440   }
01441 
01442   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
01443     std::swap(V1, V2);
01444     std::swap(V1Size, V2Size);
01445     std::swap(V1AAInfo, V2AAInfo);
01446   }
01447   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
01448     AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
01449                                   V2, V2Size, V2AAInfo);
01450     if (Result != MayAlias) return AliasCache[Locs] = Result;
01451   }
01452 
01453   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
01454     std::swap(V1, V2);
01455     std::swap(V1Size, V2Size);
01456     std::swap(V1AAInfo, V2AAInfo);
01457   }
01458   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
01459     AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
01460                                      V2, V2Size, V2AAInfo);
01461     if (Result != MayAlias) return AliasCache[Locs] = Result;
01462   }
01463 
01464   // If both pointers are pointing into the same object and one of them
01465   // accesses is accessing the entire object, then the accesses must
01466   // overlap in some way.
01467   if (DL && O1 == O2)
01468     if ((V1Size != MemoryLocation::UnknownSize &&
01469          isObjectSize(O1, V1Size, *DL, *TLI)) ||
01470         (V2Size != MemoryLocation::UnknownSize &&
01471          isObjectSize(O2, V2Size, *DL, *TLI)))
01472       return AliasCache[Locs] = PartialAlias;
01473 
01474   AliasResult Result =
01475       AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
01476                            MemoryLocation(V2, V2Size, V2AAInfo));
01477   return AliasCache[Locs] = Result;
01478 }
01479 
01480 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
01481                                                        const Value *V2) {
01482   if (V != V2)
01483     return false;
01484 
01485   const Instruction *Inst = dyn_cast<Instruction>(V);
01486   if (!Inst)
01487     return true;
01488 
01489   if (VisitedPhiBBs.empty())
01490     return true;
01491 
01492   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
01493     return false;
01494 
01495   // Use dominance or loop info if available.
01496   DominatorTreeWrapperPass *DTWP =
01497       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
01498   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
01499   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
01500   LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
01501 
01502   // Make sure that the visited phis cannot reach the Value. This ensures that
01503   // the Values cannot come from different iterations of a potential cycle the
01504   // phi nodes could be involved in.
01505   for (auto *P : VisitedPhiBBs)
01506     if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
01507       return false;
01508 
01509   return true;
01510 }
01511 
01512 /// GetIndexDifference - Dest and Src are the variable indices from two
01513 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
01514 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
01515 /// difference between the two pointers.
01516 void BasicAliasAnalysis::GetIndexDifference(
01517     SmallVectorImpl<VariableGEPIndex> &Dest,
01518     const SmallVectorImpl<VariableGEPIndex> &Src) {
01519   if (Src.empty())
01520     return;
01521 
01522   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
01523     const Value *V = Src[i].V;
01524     ExtensionKind Extension = Src[i].Extension;
01525     int64_t Scale = Src[i].Scale;
01526 
01527     // Find V in Dest.  This is N^2, but pointer indices almost never have more
01528     // than a few variable indexes.
01529     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
01530       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
01531           Dest[j].Extension != Extension)
01532         continue;
01533 
01534       // If we found it, subtract off Scale V's from the entry in Dest.  If it
01535       // goes to zero, remove the entry.
01536       if (Dest[j].Scale != Scale)
01537         Dest[j].Scale -= Scale;
01538       else
01539         Dest.erase(Dest.begin() + j);
01540       Scale = 0;
01541       break;
01542     }
01543 
01544     // If we didn't consume this entry, add it to the end of the Dest list.
01545     if (Scale) {
01546       VariableGEPIndex Entry = { V, Extension, -Scale };
01547       Dest.push_back(Entry);
01548     }
01549   }
01550 }