LLVM API Documentation

LazyValueInfo.cpp
Go to the documentation of this file.
00001 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
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 interface for lazy computation of value constraint
00011 // information.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/LazyValueInfo.h"
00016 #include "llvm/ADT/DenseSet.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/Analysis/ConstantFolding.h"
00019 #include "llvm/Analysis/ValueTracking.h"
00020 #include "llvm/IR/CFG.h"
00021 #include "llvm/IR/ConstantRange.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/PatternMatch.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetLibraryInfo.h"
00031 #include <map>
00032 #include <stack>
00033 using namespace llvm;
00034 using namespace PatternMatch;
00035 
00036 #define DEBUG_TYPE "lazy-value-info"
00037 
00038 char LazyValueInfo::ID = 0;
00039 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
00040                 "Lazy Value Information Analysis", false, true)
00041 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00042 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
00043                 "Lazy Value Information Analysis", false, true)
00044 
00045 namespace llvm {
00046   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
00047 }
00048 
00049 
00050 //===----------------------------------------------------------------------===//
00051 //                               LVILatticeVal
00052 //===----------------------------------------------------------------------===//
00053 
00054 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
00055 /// value.
00056 ///
00057 /// FIXME: This is basically just for bringup, this can be made a lot more rich
00058 /// in the future.
00059 ///
00060 namespace {
00061 class LVILatticeVal {
00062   enum LatticeValueTy {
00063     /// undefined - This Value has no known value yet.
00064     undefined,
00065     
00066     /// constant - This Value has a specific constant value.
00067     constant,
00068     /// notconstant - This Value is known to not have the specified value.
00069     notconstant,
00070 
00071     /// constantrange - The Value falls within this range.
00072     constantrange,
00073 
00074     /// overdefined - This value is not known to be constant, and we know that
00075     /// it has a value.
00076     overdefined
00077   };
00078   
00079   /// Val: This stores the current lattice value along with the Constant* for
00080   /// the constant if this is a 'constant' or 'notconstant' value.
00081   LatticeValueTy Tag;
00082   Constant *Val;
00083   ConstantRange Range;
00084   
00085 public:
00086   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
00087 
00088   static LVILatticeVal get(Constant *C) {
00089     LVILatticeVal Res;
00090     if (!isa<UndefValue>(C))
00091       Res.markConstant(C);
00092     return Res;
00093   }
00094   static LVILatticeVal getNot(Constant *C) {
00095     LVILatticeVal Res;
00096     if (!isa<UndefValue>(C))
00097       Res.markNotConstant(C);
00098     return Res;
00099   }
00100   static LVILatticeVal getRange(ConstantRange CR) {
00101     LVILatticeVal Res;
00102     Res.markConstantRange(CR);
00103     return Res;
00104   }
00105   
00106   bool isUndefined() const     { return Tag == undefined; }
00107   bool isConstant() const      { return Tag == constant; }
00108   bool isNotConstant() const   { return Tag == notconstant; }
00109   bool isConstantRange() const { return Tag == constantrange; }
00110   bool isOverdefined() const   { return Tag == overdefined; }
00111   
00112   Constant *getConstant() const {
00113     assert(isConstant() && "Cannot get the constant of a non-constant!");
00114     return Val;
00115   }
00116   
00117   Constant *getNotConstant() const {
00118     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
00119     return Val;
00120   }
00121   
00122   ConstantRange getConstantRange() const {
00123     assert(isConstantRange() &&
00124            "Cannot get the constant-range of a non-constant-range!");
00125     return Range;
00126   }
00127   
00128   /// markOverdefined - Return true if this is a change in status.
00129   bool markOverdefined() {
00130     if (isOverdefined())
00131       return false;
00132     Tag = overdefined;
00133     return true;
00134   }
00135 
00136   /// markConstant - Return true if this is a change in status.
00137   bool markConstant(Constant *V) {
00138     assert(V && "Marking constant with NULL");
00139     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
00140       return markConstantRange(ConstantRange(CI->getValue()));
00141     if (isa<UndefValue>(V))
00142       return false;
00143 
00144     assert((!isConstant() || getConstant() == V) &&
00145            "Marking constant with different value");
00146     assert(isUndefined());
00147     Tag = constant;
00148     Val = V;
00149     return true;
00150   }
00151   
00152   /// markNotConstant - Return true if this is a change in status.
00153   bool markNotConstant(Constant *V) {
00154     assert(V && "Marking constant with NULL");
00155     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
00156       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
00157     if (isa<UndefValue>(V))
00158       return false;
00159 
00160     assert((!isConstant() || getConstant() != V) &&
00161            "Marking constant !constant with same value");
00162     assert((!isNotConstant() || getNotConstant() == V) &&
00163            "Marking !constant with different value");
00164     assert(isUndefined() || isConstant());
00165     Tag = notconstant;
00166     Val = V;
00167     return true;
00168   }
00169   
00170   /// markConstantRange - Return true if this is a change in status.
00171   bool markConstantRange(const ConstantRange NewR) {
00172     if (isConstantRange()) {
00173       if (NewR.isEmptySet())
00174         return markOverdefined();
00175       
00176       bool changed = Range != NewR;
00177       Range = NewR;
00178       return changed;
00179     }
00180     
00181     assert(isUndefined());
00182     if (NewR.isEmptySet())
00183       return markOverdefined();
00184     
00185     Tag = constantrange;
00186     Range = NewR;
00187     return true;
00188   }
00189   
00190   /// mergeIn - Merge the specified lattice value into this one, updating this
00191   /// one and returning true if anything changed.
00192   bool mergeIn(const LVILatticeVal &RHS) {
00193     if (RHS.isUndefined() || isOverdefined()) return false;
00194     if (RHS.isOverdefined()) return markOverdefined();
00195 
00196     if (isUndefined()) {
00197       Tag = RHS.Tag;
00198       Val = RHS.Val;
00199       Range = RHS.Range;
00200       return true;
00201     }
00202 
00203     if (isConstant()) {
00204       if (RHS.isConstant()) {
00205         if (Val == RHS.Val)
00206           return false;
00207         return markOverdefined();
00208       }
00209 
00210       if (RHS.isNotConstant()) {
00211         if (Val == RHS.Val)
00212           return markOverdefined();
00213 
00214         // Unless we can prove that the two Constants are different, we must
00215         // move to overdefined.
00216         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
00217         if (ConstantInt *Res = dyn_cast<ConstantInt>(
00218                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
00219                                                 getConstant(),
00220                                                 RHS.getNotConstant())))
00221           if (Res->isOne())
00222             return markNotConstant(RHS.getNotConstant());
00223 
00224         return markOverdefined();
00225       }
00226 
00227       // RHS is a ConstantRange, LHS is a non-integer Constant.
00228 
00229       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
00230       // a function. The correct result is to pick up RHS.
00231 
00232       return markOverdefined();
00233     }
00234 
00235     if (isNotConstant()) {
00236       if (RHS.isConstant()) {
00237         if (Val == RHS.Val)
00238           return markOverdefined();
00239 
00240         // Unless we can prove that the two Constants are different, we must
00241         // move to overdefined.
00242         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
00243         if (ConstantInt *Res = dyn_cast<ConstantInt>(
00244                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
00245                                                 getNotConstant(),
00246                                                 RHS.getConstant())))
00247           if (Res->isOne())
00248             return false;
00249 
00250         return markOverdefined();
00251       }
00252 
00253       if (RHS.isNotConstant()) {
00254         if (Val == RHS.Val)
00255           return false;
00256         return markOverdefined();
00257       }
00258 
00259       return markOverdefined();
00260     }
00261 
00262     assert(isConstantRange() && "New LVILattice type?");
00263     if (!RHS.isConstantRange())
00264       return markOverdefined();
00265 
00266     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
00267     if (NewR.isFullSet())
00268       return markOverdefined();
00269     return markConstantRange(NewR);
00270   }
00271 };
00272   
00273 } // end anonymous namespace.
00274 
00275 namespace llvm {
00276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
00277     LLVM_ATTRIBUTE_USED;
00278 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
00279   if (Val.isUndefined())
00280     return OS << "undefined";
00281   if (Val.isOverdefined())
00282     return OS << "overdefined";
00283 
00284   if (Val.isNotConstant())
00285     return OS << "notconstant<" << *Val.getNotConstant() << '>';
00286   else if (Val.isConstantRange())
00287     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
00288               << Val.getConstantRange().getUpper() << '>';
00289   return OS << "constant<" << *Val.getConstant() << '>';
00290 }
00291 }
00292 
00293 //===----------------------------------------------------------------------===//
00294 //                          LazyValueInfoCache Decl
00295 //===----------------------------------------------------------------------===//
00296 
00297 namespace {
00298   /// LVIValueHandle - A callback value handle updates the cache when
00299   /// values are erased.
00300   class LazyValueInfoCache;
00301   struct LVIValueHandle : public CallbackVH {
00302     LazyValueInfoCache *Parent;
00303       
00304     LVIValueHandle(Value *V, LazyValueInfoCache *P)
00305       : CallbackVH(V), Parent(P) { }
00306 
00307     void deleted() override;
00308     void allUsesReplacedWith(Value *V) override {
00309       deleted();
00310     }
00311   };
00312 }
00313 
00314 namespace { 
00315   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
00316   /// maintains information about queries across the clients' queries.
00317   class LazyValueInfoCache {
00318     /// ValueCacheEntryTy - This is all of the cached block information for
00319     /// exactly one Value*.  The entries are sorted by the BasicBlock* of the
00320     /// entries, allowing us to do a lookup with a binary search.
00321     typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
00322 
00323     /// ValueCache - This is all of the cached information for all values,
00324     /// mapped from Value* to key information.
00325     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
00326     
00327     /// OverDefinedCache - This tracks, on a per-block basis, the set of 
00328     /// values that are over-defined at the end of that block.  This is required
00329     /// for cache updating.
00330     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
00331     DenseSet<OverDefinedPairTy> OverDefinedCache;
00332 
00333     /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
00334     /// don't spend time removing unused blocks from our caches.
00335     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
00336 
00337     /// BlockValueStack - This stack holds the state of the value solver
00338     /// during a query.  It basically emulates the callstack of the naive
00339     /// recursive value lookup process.
00340     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
00341     
00342     friend struct LVIValueHandle;
00343     
00344     /// OverDefinedCacheUpdater - A helper object that ensures that the
00345     /// OverDefinedCache is updated whenever solveBlockValue returns.
00346     struct OverDefinedCacheUpdater {
00347       LazyValueInfoCache *Parent;
00348       Value *Val;
00349       BasicBlock *BB;
00350       LVILatticeVal &BBLV;
00351       
00352       OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
00353                        LazyValueInfoCache *P)
00354         : Parent(P), Val(V), BB(B), BBLV(LV) { }
00355       
00356       bool markResult(bool changed) { 
00357         if (changed && BBLV.isOverdefined())
00358           Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
00359         return changed;
00360       }
00361     };
00362     
00363 
00364 
00365     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
00366     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
00367                       LVILatticeVal &Result);
00368     bool hasBlockValue(Value *Val, BasicBlock *BB);
00369 
00370     // These methods process one work item and may add more. A false value
00371     // returned means that the work item was not completely processed and must
00372     // be revisited after going through the new items.
00373     bool solveBlockValue(Value *Val, BasicBlock *BB);
00374     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
00375                                  Value *Val, BasicBlock *BB);
00376     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
00377                                 PHINode *PN, BasicBlock *BB);
00378     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
00379                                       Instruction *BBI, BasicBlock *BB);
00380 
00381     void solve();
00382     
00383     ValueCacheEntryTy &lookup(Value *V) {
00384       return ValueCache[LVIValueHandle(V, this)];
00385     }
00386 
00387   public:
00388     /// getValueInBlock - This is the query interface to determine the lattice
00389     /// value for the specified Value* at the end of the specified block.
00390     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
00391 
00392     /// getValueOnEdge - This is the query interface to determine the lattice
00393     /// value for the specified Value* that is true on the specified edge.
00394     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
00395     
00396     /// threadEdge - This is the update interface to inform the cache that an
00397     /// edge from PredBB to OldSucc has been threaded to be from PredBB to
00398     /// NewSucc.
00399     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
00400     
00401     /// eraseBlock - This is part of the update interface to inform the cache
00402     /// that a block has been deleted.
00403     void eraseBlock(BasicBlock *BB);
00404     
00405     /// clear - Empty the cache.
00406     void clear() {
00407       SeenBlocks.clear();
00408       ValueCache.clear();
00409       OverDefinedCache.clear();
00410     }
00411   };
00412 } // end anonymous namespace
00413 
00414 void LVIValueHandle::deleted() {
00415   typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
00416   
00417   SmallVector<OverDefinedPairTy, 4> ToErase;
00418   for (DenseSet<OverDefinedPairTy>::iterator 
00419        I = Parent->OverDefinedCache.begin(),
00420        E = Parent->OverDefinedCache.end();
00421        I != E; ++I) {
00422     if (I->second == getValPtr())
00423       ToErase.push_back(*I);
00424   }
00425 
00426   for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
00427        E = ToErase.end(); I != E; ++I)
00428     Parent->OverDefinedCache.erase(*I);
00429   
00430   // This erasure deallocates *this, so it MUST happen after we're done
00431   // using any and all members of *this.
00432   Parent->ValueCache.erase(*this);
00433 }
00434 
00435 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
00436   // Shortcut if we have never seen this block.
00437   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
00438   if (I == SeenBlocks.end())
00439     return;
00440   SeenBlocks.erase(I);
00441 
00442   SmallVector<OverDefinedPairTy, 4> ToErase;
00443   for (DenseSet<OverDefinedPairTy>::iterator  I = OverDefinedCache.begin(),
00444        E = OverDefinedCache.end(); I != E; ++I) {
00445     if (I->first == BB)
00446       ToErase.push_back(*I);
00447   }
00448 
00449   for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
00450        E = ToErase.end(); I != E; ++I)
00451     OverDefinedCache.erase(*I);
00452 
00453   for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
00454        I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
00455     I->second.erase(BB);
00456 }
00457 
00458 void LazyValueInfoCache::solve() {
00459   while (!BlockValueStack.empty()) {
00460     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
00461     if (solveBlockValue(e.second, e.first)) {
00462       assert(BlockValueStack.top() == e);
00463       BlockValueStack.pop();
00464     }
00465   }
00466 }
00467 
00468 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
00469   // If already a constant, there is nothing to compute.
00470   if (isa<Constant>(Val))
00471     return true;
00472 
00473   LVIValueHandle ValHandle(Val, this);
00474   std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
00475     ValueCache.find(ValHandle);
00476   if (I == ValueCache.end()) return false;
00477   return I->second.count(BB);
00478 }
00479 
00480 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
00481   // If already a constant, there is nothing to compute.
00482   if (Constant *VC = dyn_cast<Constant>(Val))
00483     return LVILatticeVal::get(VC);
00484 
00485   SeenBlocks.insert(BB);
00486   return lookup(Val)[BB];
00487 }
00488 
00489 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
00490   if (isa<Constant>(Val))
00491     return true;
00492 
00493   ValueCacheEntryTy &Cache = lookup(Val);
00494   SeenBlocks.insert(BB);
00495   LVILatticeVal &BBLV = Cache[BB];
00496   
00497   // OverDefinedCacheUpdater is a helper object that will update
00498   // the OverDefinedCache for us when this method exits.  Make sure to
00499   // call markResult on it as we exist, passing a bool to indicate if the
00500   // cache needs updating, i.e. if we have solve a new value or not.
00501   OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
00502 
00503   // If we've already computed this block's value, return it.
00504   if (!BBLV.isUndefined()) {
00505     DEBUG(dbgs() << "  reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
00506     
00507     // Since we're reusing a cached value here, we don't need to update the 
00508     // OverDefinedCahce.  The cache will have been properly updated 
00509     // whenever the cached value was inserted.
00510     ODCacheUpdater.markResult(false);
00511     return true;
00512   }
00513 
00514   // Otherwise, this is the first time we're seeing this block.  Reset the
00515   // lattice value to overdefined, so that cycles will terminate and be
00516   // conservatively correct.
00517   BBLV.markOverdefined();
00518   
00519   Instruction *BBI = dyn_cast<Instruction>(Val);
00520   if (!BBI || BBI->getParent() != BB) {
00521     return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
00522   }
00523 
00524   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
00525     return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
00526   }
00527 
00528   if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
00529     BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
00530     return ODCacheUpdater.markResult(true);
00531   }
00532 
00533   // We can only analyze the definitions of certain classes of instructions
00534   // (integral binops and casts at the moment), so bail if this isn't one.
00535   LVILatticeVal Result;
00536   if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
00537      !BBI->getType()->isIntegerTy()) {
00538     DEBUG(dbgs() << " compute BB '" << BB->getName()
00539                  << "' - overdefined because inst def found.\n");
00540     BBLV.markOverdefined();
00541     return ODCacheUpdater.markResult(true);
00542   }
00543 
00544   // FIXME: We're currently limited to binops with a constant RHS.  This should
00545   // be improved.
00546   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
00547   if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 
00548     DEBUG(dbgs() << " compute BB '" << BB->getName()
00549                  << "' - overdefined because inst def found.\n");
00550 
00551     BBLV.markOverdefined();
00552     return ODCacheUpdater.markResult(true);
00553   }
00554 
00555   return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
00556 }
00557 
00558 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
00559   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00560     return L->getPointerAddressSpace() == 0 &&
00561         GetUnderlyingObject(L->getPointerOperand()) == Ptr;
00562   }
00563   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
00564     return S->getPointerAddressSpace() == 0 &&
00565         GetUnderlyingObject(S->getPointerOperand()) == Ptr;
00566   }
00567   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
00568     if (MI->isVolatile()) return false;
00569 
00570     // FIXME: check whether it has a valuerange that excludes zero?
00571     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
00572     if (!Len || Len->isZero()) return false;
00573 
00574     if (MI->getDestAddressSpace() == 0)
00575       if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
00576         return true;
00577     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
00578       if (MTI->getSourceAddressSpace() == 0)
00579         if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
00580           return true;
00581   }
00582   return false;
00583 }
00584 
00585 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
00586                                                  Value *Val, BasicBlock *BB) {
00587   LVILatticeVal Result;  // Start Undefined.
00588 
00589   // If this is a pointer, and there's a load from that pointer in this BB,
00590   // then we know that the pointer can't be NULL.
00591   bool NotNull = false;
00592   if (Val->getType()->isPointerTy()) {
00593     if (isKnownNonNull(Val)) {
00594       NotNull = true;
00595     } else {
00596       Value *UnderlyingVal = GetUnderlyingObject(Val);
00597       // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
00598       // inside InstructionDereferencesPointer either.
00599       if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
00600         for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
00601              BI != BE; ++BI) {
00602           if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
00603             NotNull = true;
00604             break;
00605           }
00606         }
00607       }
00608     }
00609   }
00610 
00611   // If this is the entry block, we must be asking about an argument.  The
00612   // value is overdefined.
00613   if (BB == &BB->getParent()->getEntryBlock()) {
00614     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
00615     if (NotNull) {
00616       PointerType *PTy = cast<PointerType>(Val->getType());
00617       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
00618     } else {
00619       Result.markOverdefined();
00620     }
00621     BBLV = Result;
00622     return true;
00623   }
00624 
00625   // Loop over all of our predecessors, merging what we know from them into
00626   // result.
00627   bool EdgesMissing = false;
00628   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00629     LVILatticeVal EdgeResult;
00630     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
00631     if (EdgesMissing)
00632       continue;
00633 
00634     Result.mergeIn(EdgeResult);
00635 
00636     // If we hit overdefined, exit early.  The BlockVals entry is already set
00637     // to overdefined.
00638     if (Result.isOverdefined()) {
00639       DEBUG(dbgs() << " compute BB '" << BB->getName()
00640             << "' - overdefined because of pred.\n");
00641       // If we previously determined that this is a pointer that can't be null
00642       // then return that rather than giving up entirely.
00643       if (NotNull) {
00644         PointerType *PTy = cast<PointerType>(Val->getType());
00645         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
00646       }
00647       
00648       BBLV = Result;
00649       return true;
00650     }
00651   }
00652   if (EdgesMissing)
00653     return false;
00654 
00655   // Return the merged value, which is more precise than 'overdefined'.
00656   assert(!Result.isOverdefined());
00657   BBLV = Result;
00658   return true;
00659 }
00660   
00661 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
00662                                                 PHINode *PN, BasicBlock *BB) {
00663   LVILatticeVal Result;  // Start Undefined.
00664 
00665   // Loop over all of our predecessors, merging what we know from them into
00666   // result.
00667   bool EdgesMissing = false;
00668   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00669     BasicBlock *PhiBB = PN->getIncomingBlock(i);
00670     Value *PhiVal = PN->getIncomingValue(i);
00671     LVILatticeVal EdgeResult;
00672     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
00673     if (EdgesMissing)
00674       continue;
00675 
00676     Result.mergeIn(EdgeResult);
00677 
00678     // If we hit overdefined, exit early.  The BlockVals entry is already set
00679     // to overdefined.
00680     if (Result.isOverdefined()) {
00681       DEBUG(dbgs() << " compute BB '" << BB->getName()
00682             << "' - overdefined because of pred.\n");
00683       
00684       BBLV = Result;
00685       return true;
00686     }
00687   }
00688   if (EdgesMissing)
00689     return false;
00690 
00691   // Return the merged value, which is more precise than 'overdefined'.
00692   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
00693   BBLV = Result;
00694   return true;
00695 }
00696 
00697 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
00698                                                       Instruction *BBI,
00699                                                       BasicBlock *BB) {
00700   // Figure out the range of the LHS.  If that fails, bail.
00701   if (!hasBlockValue(BBI->getOperand(0), BB)) {
00702     BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
00703     return false;
00704   }
00705 
00706   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
00707   if (!LHSVal.isConstantRange()) {
00708     BBLV.markOverdefined();
00709     return true;
00710   }
00711   
00712   ConstantRange LHSRange = LHSVal.getConstantRange();
00713   ConstantRange RHSRange(1);
00714   IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
00715   if (isa<BinaryOperator>(BBI)) {
00716     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
00717       RHSRange = ConstantRange(RHS->getValue());
00718     } else {
00719       BBLV.markOverdefined();
00720       return true;
00721     }
00722   }
00723 
00724   // NOTE: We're currently limited by the set of operations that ConstantRange
00725   // can evaluate symbolically.  Enhancing that set will allows us to analyze
00726   // more definitions.
00727   LVILatticeVal Result;
00728   switch (BBI->getOpcode()) {
00729   case Instruction::Add:
00730     Result.markConstantRange(LHSRange.add(RHSRange));
00731     break;
00732   case Instruction::Sub:
00733     Result.markConstantRange(LHSRange.sub(RHSRange));
00734     break;
00735   case Instruction::Mul:
00736     Result.markConstantRange(LHSRange.multiply(RHSRange));
00737     break;
00738   case Instruction::UDiv:
00739     Result.markConstantRange(LHSRange.udiv(RHSRange));
00740     break;
00741   case Instruction::Shl:
00742     Result.markConstantRange(LHSRange.shl(RHSRange));
00743     break;
00744   case Instruction::LShr:
00745     Result.markConstantRange(LHSRange.lshr(RHSRange));
00746     break;
00747   case Instruction::Trunc:
00748     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
00749     break;
00750   case Instruction::SExt:
00751     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
00752     break;
00753   case Instruction::ZExt:
00754     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
00755     break;
00756   case Instruction::BitCast:
00757     Result.markConstantRange(LHSRange);
00758     break;
00759   case Instruction::And:
00760     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
00761     break;
00762   case Instruction::Or:
00763     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
00764     break;
00765   
00766   // Unhandled instructions are overdefined.
00767   default:
00768     DEBUG(dbgs() << " compute BB '" << BB->getName()
00769                  << "' - overdefined because inst def found.\n");
00770     Result.markOverdefined();
00771     break;
00772   }
00773   
00774   BBLV = Result;
00775   return true;
00776 }
00777 
00778 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
00779 /// Val is not constrained on the edge.
00780 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
00781                               BasicBlock *BBTo, LVILatticeVal &Result) {
00782   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
00783   // know that v != 0.
00784   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
00785     // If this is a conditional branch and only one successor goes to BBTo, then
00786     // we maybe able to infer something from the condition. 
00787     if (BI->isConditional() &&
00788         BI->getSuccessor(0) != BI->getSuccessor(1)) {
00789       bool isTrueDest = BI->getSuccessor(0) == BBTo;
00790       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
00791              "BBTo isn't a successor of BBFrom");
00792       
00793       // If V is the condition of the branch itself, then we know exactly what
00794       // it is.
00795       if (BI->getCondition() == Val) {
00796         Result = LVILatticeVal::get(ConstantInt::get(
00797                               Type::getInt1Ty(Val->getContext()), isTrueDest));
00798         return true;
00799       }
00800       
00801       // If the condition of the branch is an equality comparison, we may be
00802       // able to infer the value.
00803       ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
00804       if (ICI && isa<Constant>(ICI->getOperand(1))) {
00805         if (ICI->isEquality() && ICI->getOperand(0) == Val) {
00806           // We know that V has the RHS constant if this is a true SETEQ or
00807           // false SETNE. 
00808           if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
00809             Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
00810           else
00811             Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
00812           return true;
00813         }
00814 
00815         // Recognize the range checking idiom that InstCombine produces.
00816         // (X-C1) u< C2 --> [C1, C1+C2)
00817         ConstantInt *NegOffset = nullptr;
00818         if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
00819           match(ICI->getOperand(0), m_Add(m_Specific(Val),
00820                                           m_ConstantInt(NegOffset)));
00821 
00822         ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
00823         if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
00824           // Calculate the range of values that would satisfy the comparison.
00825           ConstantRange CmpRange(CI->getValue());
00826           ConstantRange TrueValues =
00827             ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
00828 
00829           if (NegOffset) // Apply the offset from above.
00830             TrueValues = TrueValues.subtract(NegOffset->getValue());
00831 
00832           // If we're interested in the false dest, invert the condition.
00833           if (!isTrueDest) TrueValues = TrueValues.inverse();
00834 
00835           Result = LVILatticeVal::getRange(TrueValues);
00836           return true;
00837         }
00838       }
00839     }
00840   }
00841 
00842   // If the edge was formed by a switch on the value, then we may know exactly
00843   // what it is.
00844   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
00845     if (SI->getCondition() != Val)
00846       return false;
00847 
00848     bool DefaultCase = SI->getDefaultDest() == BBTo;
00849     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
00850     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
00851 
00852     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00853          i != e; ++i) {
00854       ConstantRange EdgeVal(i.getCaseValue()->getValue());
00855       if (DefaultCase) {
00856         // It is possible that the default destination is the destination of
00857         // some cases. There is no need to perform difference for those cases.
00858         if (i.getCaseSuccessor() != BBTo)
00859           EdgesVals = EdgesVals.difference(EdgeVal);
00860       } else if (i.getCaseSuccessor() == BBTo)
00861         EdgesVals = EdgesVals.unionWith(EdgeVal);
00862     }
00863     Result = LVILatticeVal::getRange(EdgesVals);
00864     return true;
00865   }
00866   return false;
00867 }
00868 
00869 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
00870 /// the basic block if the edge does not constraint Val.
00871 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
00872                                       BasicBlock *BBTo, LVILatticeVal &Result) {
00873   // If already a constant, there is nothing to compute.
00874   if (Constant *VC = dyn_cast<Constant>(Val)) {
00875     Result = LVILatticeVal::get(VC);
00876     return true;
00877   }
00878 
00879   if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
00880     if (!Result.isConstantRange() ||
00881       Result.getConstantRange().getSingleElement())
00882       return true;
00883 
00884     // FIXME: this check should be moved to the beginning of the function when
00885     // LVI better supports recursive values. Even for the single value case, we
00886     // can intersect to detect dead code (an empty range).
00887     if (!hasBlockValue(Val, BBFrom)) {
00888       BlockValueStack.push(std::make_pair(BBFrom, Val));
00889       return false;
00890     }
00891 
00892     // Try to intersect ranges of the BB and the constraint on the edge.
00893     LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
00894     if (!InBlock.isConstantRange())
00895       return true;
00896 
00897     ConstantRange Range =
00898       Result.getConstantRange().intersectWith(InBlock.getConstantRange());
00899     Result = LVILatticeVal::getRange(Range);
00900     return true;
00901   }
00902 
00903   if (!hasBlockValue(Val, BBFrom)) {
00904     BlockValueStack.push(std::make_pair(BBFrom, Val));
00905     return false;
00906   }
00907 
00908   // if we couldn't compute the value on the edge, use the value from the BB
00909   Result = getBlockValue(Val, BBFrom);
00910   return true;
00911 }
00912 
00913 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
00914   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
00915         << BB->getName() << "'\n");
00916   
00917   BlockValueStack.push(std::make_pair(BB, V));
00918   solve();
00919   LVILatticeVal Result = getBlockValue(V, BB);
00920 
00921   DEBUG(dbgs() << "  Result = " << Result << "\n");
00922   return Result;
00923 }
00924 
00925 LVILatticeVal LazyValueInfoCache::
00926 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
00927   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
00928         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
00929   
00930   LVILatticeVal Result;
00931   if (!getEdgeValue(V, FromBB, ToBB, Result)) {
00932     solve();
00933     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
00934     (void)WasFastQuery;
00935     assert(WasFastQuery && "More work to do after problem solved?");
00936   }
00937 
00938   DEBUG(dbgs() << "  Result = " << Result << "\n");
00939   return Result;
00940 }
00941 
00942 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
00943                                     BasicBlock *NewSucc) {
00944   // When an edge in the graph has been threaded, values that we could not 
00945   // determine a value for before (i.e. were marked overdefined) may be possible
00946   // to solve now.  We do NOT try to proactively update these values.  Instead,
00947   // we clear their entries from the cache, and allow lazy updating to recompute
00948   // them when needed.
00949   
00950   // The updating process is fairly simple: we need to dropped cached info
00951   // for all values that were marked overdefined in OldSucc, and for those same
00952   // values in any successor of OldSucc (except NewSucc) in which they were
00953   // also marked overdefined.
00954   std::vector<BasicBlock*> worklist;
00955   worklist.push_back(OldSucc);
00956   
00957   DenseSet<Value*> ClearSet;
00958   for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
00959        E = OverDefinedCache.end(); I != E; ++I) {
00960     if (I->first == OldSucc)
00961       ClearSet.insert(I->second);
00962   }
00963   
00964   // Use a worklist to perform a depth-first search of OldSucc's successors.
00965   // NOTE: We do not need a visited list since any blocks we have already
00966   // visited will have had their overdefined markers cleared already, and we
00967   // thus won't loop to their successors.
00968   while (!worklist.empty()) {
00969     BasicBlock *ToUpdate = worklist.back();
00970     worklist.pop_back();
00971     
00972     // Skip blocks only accessible through NewSucc.
00973     if (ToUpdate == NewSucc) continue;
00974     
00975     bool changed = false;
00976     for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
00977          I != E; ++I) {
00978       // If a value was marked overdefined in OldSucc, and is here too...
00979       DenseSet<OverDefinedPairTy>::iterator OI =
00980         OverDefinedCache.find(std::make_pair(ToUpdate, *I));
00981       if (OI == OverDefinedCache.end()) continue;
00982 
00983       // Remove it from the caches.
00984       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
00985       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
00986 
00987       assert(CI != Entry.end() && "Couldn't find entry to update?");
00988       Entry.erase(CI);
00989       OverDefinedCache.erase(OI);
00990 
00991       // If we removed anything, then we potentially need to update 
00992       // blocks successors too.
00993       changed = true;
00994     }
00995 
00996     if (!changed) continue;
00997     
00998     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
00999   }
01000 }
01001 
01002 //===----------------------------------------------------------------------===//
01003 //                            LazyValueInfo Impl
01004 //===----------------------------------------------------------------------===//
01005 
01006 /// getCache - This lazily constructs the LazyValueInfoCache.
01007 static LazyValueInfoCache &getCache(void *&PImpl) {
01008   if (!PImpl)
01009     PImpl = new LazyValueInfoCache();
01010   return *static_cast<LazyValueInfoCache*>(PImpl);
01011 }
01012 
01013 bool LazyValueInfo::runOnFunction(Function &F) {
01014   if (PImpl)
01015     getCache(PImpl).clear();
01016 
01017   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01018   DL = DLP ? &DLP->getDataLayout() : nullptr;
01019   TLI = &getAnalysis<TargetLibraryInfo>();
01020 
01021   // Fully lazy.
01022   return false;
01023 }
01024 
01025 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
01026   AU.setPreservesAll();
01027   AU.addRequired<TargetLibraryInfo>();
01028 }
01029 
01030 void LazyValueInfo::releaseMemory() {
01031   // If the cache was allocated, free it.
01032   if (PImpl) {
01033     delete &getCache(PImpl);
01034     PImpl = nullptr;
01035   }
01036 }
01037 
01038 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
01039   LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
01040   
01041   if (Result.isConstant())
01042     return Result.getConstant();
01043   if (Result.isConstantRange()) {
01044     ConstantRange CR = Result.getConstantRange();
01045     if (const APInt *SingleVal = CR.getSingleElement())
01046       return ConstantInt::get(V->getContext(), *SingleVal);
01047   }
01048   return nullptr;
01049 }
01050 
01051 /// getConstantOnEdge - Determine whether the specified value is known to be a
01052 /// constant on the specified edge.  Return null if not.
01053 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
01054                                            BasicBlock *ToBB) {
01055   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
01056   
01057   if (Result.isConstant())
01058     return Result.getConstant();
01059   if (Result.isConstantRange()) {
01060     ConstantRange CR = Result.getConstantRange();
01061     if (const APInt *SingleVal = CR.getSingleElement())
01062       return ConstantInt::get(V->getContext(), *SingleVal);
01063   }
01064   return nullptr;
01065 }
01066 
01067 /// getPredicateOnEdge - Determine whether the specified value comparison
01068 /// with a constant is known to be true or false on the specified CFG edge.
01069 /// Pred is a CmpInst predicate.
01070 LazyValueInfo::Tristate
01071 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
01072                                   BasicBlock *FromBB, BasicBlock *ToBB) {
01073   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
01074   
01075   // If we know the value is a constant, evaluate the conditional.
01076   Constant *Res = nullptr;
01077   if (Result.isConstant()) {
01078     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
01079                                           TLI);
01080     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
01081       return ResCI->isZero() ? False : True;
01082     return Unknown;
01083   }
01084   
01085   if (Result.isConstantRange()) {
01086     ConstantInt *CI = dyn_cast<ConstantInt>(C);
01087     if (!CI) return Unknown;
01088     
01089     ConstantRange CR = Result.getConstantRange();
01090     if (Pred == ICmpInst::ICMP_EQ) {
01091       if (!CR.contains(CI->getValue()))
01092         return False;
01093       
01094       if (CR.isSingleElement() && CR.contains(CI->getValue()))
01095         return True;
01096     } else if (Pred == ICmpInst::ICMP_NE) {
01097       if (!CR.contains(CI->getValue()))
01098         return True;
01099       
01100       if (CR.isSingleElement() && CR.contains(CI->getValue()))
01101         return False;
01102     }
01103     
01104     // Handle more complex predicates.
01105     ConstantRange TrueValues =
01106         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
01107     if (TrueValues.contains(CR))
01108       return True;
01109     if (TrueValues.inverse().contains(CR))
01110       return False;
01111     return Unknown;
01112   }
01113   
01114   if (Result.isNotConstant()) {
01115     // If this is an equality comparison, we can try to fold it knowing that
01116     // "V != C1".
01117     if (Pred == ICmpInst::ICMP_EQ) {
01118       // !C1 == C -> false iff C1 == C.
01119       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
01120                                             Result.getNotConstant(), C, DL,
01121                                             TLI);
01122       if (Res->isNullValue())
01123         return False;
01124     } else if (Pred == ICmpInst::ICMP_NE) {
01125       // !C1 != C -> true iff C1 == C.
01126       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
01127                                             Result.getNotConstant(), C, DL,
01128                                             TLI);
01129       if (Res->isNullValue())
01130         return True;
01131     }
01132     return Unknown;
01133   }
01134   
01135   return Unknown;
01136 }
01137 
01138 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
01139                                BasicBlock *NewSucc) {
01140   if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
01141 }
01142 
01143 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
01144   if (PImpl) getCache(PImpl).eraseBlock(BB);
01145 }