LLVM API Documentation

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