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