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