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