Home | History | Annotate | Download | only in Analysis
      1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements an analysis that determines, for a given memory
     11 // operation, what preceding memory operations it depends on.  It builds on
     12 // alias analysis information, and tries to provide a lazy, caching interface to
     13 // a common kind of alias information query.
     14 //
     15 //===----------------------------------------------------------------------===//
     16 
     17 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
     18 #include "llvm/ADT/STLExtras.h"
     19 #include "llvm/ADT/Statistic.h"
     20 #include "llvm/Analysis/AliasAnalysis.h"
     21 #include "llvm/Analysis/InstructionSimplify.h"
     22 #include "llvm/Analysis/MemoryBuiltins.h"
     23 #include "llvm/Analysis/PHITransAddr.h"
     24 #include "llvm/Analysis/ValueTracking.h"
     25 #include "llvm/IR/DataLayout.h"
     26 #include "llvm/IR/Dominators.h"
     27 #include "llvm/IR/Function.h"
     28 #include "llvm/IR/Instructions.h"
     29 #include "llvm/IR/IntrinsicInst.h"
     30 #include "llvm/IR/LLVMContext.h"
     31 #include "llvm/IR/PredIteratorCache.h"
     32 #include "llvm/Support/Debug.h"
     33 using namespace llvm;
     34 
     35 #define DEBUG_TYPE "memdep"
     36 
     37 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
     38 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
     39 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
     40 
     41 STATISTIC(NumCacheNonLocalPtr,
     42           "Number of fully cached non-local ptr responses");
     43 STATISTIC(NumCacheDirtyNonLocalPtr,
     44           "Number of cached, but dirty, non-local ptr responses");
     45 STATISTIC(NumUncacheNonLocalPtr,
     46           "Number of uncached non-local ptr responses");
     47 STATISTIC(NumCacheCompleteNonLocalPtr,
     48           "Number of block queries that were completely cached");
     49 
     50 // Limit for the number of instructions to scan in a block.
     51 static const int BlockScanLimit = 100;
     52 
     53 char MemoryDependenceAnalysis::ID = 0;
     54 
     55 // Register this pass...
     56 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
     57                 "Memory Dependence Analysis", false, true)
     58 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
     59 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
     60                       "Memory Dependence Analysis", false, true)
     61 
     62 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
     63     : FunctionPass(ID), PredCache() {
     64   initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
     65 }
     66 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
     67 }
     68 
     69 /// Clean up memory in between runs
     70 void MemoryDependenceAnalysis::releaseMemory() {
     71   LocalDeps.clear();
     72   NonLocalDeps.clear();
     73   NonLocalPointerDeps.clear();
     74   ReverseLocalDeps.clear();
     75   ReverseNonLocalDeps.clear();
     76   ReverseNonLocalPtrDeps.clear();
     77   PredCache->clear();
     78 }
     79 
     80 
     81 
     82 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
     83 ///
     84 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
     85   AU.setPreservesAll();
     86   AU.addRequiredTransitive<AliasAnalysis>();
     87 }
     88 
     89 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
     90   AA = &getAnalysis<AliasAnalysis>();
     91   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
     92   DL = DLP ? &DLP->getDataLayout() : nullptr;
     93   DominatorTreeWrapperPass *DTWP =
     94       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
     95   DT = DTWP ? &DTWP->getDomTree() : nullptr;
     96   if (!PredCache)
     97     PredCache.reset(new PredIteratorCache());
     98   return false;
     99 }
    100 
    101 /// RemoveFromReverseMap - This is a helper function that removes Val from
    102 /// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
    103 template <typename KeyTy>
    104 static void RemoveFromReverseMap(DenseMap<Instruction*,
    105                                  SmallPtrSet<KeyTy, 4> > &ReverseMap,
    106                                  Instruction *Inst, KeyTy Val) {
    107   typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
    108   InstIt = ReverseMap.find(Inst);
    109   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
    110   bool Found = InstIt->second.erase(Val);
    111   assert(Found && "Invalid reverse map!"); (void)Found;
    112   if (InstIt->second.empty())
    113     ReverseMap.erase(InstIt);
    114 }
    115 
    116 /// GetLocation - If the given instruction references a specific memory
    117 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
    118 /// Return a ModRefInfo value describing the general behavior of the
    119 /// instruction.
    120 static
    121 AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
    122                                         AliasAnalysis::Location &Loc,
    123                                         AliasAnalysis *AA) {
    124   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
    125     if (LI->isUnordered()) {
    126       Loc = AA->getLocation(LI);
    127       return AliasAnalysis::Ref;
    128     }
    129     if (LI->getOrdering() == Monotonic) {
    130       Loc = AA->getLocation(LI);
    131       return AliasAnalysis::ModRef;
    132     }
    133     Loc = AliasAnalysis::Location();
    134     return AliasAnalysis::ModRef;
    135   }
    136 
    137   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
    138     if (SI->isUnordered()) {
    139       Loc = AA->getLocation(SI);
    140       return AliasAnalysis::Mod;
    141     }
    142     if (SI->getOrdering() == Monotonic) {
    143       Loc = AA->getLocation(SI);
    144       return AliasAnalysis::ModRef;
    145     }
    146     Loc = AliasAnalysis::Location();
    147     return AliasAnalysis::ModRef;
    148   }
    149 
    150   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
    151     Loc = AA->getLocation(V);
    152     return AliasAnalysis::ModRef;
    153   }
    154 
    155   if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
    156     // calls to free() deallocate the entire structure
    157     Loc = AliasAnalysis::Location(CI->getArgOperand(0));
    158     return AliasAnalysis::Mod;
    159   }
    160 
    161   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
    162     switch (II->getIntrinsicID()) {
    163     case Intrinsic::lifetime_start:
    164     case Intrinsic::lifetime_end:
    165     case Intrinsic::invariant_start:
    166       Loc = AliasAnalysis::Location(II->getArgOperand(1),
    167                                     cast<ConstantInt>(II->getArgOperand(0))
    168                                       ->getZExtValue(),
    169                                     II->getMetadata(LLVMContext::MD_tbaa));
    170       // These intrinsics don't really modify the memory, but returning Mod
    171       // will allow them to be handled conservatively.
    172       return AliasAnalysis::Mod;
    173     case Intrinsic::invariant_end:
    174       Loc = AliasAnalysis::Location(II->getArgOperand(2),
    175                                     cast<ConstantInt>(II->getArgOperand(1))
    176                                       ->getZExtValue(),
    177                                     II->getMetadata(LLVMContext::MD_tbaa));
    178       // These intrinsics don't really modify the memory, but returning Mod
    179       // will allow them to be handled conservatively.
    180       return AliasAnalysis::Mod;
    181     default:
    182       break;
    183     }
    184 
    185   // Otherwise, just do the coarse-grained thing that always works.
    186   if (Inst->mayWriteToMemory())
    187     return AliasAnalysis::ModRef;
    188   if (Inst->mayReadFromMemory())
    189     return AliasAnalysis::Ref;
    190   return AliasAnalysis::NoModRef;
    191 }
    192 
    193 /// getCallSiteDependencyFrom - Private helper for finding the local
    194 /// dependencies of a call site.
    195 MemDepResult MemoryDependenceAnalysis::
    196 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
    197                           BasicBlock::iterator ScanIt, BasicBlock *BB) {
    198   unsigned Limit = BlockScanLimit;
    199 
    200   // Walk backwards through the block, looking for dependencies
    201   while (ScanIt != BB->begin()) {
    202     // Limit the amount of scanning we do so we don't end up with quadratic
    203     // running time on extreme testcases.
    204     --Limit;
    205     if (!Limit)
    206       return MemDepResult::getUnknown();
    207 
    208     Instruction *Inst = --ScanIt;
    209 
    210     // If this inst is a memory op, get the pointer it accessed
    211     AliasAnalysis::Location Loc;
    212     AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
    213     if (Loc.Ptr) {
    214       // A simple instruction.
    215       if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
    216         return MemDepResult::getClobber(Inst);
    217       continue;
    218     }
    219 
    220     if (CallSite InstCS = cast<Value>(Inst)) {
    221       // Debug intrinsics don't cause dependences.
    222       if (isa<DbgInfoIntrinsic>(Inst)) continue;
    223       // If these two calls do not interfere, look past it.
    224       switch (AA->getModRefInfo(CS, InstCS)) {
    225       case AliasAnalysis::NoModRef:
    226         // If the two calls are the same, return InstCS as a Def, so that
    227         // CS can be found redundant and eliminated.
    228         if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
    229             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
    230           return MemDepResult::getDef(Inst);
    231 
    232         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
    233         // keep scanning.
    234         continue;
    235       default:
    236         return MemDepResult::getClobber(Inst);
    237       }
    238     }
    239 
    240     // If we could not obtain a pointer for the instruction and the instruction
    241     // touches memory then assume that this is a dependency.
    242     if (MR != AliasAnalysis::NoModRef)
    243       return MemDepResult::getClobber(Inst);
    244   }
    245 
    246   // No dependence found.  If this is the entry block of the function, it is
    247   // unknown, otherwise it is non-local.
    248   if (BB != &BB->getParent()->getEntryBlock())
    249     return MemDepResult::getNonLocal();
    250   return MemDepResult::getNonFuncLocal();
    251 }
    252 
    253 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
    254 /// would fully overlap MemLoc if done as a wider legal integer load.
    255 ///
    256 /// MemLocBase, MemLocOffset are lazily computed here the first time the
    257 /// base/offs of memloc is needed.
    258 static bool
    259 isLoadLoadClobberIfExtendedToFullWidth(const AliasAnalysis::Location &MemLoc,
    260                                        const Value *&MemLocBase,
    261                                        int64_t &MemLocOffs,
    262                                        const LoadInst *LI,
    263                                        const DataLayout *DL) {
    264   // If we have no target data, we can't do this.
    265   if (!DL) return false;
    266 
    267   // If we haven't already computed the base/offset of MemLoc, do so now.
    268   if (!MemLocBase)
    269     MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
    270 
    271   unsigned Size = MemoryDependenceAnalysis::
    272     getLoadLoadClobberFullWidthSize(MemLocBase, MemLocOffs, MemLoc.Size,
    273                                     LI, *DL);
    274   return Size != 0;
    275 }
    276 
    277 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
    278 /// looks at a memory location for a load (specified by MemLocBase, Offs,
    279 /// and Size) and compares it against a load.  If the specified load could
    280 /// be safely widened to a larger integer load that is 1) still efficient,
    281 /// 2) safe for the target, and 3) would provide the specified memory
    282 /// location value, then this function returns the size in bytes of the
    283 /// load width to use.  If not, this returns zero.
    284 unsigned MemoryDependenceAnalysis::
    285 getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs,
    286                                 unsigned MemLocSize, const LoadInst *LI,
    287                                 const DataLayout &DL) {
    288   // We can only extend simple integer loads.
    289   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
    290 
    291   // Load widening is hostile to ThreadSanitizer: it may cause false positives
    292   // or make the reports more cryptic (access sizes are wrong).
    293   if (LI->getParent()->getParent()->getAttributes().
    294       hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeThread))
    295     return 0;
    296 
    297   // Get the base of this load.
    298   int64_t LIOffs = 0;
    299   const Value *LIBase =
    300     GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, &DL);
    301 
    302   // If the two pointers are not based on the same pointer, we can't tell that
    303   // they are related.
    304   if (LIBase != MemLocBase) return 0;
    305 
    306   // Okay, the two values are based on the same pointer, but returned as
    307   // no-alias.  This happens when we have things like two byte loads at "P+1"
    308   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
    309   // alignment (or the largest native integer type) will allow us to load all
    310   // the bits required by MemLoc.
    311 
    312   // If MemLoc is before LI, then no widening of LI will help us out.
    313   if (MemLocOffs < LIOffs) return 0;
    314 
    315   // Get the alignment of the load in bytes.  We assume that it is safe to load
    316   // any legal integer up to this size without a problem.  For example, if we're
    317   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
    318   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
    319   // to i16.
    320   unsigned LoadAlign = LI->getAlignment();
    321 
    322   int64_t MemLocEnd = MemLocOffs+MemLocSize;
    323 
    324   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
    325   if (LIOffs+LoadAlign < MemLocEnd) return 0;
    326 
    327   // This is the size of the load to try.  Start with the next larger power of
    328   // two.
    329   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
    330   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
    331 
    332   while (1) {
    333     // If this load size is bigger than our known alignment or would not fit
    334     // into a native integer register, then we fail.
    335     if (NewLoadByteSize > LoadAlign ||
    336         !DL.fitsInLegalInteger(NewLoadByteSize*8))
    337       return 0;
    338 
    339     if (LIOffs+NewLoadByteSize > MemLocEnd &&
    340         LI->getParent()->getParent()->getAttributes().
    341           hasAttribute(AttributeSet::FunctionIndex, Attribute::SanitizeAddress))
    342       // We will be reading past the location accessed by the original program.
    343       // While this is safe in a regular build, Address Safety analysis tools
    344       // may start reporting false warnings. So, don't do widening.
    345       return 0;
    346 
    347     // If a load of this width would include all of MemLoc, then we succeed.
    348     if (LIOffs+NewLoadByteSize >= MemLocEnd)
    349       return NewLoadByteSize;
    350 
    351     NewLoadByteSize <<= 1;
    352   }
    353 }
    354 
    355 /// getPointerDependencyFrom - Return the instruction on which a memory
    356 /// location depends.  If isLoad is true, this routine ignores may-aliases with
    357 /// read-only operations.  If isLoad is false, this routine ignores may-aliases
    358 /// with reads from read-only locations.  If possible, pass the query
    359 /// instruction as well; this function may take advantage of the metadata
    360 /// annotated to the query instruction to refine the result.
    361 MemDepResult MemoryDependenceAnalysis::
    362 getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
    363                          BasicBlock::iterator ScanIt, BasicBlock *BB,
    364                          Instruction *QueryInst) {
    365 
    366   const Value *MemLocBase = nullptr;
    367   int64_t MemLocOffset = 0;
    368   unsigned Limit = BlockScanLimit;
    369   bool isInvariantLoad = false;
    370   if (isLoad && QueryInst) {
    371     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
    372     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
    373       isInvariantLoad = true;
    374   }
    375 
    376   // Walk backwards through the basic block, looking for dependencies.
    377   while (ScanIt != BB->begin()) {
    378     Instruction *Inst = --ScanIt;
    379 
    380     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
    381       // Debug intrinsics don't (and can't) cause dependencies.
    382       if (isa<DbgInfoIntrinsic>(II)) continue;
    383 
    384     // Limit the amount of scanning we do so we don't end up with quadratic
    385     // running time on extreme testcases.
    386     --Limit;
    387     if (!Limit)
    388       return MemDepResult::getUnknown();
    389 
    390     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
    391       // If we reach a lifetime begin or end marker, then the query ends here
    392       // because the value is undefined.
    393       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
    394         // FIXME: This only considers queries directly on the invariant-tagged
    395         // pointer, not on query pointers that are indexed off of them.  It'd
    396         // be nice to handle that at some point (the right approach is to use
    397         // GetPointerBaseWithConstantOffset).
    398         if (AA->isMustAlias(AliasAnalysis::Location(II->getArgOperand(1)),
    399                             MemLoc))
    400           return MemDepResult::getDef(II);
    401         continue;
    402       }
    403     }
    404 
    405     // Values depend on loads if the pointers are must aliased.  This means that
    406     // a load depends on another must aliased load from the same value.
    407     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
    408       // Atomic loads have complications involved.
    409       // FIXME: This is overly conservative.
    410       if (!LI->isUnordered())
    411         return MemDepResult::getClobber(LI);
    412 
    413       AliasAnalysis::Location LoadLoc = AA->getLocation(LI);
    414 
    415       // If we found a pointer, check if it could be the same as our pointer.
    416       AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
    417 
    418       if (isLoad) {
    419         if (R == AliasAnalysis::NoAlias) {
    420           // If this is an over-aligned integer load (for example,
    421           // "load i8* %P, align 4") see if it would obviously overlap with the
    422           // queried location if widened to a larger load (e.g. if the queried
    423           // location is 1 byte at P+1).  If so, return it as a load/load
    424           // clobber result, allowing the client to decide to widen the load if
    425           // it wants to.
    426           if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType()))
    427             if (LI->getAlignment()*8 > ITy->getPrimitiveSizeInBits() &&
    428                 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
    429                                                        MemLocOffset, LI, DL))
    430               return MemDepResult::getClobber(Inst);
    431 
    432           continue;
    433         }
    434 
    435         // Must aliased loads are defs of each other.
    436         if (R == AliasAnalysis::MustAlias)
    437           return MemDepResult::getDef(Inst);
    438 
    439 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
    440       // in terms of clobbering loads, but since it does this by looking
    441       // at the clobbering load directly, it doesn't know about any
    442       // phi translation that may have happened along the way.
    443 
    444         // If we have a partial alias, then return this as a clobber for the
    445         // client to handle.
    446         if (R == AliasAnalysis::PartialAlias)
    447           return MemDepResult::getClobber(Inst);
    448 #endif
    449 
    450         // Random may-alias loads don't depend on each other without a
    451         // dependence.
    452         continue;
    453       }
    454 
    455       // Stores don't depend on other no-aliased accesses.
    456       if (R == AliasAnalysis::NoAlias)
    457         continue;
    458 
    459       // Stores don't alias loads from read-only memory.
    460       if (AA->pointsToConstantMemory(LoadLoc))
    461         continue;
    462 
    463       // Stores depend on may/must aliased loads.
    464       return MemDepResult::getDef(Inst);
    465     }
    466 
    467     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
    468       // Atomic stores have complications involved.
    469       // FIXME: This is overly conservative.
    470       if (!SI->isUnordered())
    471         return MemDepResult::getClobber(SI);
    472 
    473       // If alias analysis can tell that this store is guaranteed to not modify
    474       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
    475       // the query pointer points to constant memory etc.
    476       if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
    477         continue;
    478 
    479       // Ok, this store might clobber the query pointer.  Check to see if it is
    480       // a must alias: in this case, we want to return this as a def.
    481       AliasAnalysis::Location StoreLoc = AA->getLocation(SI);
    482 
    483       // If we found a pointer, check if it could be the same as our pointer.
    484       AliasAnalysis::AliasResult R = AA->alias(StoreLoc, MemLoc);
    485 
    486       if (R == AliasAnalysis::NoAlias)
    487         continue;
    488       if (R == AliasAnalysis::MustAlias)
    489         return MemDepResult::getDef(Inst);
    490       if (isInvariantLoad)
    491        continue;
    492       return MemDepResult::getClobber(Inst);
    493     }
    494 
    495     // If this is an allocation, and if we know that the accessed pointer is to
    496     // the allocation, return Def.  This means that there is no dependence and
    497     // the access can be optimized based on that.  For example, a load could
    498     // turn into undef.
    499     // Note: Only determine this to be a malloc if Inst is the malloc call, not
    500     // a subsequent bitcast of the malloc call result.  There can be stores to
    501     // the malloced memory between the malloc call and its bitcast uses, and we
    502     // need to continue scanning until the malloc call.
    503     const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
    504     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
    505       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
    506 
    507       if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
    508         return MemDepResult::getDef(Inst);
    509       // Be conservative if the accessed pointer may alias the allocation.
    510       if (AA->alias(Inst, AccessPtr) != AliasAnalysis::NoAlias)
    511         return MemDepResult::getClobber(Inst);
    512       // If the allocation is not aliased and does not read memory (like
    513       // strdup), it is safe to ignore.
    514       if (isa<AllocaInst>(Inst) ||
    515           isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
    516         continue;
    517     }
    518 
    519     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
    520     AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
    521     // If necessary, perform additional analysis.
    522     if (MR == AliasAnalysis::ModRef)
    523       MR = AA->callCapturesBefore(Inst, MemLoc, DT);
    524     switch (MR) {
    525     case AliasAnalysis::NoModRef:
    526       // If the call has no effect on the queried pointer, just ignore it.
    527       continue;
    528     case AliasAnalysis::Mod:
    529       return MemDepResult::getClobber(Inst);
    530     case AliasAnalysis::Ref:
    531       // If the call is known to never store to the pointer, and if this is a
    532       // load query, we can safely ignore it (scan past it).
    533       if (isLoad)
    534         continue;
    535     default:
    536       // Otherwise, there is a potential dependence.  Return a clobber.
    537       return MemDepResult::getClobber(Inst);
    538     }
    539   }
    540 
    541   // No dependence found.  If this is the entry block of the function, it is
    542   // unknown, otherwise it is non-local.
    543   if (BB != &BB->getParent()->getEntryBlock())
    544     return MemDepResult::getNonLocal();
    545   return MemDepResult::getNonFuncLocal();
    546 }
    547 
    548 /// getDependency - Return the instruction on which a memory operation
    549 /// depends.
    550 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
    551   Instruction *ScanPos = QueryInst;
    552 
    553   // Check for a cached result
    554   MemDepResult &LocalCache = LocalDeps[QueryInst];
    555 
    556   // If the cached entry is non-dirty, just return it.  Note that this depends
    557   // on MemDepResult's default constructing to 'dirty'.
    558   if (!LocalCache.isDirty())
    559     return LocalCache;
    560 
    561   // Otherwise, if we have a dirty entry, we know we can start the scan at that
    562   // instruction, which may save us some work.
    563   if (Instruction *Inst = LocalCache.getInst()) {
    564     ScanPos = Inst;
    565 
    566     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
    567   }
    568 
    569   BasicBlock *QueryParent = QueryInst->getParent();
    570 
    571   // Do the scan.
    572   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
    573     // No dependence found.  If this is the entry block of the function, it is
    574     // unknown, otherwise it is non-local.
    575     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
    576       LocalCache = MemDepResult::getNonLocal();
    577     else
    578       LocalCache = MemDepResult::getNonFuncLocal();
    579   } else {
    580     AliasAnalysis::Location MemLoc;
    581     AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
    582     if (MemLoc.Ptr) {
    583       // If we can do a pointer scan, make it happen.
    584       bool isLoad = !(MR & AliasAnalysis::Mod);
    585       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
    586         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
    587 
    588       LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
    589                                             QueryParent, QueryInst);
    590     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
    591       CallSite QueryCS(QueryInst);
    592       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
    593       LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
    594                                              QueryParent);
    595     } else
    596       // Non-memory instruction.
    597       LocalCache = MemDepResult::getUnknown();
    598   }
    599 
    600   // Remember the result!
    601   if (Instruction *I = LocalCache.getInst())
    602     ReverseLocalDeps[I].insert(QueryInst);
    603 
    604   return LocalCache;
    605 }
    606 
    607 #ifndef NDEBUG
    608 /// AssertSorted - This method is used when -debug is specified to verify that
    609 /// cache arrays are properly kept sorted.
    610 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
    611                          int Count = -1) {
    612   if (Count == -1) Count = Cache.size();
    613   if (Count == 0) return;
    614 
    615   for (unsigned i = 1; i != unsigned(Count); ++i)
    616     assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
    617 }
    618 #endif
    619 
    620 /// getNonLocalCallDependency - Perform a full dependency query for the
    621 /// specified call, returning the set of blocks that the value is
    622 /// potentially live across.  The returned set of results will include a
    623 /// "NonLocal" result for all blocks where the value is live across.
    624 ///
    625 /// This method assumes the instruction returns a "NonLocal" dependency
    626 /// within its own block.
    627 ///
    628 /// This returns a reference to an internal data structure that may be
    629 /// invalidated on the next non-local query or when an instruction is
    630 /// removed.  Clients must copy this data if they want it around longer than
    631 /// that.
    632 const MemoryDependenceAnalysis::NonLocalDepInfo &
    633 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
    634   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
    635  "getNonLocalCallDependency should only be used on calls with non-local deps!");
    636   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
    637   NonLocalDepInfo &Cache = CacheP.first;
    638 
    639   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
    640   /// the cached case, this can happen due to instructions being deleted etc. In
    641   /// the uncached case, this starts out as the set of predecessors we care
    642   /// about.
    643   SmallVector<BasicBlock*, 32> DirtyBlocks;
    644 
    645   if (!Cache.empty()) {
    646     // Okay, we have a cache entry.  If we know it is not dirty, just return it
    647     // with no computation.
    648     if (!CacheP.second) {
    649       ++NumCacheNonLocal;
    650       return Cache;
    651     }
    652 
    653     // If we already have a partially computed set of results, scan them to
    654     // determine what is dirty, seeding our initial DirtyBlocks worklist.
    655     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
    656        I != E; ++I)
    657       if (I->getResult().isDirty())
    658         DirtyBlocks.push_back(I->getBB());
    659 
    660     // Sort the cache so that we can do fast binary search lookups below.
    661     std::sort(Cache.begin(), Cache.end());
    662 
    663     ++NumCacheDirtyNonLocal;
    664     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
    665     //     << Cache.size() << " cached: " << *QueryInst;
    666   } else {
    667     // Seed DirtyBlocks with each of the preds of QueryInst's block.
    668     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
    669     for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
    670       DirtyBlocks.push_back(*PI);
    671     ++NumUncacheNonLocal;
    672   }
    673 
    674   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
    675   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
    676 
    677   SmallPtrSet<BasicBlock*, 64> Visited;
    678 
    679   unsigned NumSortedEntries = Cache.size();
    680   DEBUG(AssertSorted(Cache));
    681 
    682   // Iterate while we still have blocks to update.
    683   while (!DirtyBlocks.empty()) {
    684     BasicBlock *DirtyBB = DirtyBlocks.back();
    685     DirtyBlocks.pop_back();
    686 
    687     // Already processed this block?
    688     if (!Visited.insert(DirtyBB))
    689       continue;
    690 
    691     // Do a binary search to see if we already have an entry for this block in
    692     // the cache set.  If so, find it.
    693     DEBUG(AssertSorted(Cache, NumSortedEntries));
    694     NonLocalDepInfo::iterator Entry =
    695       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
    696                        NonLocalDepEntry(DirtyBB));
    697     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
    698       --Entry;
    699 
    700     NonLocalDepEntry *ExistingResult = nullptr;
    701     if (Entry != Cache.begin()+NumSortedEntries &&
    702         Entry->getBB() == DirtyBB) {
    703       // If we already have an entry, and if it isn't already dirty, the block
    704       // is done.
    705       if (!Entry->getResult().isDirty())
    706         continue;
    707 
    708       // Otherwise, remember this slot so we can update the value.
    709       ExistingResult = &*Entry;
    710     }
    711 
    712     // If the dirty entry has a pointer, start scanning from it so we don't have
    713     // to rescan the entire block.
    714     BasicBlock::iterator ScanPos = DirtyBB->end();
    715     if (ExistingResult) {
    716       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
    717         ScanPos = Inst;
    718         // We're removing QueryInst's use of Inst.
    719         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
    720                              QueryCS.getInstruction());
    721       }
    722     }
    723 
    724     // Find out if this block has a local dependency for QueryInst.
    725     MemDepResult Dep;
    726 
    727     if (ScanPos != DirtyBB->begin()) {
    728       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
    729     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
    730       // No dependence found.  If this is the entry block of the function, it is
    731       // a clobber, otherwise it is unknown.
    732       Dep = MemDepResult::getNonLocal();
    733     } else {
    734       Dep = MemDepResult::getNonFuncLocal();
    735     }
    736 
    737     // If we had a dirty entry for the block, update it.  Otherwise, just add
    738     // a new entry.
    739     if (ExistingResult)
    740       ExistingResult->setResult(Dep);
    741     else
    742       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
    743 
    744     // If the block has a dependency (i.e. it isn't completely transparent to
    745     // the value), remember the association!
    746     if (!Dep.isNonLocal()) {
    747       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
    748       // update this when we remove instructions.
    749       if (Instruction *Inst = Dep.getInst())
    750         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
    751     } else {
    752 
    753       // If the block *is* completely transparent to the load, we need to check
    754       // the predecessors of this block.  Add them to our worklist.
    755       for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
    756         DirtyBlocks.push_back(*PI);
    757     }
    758   }
    759 
    760   return Cache;
    761 }
    762 
    763 /// getNonLocalPointerDependency - Perform a full dependency query for an
    764 /// access to the specified (non-volatile) memory location, returning the
    765 /// set of instructions that either define or clobber the value.
    766 ///
    767 /// This method assumes the pointer has a "NonLocal" dependency within its
    768 /// own block.
    769 ///
    770 void MemoryDependenceAnalysis::
    771 getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
    772                              BasicBlock *FromBB,
    773                              SmallVectorImpl<NonLocalDepResult> &Result) {
    774   assert(Loc.Ptr->getType()->isPointerTy() &&
    775          "Can't get pointer deps of a non-pointer!");
    776   Result.clear();
    777 
    778   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL);
    779 
    780   // This is the set of blocks we've inspected, and the pointer we consider in
    781   // each block.  Because of critical edges, we currently bail out if querying
    782   // a block with multiple different pointers.  This can happen during PHI
    783   // translation.
    784   DenseMap<BasicBlock*, Value*> Visited;
    785   if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
    786                                    Result, Visited, true))
    787     return;
    788   Result.clear();
    789   Result.push_back(NonLocalDepResult(FromBB,
    790                                      MemDepResult::getUnknown(),
    791                                      const_cast<Value *>(Loc.Ptr)));
    792 }
    793 
    794 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
    795 /// Pointer/PointeeSize using either cached information in Cache or by doing a
    796 /// lookup (which may use dirty cache info if available).  If we do a lookup,
    797 /// add the result to the cache.
    798 MemDepResult MemoryDependenceAnalysis::
    799 GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
    800                         bool isLoad, BasicBlock *BB,
    801                         NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
    802 
    803   // Do a binary search to see if we already have an entry for this block in
    804   // the cache set.  If so, find it.
    805   NonLocalDepInfo::iterator Entry =
    806     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
    807                      NonLocalDepEntry(BB));
    808   if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
    809     --Entry;
    810 
    811   NonLocalDepEntry *ExistingResult = nullptr;
    812   if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
    813     ExistingResult = &*Entry;
    814 
    815   // If we have a cached entry, and it is non-dirty, use it as the value for
    816   // this dependency.
    817   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
    818     ++NumCacheNonLocalPtr;
    819     return ExistingResult->getResult();
    820   }
    821 
    822   // Otherwise, we have to scan for the value.  If we have a dirty cache
    823   // entry, start scanning from its position, otherwise we scan from the end
    824   // of the block.
    825   BasicBlock::iterator ScanPos = BB->end();
    826   if (ExistingResult && ExistingResult->getResult().getInst()) {
    827     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
    828            "Instruction invalidated?");
    829     ++NumCacheDirtyNonLocalPtr;
    830     ScanPos = ExistingResult->getResult().getInst();
    831 
    832     // Eliminating the dirty entry from 'Cache', so update the reverse info.
    833     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
    834     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
    835   } else {
    836     ++NumUncacheNonLocalPtr;
    837   }
    838 
    839   // Scan the block for the dependency.
    840   MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
    841 
    842   // If we had a dirty entry for the block, update it.  Otherwise, just add
    843   // a new entry.
    844   if (ExistingResult)
    845     ExistingResult->setResult(Dep);
    846   else
    847     Cache->push_back(NonLocalDepEntry(BB, Dep));
    848 
    849   // If the block has a dependency (i.e. it isn't completely transparent to
    850   // the value), remember the reverse association because we just added it
    851   // to Cache!
    852   if (!Dep.isDef() && !Dep.isClobber())
    853     return Dep;
    854 
    855   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
    856   // update MemDep when we remove instructions.
    857   Instruction *Inst = Dep.getInst();
    858   assert(Inst && "Didn't depend on anything?");
    859   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
    860   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
    861   return Dep;
    862 }
    863 
    864 /// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
    865 /// number of elements in the array that are already properly ordered.  This is
    866 /// optimized for the case when only a few entries are added.
    867 static void
    868 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
    869                          unsigned NumSortedEntries) {
    870   switch (Cache.size() - NumSortedEntries) {
    871   case 0:
    872     // done, no new entries.
    873     break;
    874   case 2: {
    875     // Two new entries, insert the last one into place.
    876     NonLocalDepEntry Val = Cache.back();
    877     Cache.pop_back();
    878     MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
    879       std::upper_bound(Cache.begin(), Cache.end()-1, Val);
    880     Cache.insert(Entry, Val);
    881     // FALL THROUGH.
    882   }
    883   case 1:
    884     // One new entry, Just insert the new value at the appropriate position.
    885     if (Cache.size() != 1) {
    886       NonLocalDepEntry Val = Cache.back();
    887       Cache.pop_back();
    888       MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
    889         std::upper_bound(Cache.begin(), Cache.end(), Val);
    890       Cache.insert(Entry, Val);
    891     }
    892     break;
    893   default:
    894     // Added many values, do a full scale sort.
    895     std::sort(Cache.begin(), Cache.end());
    896     break;
    897   }
    898 }
    899 
    900 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
    901 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
    902 /// results to the results vector and keep track of which blocks are visited in
    903 /// 'Visited'.
    904 ///
    905 /// This has special behavior for the first block queries (when SkipFirstBlock
    906 /// is true).  In this special case, it ignores the contents of the specified
    907 /// block and starts returning dependence info for its predecessors.
    908 ///
    909 /// This function returns false on success, or true to indicate that it could
    910 /// not compute dependence information for some reason.  This should be treated
    911 /// as a clobber dependence on the first instruction in the predecessor block.
    912 bool MemoryDependenceAnalysis::
    913 getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
    914                             const AliasAnalysis::Location &Loc,
    915                             bool isLoad, BasicBlock *StartBB,
    916                             SmallVectorImpl<NonLocalDepResult> &Result,
    917                             DenseMap<BasicBlock*, Value*> &Visited,
    918                             bool SkipFirstBlock) {
    919   // Look up the cached info for Pointer.
    920   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
    921 
    922   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
    923   // CacheKey, this value will be inserted as the associated value. Otherwise,
    924   // it'll be ignored, and we'll have to check to see if the cached size and
    925   // tbaa tag are consistent with the current query.
    926   NonLocalPointerInfo InitialNLPI;
    927   InitialNLPI.Size = Loc.Size;
    928   InitialNLPI.TBAATag = Loc.TBAATag;
    929 
    930   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
    931   // already have one.
    932   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
    933     NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
    934   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
    935 
    936   // If we already have a cache entry for this CacheKey, we may need to do some
    937   // work to reconcile the cache entry and the current query.
    938   if (!Pair.second) {
    939     if (CacheInfo->Size < Loc.Size) {
    940       // The query's Size is greater than the cached one. Throw out the
    941       // cached data and proceed with the query at the greater size.
    942       CacheInfo->Pair = BBSkipFirstBlockPair();
    943       CacheInfo->Size = Loc.Size;
    944       for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
    945            DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
    946         if (Instruction *Inst = DI->getResult().getInst())
    947           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
    948       CacheInfo->NonLocalDeps.clear();
    949     } else if (CacheInfo->Size > Loc.Size) {
    950       // This query's Size is less than the cached one. Conservatively restart
    951       // the query using the greater size.
    952       return getNonLocalPointerDepFromBB(Pointer,
    953                                          Loc.getWithNewSize(CacheInfo->Size),
    954                                          isLoad, StartBB, Result, Visited,
    955                                          SkipFirstBlock);
    956     }
    957 
    958     // If the query's TBAATag is inconsistent with the cached one,
    959     // conservatively throw out the cached data and restart the query with
    960     // no tag if needed.
    961     if (CacheInfo->TBAATag != Loc.TBAATag) {
    962       if (CacheInfo->TBAATag) {
    963         CacheInfo->Pair = BBSkipFirstBlockPair();
    964         CacheInfo->TBAATag = nullptr;
    965         for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
    966              DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
    967           if (Instruction *Inst = DI->getResult().getInst())
    968             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
    969         CacheInfo->NonLocalDeps.clear();
    970       }
    971       if (Loc.TBAATag)
    972         return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
    973                                            isLoad, StartBB, Result, Visited,
    974                                            SkipFirstBlock);
    975     }
    976   }
    977 
    978   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
    979 
    980   // If we have valid cached information for exactly the block we are
    981   // investigating, just return it with no recomputation.
    982   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
    983     // We have a fully cached result for this query then we can just return the
    984     // cached results and populate the visited set.  However, we have to verify
    985     // that we don't already have conflicting results for these blocks.  Check
    986     // to ensure that if a block in the results set is in the visited set that
    987     // it was for the same pointer query.
    988     if (!Visited.empty()) {
    989       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
    990            I != E; ++I) {
    991         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
    992         if (VI == Visited.end() || VI->second == Pointer.getAddr())
    993           continue;
    994 
    995         // We have a pointer mismatch in a block.  Just return clobber, saying
    996         // that something was clobbered in this result.  We could also do a
    997         // non-fully cached query, but there is little point in doing this.
    998         return true;
    999       }
   1000     }
   1001 
   1002     Value *Addr = Pointer.getAddr();
   1003     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
   1004          I != E; ++I) {
   1005       Visited.insert(std::make_pair(I->getBB(), Addr));
   1006       if (I->getResult().isNonLocal()) {
   1007         continue;
   1008       }
   1009 
   1010       if (!DT) {
   1011         Result.push_back(NonLocalDepResult(I->getBB(),
   1012                                            MemDepResult::getUnknown(),
   1013                                            Addr));
   1014       } else if (DT->isReachableFromEntry(I->getBB())) {
   1015         Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
   1016       }
   1017     }
   1018     ++NumCacheCompleteNonLocalPtr;
   1019     return false;
   1020   }
   1021 
   1022   // Otherwise, either this is a new block, a block with an invalid cache
   1023   // pointer or one that we're about to invalidate by putting more info into it
   1024   // than its valid cache info.  If empty, the result will be valid cache info,
   1025   // otherwise it isn't.
   1026   if (Cache->empty())
   1027     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
   1028   else
   1029     CacheInfo->Pair = BBSkipFirstBlockPair();
   1030 
   1031   SmallVector<BasicBlock*, 32> Worklist;
   1032   Worklist.push_back(StartBB);
   1033 
   1034   // PredList used inside loop.
   1035   SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
   1036 
   1037   // Keep track of the entries that we know are sorted.  Previously cached
   1038   // entries will all be sorted.  The entries we add we only sort on demand (we
   1039   // don't insert every element into its sorted position).  We know that we
   1040   // won't get any reuse from currently inserted values, because we don't
   1041   // revisit blocks after we insert info for them.
   1042   unsigned NumSortedEntries = Cache->size();
   1043   DEBUG(AssertSorted(*Cache));
   1044 
   1045   while (!Worklist.empty()) {
   1046     BasicBlock *BB = Worklist.pop_back_val();
   1047 
   1048     // Skip the first block if we have it.
   1049     if (!SkipFirstBlock) {
   1050       // Analyze the dependency of *Pointer in FromBB.  See if we already have
   1051       // been here.
   1052       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
   1053 
   1054       // Get the dependency info for Pointer in BB.  If we have cached
   1055       // information, we will use it, otherwise we compute it.
   1056       DEBUG(AssertSorted(*Cache, NumSortedEntries));
   1057       MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
   1058                                                  NumSortedEntries);
   1059 
   1060       // If we got a Def or Clobber, add this to the list of results.
   1061       if (!Dep.isNonLocal()) {
   1062         if (!DT) {
   1063           Result.push_back(NonLocalDepResult(BB,
   1064                                              MemDepResult::getUnknown(),
   1065                                              Pointer.getAddr()));
   1066           continue;
   1067         } else if (DT->isReachableFromEntry(BB)) {
   1068           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
   1069           continue;
   1070         }
   1071       }
   1072     }
   1073 
   1074     // If 'Pointer' is an instruction defined in this block, then we need to do
   1075     // phi translation to change it into a value live in the predecessor block.
   1076     // If not, we just add the predecessors to the worklist and scan them with
   1077     // the same Pointer.
   1078     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
   1079       SkipFirstBlock = false;
   1080       SmallVector<BasicBlock*, 16> NewBlocks;
   1081       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
   1082         // Verify that we haven't looked at this block yet.
   1083         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
   1084           InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
   1085         if (InsertRes.second) {
   1086           // First time we've looked at *PI.
   1087           NewBlocks.push_back(*PI);
   1088           continue;
   1089         }
   1090 
   1091         // If we have seen this block before, but it was with a different
   1092         // pointer then we have a phi translation failure and we have to treat
   1093         // this as a clobber.
   1094         if (InsertRes.first->second != Pointer.getAddr()) {
   1095           // Make sure to clean up the Visited map before continuing on to
   1096           // PredTranslationFailure.
   1097           for (unsigned i = 0; i < NewBlocks.size(); i++)
   1098             Visited.erase(NewBlocks[i]);
   1099           goto PredTranslationFailure;
   1100         }
   1101       }
   1102       Worklist.append(NewBlocks.begin(), NewBlocks.end());
   1103       continue;
   1104     }
   1105 
   1106     // We do need to do phi translation, if we know ahead of time we can't phi
   1107     // translate this value, don't even try.
   1108     if (!Pointer.IsPotentiallyPHITranslatable())
   1109       goto PredTranslationFailure;
   1110 
   1111     // We may have added values to the cache list before this PHI translation.
   1112     // If so, we haven't done anything to ensure that the cache remains sorted.
   1113     // Sort it now (if needed) so that recursive invocations of
   1114     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
   1115     // value will only see properly sorted cache arrays.
   1116     if (Cache && NumSortedEntries != Cache->size()) {
   1117       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
   1118       NumSortedEntries = Cache->size();
   1119     }
   1120     Cache = nullptr;
   1121 
   1122     PredList.clear();
   1123     for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
   1124       BasicBlock *Pred = *PI;
   1125       PredList.push_back(std::make_pair(Pred, Pointer));
   1126 
   1127       // Get the PHI translated pointer in this predecessor.  This can fail if
   1128       // not translatable, in which case the getAddr() returns null.
   1129       PHITransAddr &PredPointer = PredList.back().second;
   1130       PredPointer.PHITranslateValue(BB, Pred, nullptr);
   1131 
   1132       Value *PredPtrVal = PredPointer.getAddr();
   1133 
   1134       // Check to see if we have already visited this pred block with another
   1135       // pointer.  If so, we can't do this lookup.  This failure can occur
   1136       // with PHI translation when a critical edge exists and the PHI node in
   1137       // the successor translates to a pointer value different than the
   1138       // pointer the block was first analyzed with.
   1139       std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
   1140         InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
   1141 
   1142       if (!InsertRes.second) {
   1143         // We found the pred; take it off the list of preds to visit.
   1144         PredList.pop_back();
   1145 
   1146         // If the predecessor was visited with PredPtr, then we already did
   1147         // the analysis and can ignore it.
   1148         if (InsertRes.first->second == PredPtrVal)
   1149           continue;
   1150 
   1151         // Otherwise, the block was previously analyzed with a different
   1152         // pointer.  We can't represent the result of this case, so we just
   1153         // treat this as a phi translation failure.
   1154 
   1155         // Make sure to clean up the Visited map before continuing on to
   1156         // PredTranslationFailure.
   1157         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
   1158           Visited.erase(PredList[i].first);
   1159 
   1160         goto PredTranslationFailure;
   1161       }
   1162     }
   1163 
   1164     // Actually process results here; this need to be a separate loop to avoid
   1165     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
   1166     // any results for.  (getNonLocalPointerDepFromBB will modify our
   1167     // datastructures in ways the code after the PredTranslationFailure label
   1168     // doesn't expect.)
   1169     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
   1170       BasicBlock *Pred = PredList[i].first;
   1171       PHITransAddr &PredPointer = PredList[i].second;
   1172       Value *PredPtrVal = PredPointer.getAddr();
   1173 
   1174       bool CanTranslate = true;
   1175       // If PHI translation was unable to find an available pointer in this
   1176       // predecessor, then we have to assume that the pointer is clobbered in
   1177       // that predecessor.  We can still do PRE of the load, which would insert
   1178       // a computation of the pointer in this predecessor.
   1179       if (!PredPtrVal)
   1180         CanTranslate = false;
   1181 
   1182       // FIXME: it is entirely possible that PHI translating will end up with
   1183       // the same value.  Consider PHI translating something like:
   1184       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
   1185       // to recurse here, pedantically speaking.
   1186 
   1187       // If getNonLocalPointerDepFromBB fails here, that means the cached
   1188       // result conflicted with the Visited list; we have to conservatively
   1189       // assume it is unknown, but this also does not block PRE of the load.
   1190       if (!CanTranslate ||
   1191           getNonLocalPointerDepFromBB(PredPointer,
   1192                                       Loc.getWithNewPtr(PredPtrVal),
   1193                                       isLoad, Pred,
   1194                                       Result, Visited)) {
   1195         // Add the entry to the Result list.
   1196         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
   1197         Result.push_back(Entry);
   1198 
   1199         // Since we had a phi translation failure, the cache for CacheKey won't
   1200         // include all of the entries that we need to immediately satisfy future
   1201         // queries.  Mark this in NonLocalPointerDeps by setting the
   1202         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
   1203         // cached value to do more work but not miss the phi trans failure.
   1204         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
   1205         NLPI.Pair = BBSkipFirstBlockPair();
   1206         continue;
   1207       }
   1208     }
   1209 
   1210     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
   1211     CacheInfo = &NonLocalPointerDeps[CacheKey];
   1212     Cache = &CacheInfo->NonLocalDeps;
   1213     NumSortedEntries = Cache->size();
   1214 
   1215     // Since we did phi translation, the "Cache" set won't contain all of the
   1216     // results for the query.  This is ok (we can still use it to accelerate
   1217     // specific block queries) but we can't do the fastpath "return all
   1218     // results from the set"  Clear out the indicator for this.
   1219     CacheInfo->Pair = BBSkipFirstBlockPair();
   1220     SkipFirstBlock = false;
   1221     continue;
   1222 
   1223   PredTranslationFailure:
   1224     // The following code is "failure"; we can't produce a sane translation
   1225     // for the given block.  It assumes that we haven't modified any of
   1226     // our datastructures while processing the current block.
   1227 
   1228     if (!Cache) {
   1229       // Refresh the CacheInfo/Cache pointer if it got invalidated.
   1230       CacheInfo = &NonLocalPointerDeps[CacheKey];
   1231       Cache = &CacheInfo->NonLocalDeps;
   1232       NumSortedEntries = Cache->size();
   1233     }
   1234 
   1235     // Since we failed phi translation, the "Cache" set won't contain all of the
   1236     // results for the query.  This is ok (we can still use it to accelerate
   1237     // specific block queries) but we can't do the fastpath "return all
   1238     // results from the set".  Clear out the indicator for this.
   1239     CacheInfo->Pair = BBSkipFirstBlockPair();
   1240 
   1241     // If *nothing* works, mark the pointer as unknown.
   1242     //
   1243     // If this is the magic first block, return this as a clobber of the whole
   1244     // incoming value.  Since we can't phi translate to one of the predecessors,
   1245     // we have to bail out.
   1246     if (SkipFirstBlock)
   1247       return true;
   1248 
   1249     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
   1250       assert(I != Cache->rend() && "Didn't find current block??");
   1251       if (I->getBB() != BB)
   1252         continue;
   1253 
   1254       assert(I->getResult().isNonLocal() &&
   1255              "Should only be here with transparent block");
   1256       I->setResult(MemDepResult::getUnknown());
   1257       Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
   1258                                          Pointer.getAddr()));
   1259       break;
   1260     }
   1261   }
   1262 
   1263   // Okay, we're done now.  If we added new values to the cache, re-sort it.
   1264   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
   1265   DEBUG(AssertSorted(*Cache));
   1266   return false;
   1267 }
   1268 
   1269 /// RemoveCachedNonLocalPointerDependencies - If P exists in
   1270 /// CachedNonLocalPointerInfo, remove it.
   1271 void MemoryDependenceAnalysis::
   1272 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
   1273   CachedNonLocalPointerInfo::iterator It =
   1274     NonLocalPointerDeps.find(P);
   1275   if (It == NonLocalPointerDeps.end()) return;
   1276 
   1277   // Remove all of the entries in the BB->val map.  This involves removing
   1278   // instructions from the reverse map.
   1279   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
   1280 
   1281   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
   1282     Instruction *Target = PInfo[i].getResult().getInst();
   1283     if (!Target) continue;  // Ignore non-local dep results.
   1284     assert(Target->getParent() == PInfo[i].getBB());
   1285 
   1286     // Eliminating the dirty entry from 'Cache', so update the reverse info.
   1287     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
   1288   }
   1289 
   1290   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
   1291   NonLocalPointerDeps.erase(It);
   1292 }
   1293 
   1294 
   1295 /// invalidateCachedPointerInfo - This method is used to invalidate cached
   1296 /// information about the specified pointer, because it may be too
   1297 /// conservative in memdep.  This is an optional call that can be used when
   1298 /// the client detects an equivalence between the pointer and some other
   1299 /// value and replaces the other value with ptr. This can make Ptr available
   1300 /// in more places that cached info does not necessarily keep.
   1301 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
   1302   // If Ptr isn't really a pointer, just ignore it.
   1303   if (!Ptr->getType()->isPointerTy()) return;
   1304   // Flush store info for the pointer.
   1305   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
   1306   // Flush load info for the pointer.
   1307   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
   1308 }
   1309 
   1310 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
   1311 /// This needs to be done when the CFG changes, e.g., due to splitting
   1312 /// critical edges.
   1313 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
   1314   PredCache->clear();
   1315 }
   1316 
   1317 /// removeInstruction - Remove an instruction from the dependence analysis,
   1318 /// updating the dependence of instructions that previously depended on it.
   1319 /// This method attempts to keep the cache coherent using the reverse map.
   1320 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
   1321   // Walk through the Non-local dependencies, removing this one as the value
   1322   // for any cached queries.
   1323   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
   1324   if (NLDI != NonLocalDeps.end()) {
   1325     NonLocalDepInfo &BlockMap = NLDI->second.first;
   1326     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
   1327          DI != DE; ++DI)
   1328       if (Instruction *Inst = DI->getResult().getInst())
   1329         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
   1330     NonLocalDeps.erase(NLDI);
   1331   }
   1332 
   1333   // If we have a cached local dependence query for this instruction, remove it.
   1334   //
   1335   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
   1336   if (LocalDepEntry != LocalDeps.end()) {
   1337     // Remove us from DepInst's reverse set now that the local dep info is gone.
   1338     if (Instruction *Inst = LocalDepEntry->second.getInst())
   1339       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
   1340 
   1341     // Remove this local dependency info.
   1342     LocalDeps.erase(LocalDepEntry);
   1343   }
   1344 
   1345   // If we have any cached pointer dependencies on this instruction, remove
   1346   // them.  If the instruction has non-pointer type, then it can't be a pointer
   1347   // base.
   1348 
   1349   // Remove it from both the load info and the store info.  The instruction
   1350   // can't be in either of these maps if it is non-pointer.
   1351   if (RemInst->getType()->isPointerTy()) {
   1352     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
   1353     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
   1354   }
   1355 
   1356   // Loop over all of the things that depend on the instruction we're removing.
   1357   //
   1358   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
   1359 
   1360   // If we find RemInst as a clobber or Def in any of the maps for other values,
   1361   // we need to replace its entry with a dirty version of the instruction after
   1362   // it.  If RemInst is a terminator, we use a null dirty value.
   1363   //
   1364   // Using a dirty version of the instruction after RemInst saves having to scan
   1365   // the entire block to get to this point.
   1366   MemDepResult NewDirtyVal;
   1367   if (!RemInst->isTerminator())
   1368     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
   1369 
   1370   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
   1371   if (ReverseDepIt != ReverseLocalDeps.end()) {
   1372     SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
   1373     // RemInst can't be the terminator if it has local stuff depending on it.
   1374     assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
   1375            "Nothing can locally depend on a terminator");
   1376 
   1377     for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
   1378          E = ReverseDeps.end(); I != E; ++I) {
   1379       Instruction *InstDependingOnRemInst = *I;
   1380       assert(InstDependingOnRemInst != RemInst &&
   1381              "Already removed our local dep info");
   1382 
   1383       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
   1384 
   1385       // Make sure to remember that new things depend on NewDepInst.
   1386       assert(NewDirtyVal.getInst() && "There is no way something else can have "
   1387              "a local dep on this if it is a terminator!");
   1388       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
   1389                                                 InstDependingOnRemInst));
   1390     }
   1391 
   1392     ReverseLocalDeps.erase(ReverseDepIt);
   1393 
   1394     // Add new reverse deps after scanning the set, to avoid invalidating the
   1395     // 'ReverseDeps' reference.
   1396     while (!ReverseDepsToAdd.empty()) {
   1397       ReverseLocalDeps[ReverseDepsToAdd.back().first]
   1398         .insert(ReverseDepsToAdd.back().second);
   1399       ReverseDepsToAdd.pop_back();
   1400     }
   1401   }
   1402 
   1403   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
   1404   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
   1405     SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
   1406     for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
   1407          I != E; ++I) {
   1408       assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
   1409 
   1410       PerInstNLInfo &INLD = NonLocalDeps[*I];
   1411       // The information is now dirty!
   1412       INLD.second = true;
   1413 
   1414       for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
   1415            DE = INLD.first.end(); DI != DE; ++DI) {
   1416         if (DI->getResult().getInst() != RemInst) continue;
   1417 
   1418         // Convert to a dirty entry for the subsequent instruction.
   1419         DI->setResult(NewDirtyVal);
   1420 
   1421         if (Instruction *NextI = NewDirtyVal.getInst())
   1422           ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
   1423       }
   1424     }
   1425 
   1426     ReverseNonLocalDeps.erase(ReverseDepIt);
   1427 
   1428     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
   1429     while (!ReverseDepsToAdd.empty()) {
   1430       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
   1431         .insert(ReverseDepsToAdd.back().second);
   1432       ReverseDepsToAdd.pop_back();
   1433     }
   1434   }
   1435 
   1436   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
   1437   // value in the NonLocalPointerDeps info.
   1438   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
   1439     ReverseNonLocalPtrDeps.find(RemInst);
   1440   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
   1441     SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
   1442     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
   1443 
   1444     for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
   1445          E = Set.end(); I != E; ++I) {
   1446       ValueIsLoadPair P = *I;
   1447       assert(P.getPointer() != RemInst &&
   1448              "Already removed NonLocalPointerDeps info for RemInst");
   1449 
   1450       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
   1451 
   1452       // The cache is not valid for any specific block anymore.
   1453       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
   1454 
   1455       // Update any entries for RemInst to use the instruction after it.
   1456       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
   1457            DI != DE; ++DI) {
   1458         if (DI->getResult().getInst() != RemInst) continue;
   1459 
   1460         // Convert to a dirty entry for the subsequent instruction.
   1461         DI->setResult(NewDirtyVal);
   1462 
   1463         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
   1464           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
   1465       }
   1466 
   1467       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
   1468       // subsequent value may invalidate the sortedness.
   1469       std::sort(NLPDI.begin(), NLPDI.end());
   1470     }
   1471 
   1472     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
   1473 
   1474     while (!ReversePtrDepsToAdd.empty()) {
   1475       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
   1476         .insert(ReversePtrDepsToAdd.back().second);
   1477       ReversePtrDepsToAdd.pop_back();
   1478     }
   1479   }
   1480 
   1481 
   1482   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
   1483   AA->deleteValue(RemInst);
   1484   DEBUG(verifyRemoved(RemInst));
   1485 }
   1486 /// verifyRemoved - Verify that the specified instruction does not occur
   1487 /// in our internal data structures.
   1488 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
   1489   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
   1490        E = LocalDeps.end(); I != E; ++I) {
   1491     assert(I->first != D && "Inst occurs in data structures");
   1492     assert(I->second.getInst() != D &&
   1493            "Inst occurs in data structures");
   1494   }
   1495 
   1496   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
   1497        E = NonLocalPointerDeps.end(); I != E; ++I) {
   1498     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
   1499     const NonLocalDepInfo &Val = I->second.NonLocalDeps;
   1500     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
   1501          II != E; ++II)
   1502       assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
   1503   }
   1504 
   1505   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
   1506        E = NonLocalDeps.end(); I != E; ++I) {
   1507     assert(I->first != D && "Inst occurs in data structures");
   1508     const PerInstNLInfo &INLD = I->second;
   1509     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
   1510          EE = INLD.first.end(); II  != EE; ++II)
   1511       assert(II->getResult().getInst() != D && "Inst occurs in data structures");
   1512   }
   1513 
   1514   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
   1515        E = ReverseLocalDeps.end(); I != E; ++I) {
   1516     assert(I->first != D && "Inst occurs in data structures");
   1517     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
   1518          EE = I->second.end(); II != EE; ++II)
   1519       assert(*II != D && "Inst occurs in data structures");
   1520   }
   1521 
   1522   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
   1523        E = ReverseNonLocalDeps.end();
   1524        I != E; ++I) {
   1525     assert(I->first != D && "Inst occurs in data structures");
   1526     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
   1527          EE = I->second.end(); II != EE; ++II)
   1528       assert(*II != D && "Inst occurs in data structures");
   1529   }
   1530 
   1531   for (ReverseNonLocalPtrDepTy::const_iterator
   1532        I = ReverseNonLocalPtrDeps.begin(),
   1533        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
   1534     assert(I->first != D && "Inst occurs in rev NLPD map");
   1535 
   1536     for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
   1537          E = I->second.end(); II != E; ++II)
   1538       assert(*II != ValueIsLoadPair(D, false) &&
   1539              *II != ValueIsLoadPair(D, true) &&
   1540              "Inst occurs in ReverseNonLocalPtrDeps map");
   1541   }
   1542 
   1543 }
   1544