1 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for lazy computation of value constraint
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/STLExtras.h"
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
39 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
40 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
41 "Lazy Value Information Analysis", false, true)
44 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
55 /// FIXME: This is basically just for bringup, this can be made a lot more rich
61 /// undefined - This Value has no known value yet.
64 /// constant - This Value has a specific constant value.
66 /// notconstant - This Value is known to not have the specified value.
69 /// constantrange - The Value falls within this range.
72 /// overdefined - This value is not known to be constant, and we know that
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'notconstant' value.
84 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
86 static LVILatticeVal get(Constant *C) {
88 if (!isa<UndefValue>(C))
92 static LVILatticeVal getNot(Constant *C) {
94 if (!isa<UndefValue>(C))
95 Res.markNotConstant(C);
98 static LVILatticeVal getRange(ConstantRange CR) {
100 Res.markConstantRange(CR);
104 bool isUndefined() const { return Tag == undefined; }
105 bool isConstant() const { return Tag == constant; }
106 bool isNotConstant() const { return Tag == notconstant; }
107 bool isConstantRange() const { return Tag == constantrange; }
108 bool isOverdefined() const { return Tag == overdefined; }
110 Constant *getConstant() const {
111 assert(isConstant() && "Cannot get the constant of a non-constant!");
115 Constant *getNotConstant() const {
116 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
120 ConstantRange getConstantRange() const {
121 assert(isConstantRange() &&
122 "Cannot get the constant-range of a non-constant-range!");
126 /// markOverdefined - Return true if this is a change in status.
127 bool markOverdefined() {
134 /// markConstant - Return true if this is a change in status.
135 bool markConstant(Constant *V) {
136 assert(V && "Marking constant with NULL");
137 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
138 return markConstantRange(ConstantRange(CI->getValue()));
139 if (isa<UndefValue>(V))
142 assert((!isConstant() || getConstant() == V) &&
143 "Marking constant with different value");
144 assert(isUndefined());
150 /// markNotConstant - Return true if this is a change in status.
151 bool markNotConstant(Constant *V) {
152 assert(V && "Marking constant with NULL");
153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
155 if (isa<UndefValue>(V))
158 assert((!isConstant() || getConstant() != V) &&
159 "Marking constant !constant with same value");
160 assert((!isNotConstant() || getNotConstant() == V) &&
161 "Marking !constant with different value");
162 assert(isUndefined() || isConstant());
168 /// markConstantRange - Return true if this is a change in status.
169 bool markConstantRange(const ConstantRange NewR) {
170 if (isConstantRange()) {
171 if (NewR.isEmptySet())
172 return markOverdefined();
174 bool changed = Range == NewR;
179 assert(isUndefined());
180 if (NewR.isEmptySet())
181 return markOverdefined();
188 /// mergeIn - Merge the specified lattice value into this one, updating this
189 /// one and returning true if anything changed.
190 bool mergeIn(const LVILatticeVal &RHS) {
191 if (RHS.isUndefined() || isOverdefined()) return false;
192 if (RHS.isOverdefined()) return markOverdefined();
202 if (RHS.isConstant()) {
205 return markOverdefined();
208 if (RHS.isNotConstant()) {
210 return markOverdefined();
212 // Unless we can prove that the two Constants are different, we must
213 // move to overdefined.
214 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
215 if (ConstantInt *Res = dyn_cast<ConstantInt>(
216 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
218 RHS.getNotConstant())))
220 return markNotConstant(RHS.getNotConstant());
222 return markOverdefined();
225 // RHS is a ConstantRange, LHS is a non-integer Constant.
227 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
228 // a function. The correct result is to pick up RHS.
230 return markOverdefined();
233 if (isNotConstant()) {
234 if (RHS.isConstant()) {
236 return markOverdefined();
238 // Unless we can prove that the two Constants are different, we must
239 // move to overdefined.
240 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
241 if (ConstantInt *Res = dyn_cast<ConstantInt>(
242 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
248 return markOverdefined();
251 if (RHS.isNotConstant()) {
254 return markOverdefined();
257 return markOverdefined();
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
271 } // end anonymous namespace.
274 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
287 return OS << "constant<" << *Val.getConstant() << '>';
291 //===----------------------------------------------------------------------===//
292 // LazyValueInfoCache Decl
293 //===----------------------------------------------------------------------===//
296 /// LVIValueHandle - A callback value handle update the cache when
297 /// values are erased.
298 class LazyValueInfoCache;
299 struct LVIValueHandle : public CallbackVH {
300 LazyValueInfoCache *Parent;
302 LVIValueHandle(Value *V, LazyValueInfoCache *P)
303 : CallbackVH(V), Parent(P) { }
306 void allUsesReplacedWith(Value *V) {
314 struct DenseMapInfo<LVIValueHandle> {
315 typedef DenseMapInfo<Value*> PointerInfo;
316 static inline LVIValueHandle getEmptyKey() {
317 return LVIValueHandle(PointerInfo::getEmptyKey(),
318 static_cast<LazyValueInfoCache*>(0));
320 static inline LVIValueHandle getTombstoneKey() {
321 return LVIValueHandle(PointerInfo::getTombstoneKey(),
322 static_cast<LazyValueInfoCache*>(0));
324 static unsigned getHashValue(const LVIValueHandle &Val) {
325 return PointerInfo::getHashValue(Val);
327 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
333 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
334 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
335 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
336 typedef DenseMapInfo<Value*> BPointerInfo;
337 static inline PairTy getEmptyKey() {
338 return std::make_pair(APointerInfo::getEmptyKey(),
339 BPointerInfo::getEmptyKey());
341 static inline PairTy getTombstoneKey() {
342 return std::make_pair(APointerInfo::getTombstoneKey(),
343 BPointerInfo::getTombstoneKey());
345 static unsigned getHashValue( const PairTy &Val) {
346 return APointerInfo::getHashValue(Val.first) ^
347 BPointerInfo::getHashValue(Val.second);
349 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
350 return APointerInfo::isEqual(LHS.first, RHS.first) &&
351 BPointerInfo::isEqual(LHS.second, RHS.second);
357 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
358 /// maintains information about queries across the clients' queries.
359 class LazyValueInfoCache {
360 /// ValueCacheEntryTy - This is all of the cached block information for
361 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
362 /// entries, allowing us to do a lookup with a binary search.
363 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
365 /// ValueCache - This is all of the cached information for all values,
366 /// mapped from Value* to key information.
367 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
369 /// OverDefinedCache - This tracks, on a per-block basis, the set of
370 /// values that are over-defined at the end of that block. This is required
371 /// for cache updating.
372 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
373 DenseSet<OverDefinedPairTy> OverDefinedCache;
375 /// BlockValueStack - This stack holds the state of the value solver
376 /// during a query. It basically emulates the callstack of the naive
377 /// recursive value lookup process.
378 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
380 friend struct LVIValueHandle;
382 /// OverDefinedCacheUpdater - A helper object that ensures that the
383 /// OverDefinedCache is updated whenever solveBlockValue returns.
384 struct OverDefinedCacheUpdater {
385 LazyValueInfoCache *Parent;
390 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
391 LazyValueInfoCache *P)
392 : Parent(P), Val(V), BB(B), BBLV(LV) { }
394 bool markResult(bool changed) {
395 if (changed && BBLV.isOverdefined())
396 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
403 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
404 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
405 LVILatticeVal &Result);
406 bool hasBlockValue(Value *Val, BasicBlock *BB);
408 // These methods process one work item and may add more. A false value
409 // returned means that the work item was not completely processed and must
410 // be revisited after going through the new items.
411 bool solveBlockValue(Value *Val, BasicBlock *BB);
412 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
413 Value *Val, BasicBlock *BB);
414 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
415 PHINode *PN, BasicBlock *BB);
416 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
417 Instruction *BBI, BasicBlock *BB);
421 ValueCacheEntryTy &lookup(Value *V) {
422 return ValueCache[LVIValueHandle(V, this)];
426 /// getValueInBlock - This is the query interface to determine the lattice
427 /// value for the specified Value* at the end of the specified block.
428 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
430 /// getValueOnEdge - This is the query interface to determine the lattice
431 /// value for the specified Value* that is true on the specified edge.
432 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
434 /// threadEdge - This is the update interface to inform the cache that an
435 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
437 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
439 /// eraseBlock - This is part of the update interface to inform the cache
440 /// that a block has been deleted.
441 void eraseBlock(BasicBlock *BB);
443 /// clear - Empty the cache.
446 OverDefinedCache.clear();
449 } // end anonymous namespace
451 void LVIValueHandle::deleted() {
452 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
454 SmallVector<OverDefinedPairTy, 4> ToErase;
455 for (DenseSet<OverDefinedPairTy>::iterator
456 I = Parent->OverDefinedCache.begin(),
457 E = Parent->OverDefinedCache.end();
459 if (I->second == getValPtr())
460 ToErase.push_back(*I);
463 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
464 E = ToErase.end(); I != E; ++I)
465 Parent->OverDefinedCache.erase(*I);
467 // This erasure deallocates *this, so it MUST happen after we're done
468 // using any and all members of *this.
469 Parent->ValueCache.erase(*this);
472 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
473 SmallVector<OverDefinedPairTy, 4> ToErase;
474 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
475 E = OverDefinedCache.end(); I != E; ++I) {
477 ToErase.push_back(*I);
480 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
481 E = ToErase.end(); I != E; ++I)
482 OverDefinedCache.erase(*I);
484 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
485 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
489 void LazyValueInfoCache::solve() {
490 while (!BlockValueStack.empty()) {
491 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
492 if (solveBlockValue(e.second, e.first))
493 BlockValueStack.pop();
497 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
498 // If already a constant, there is nothing to compute.
499 if (isa<Constant>(Val))
502 LVIValueHandle ValHandle(Val, this);
503 if (!ValueCache.count(ValHandle)) return false;
504 return ValueCache[ValHandle].count(BB);
507 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
508 // If already a constant, there is nothing to compute.
509 if (Constant *VC = dyn_cast<Constant>(Val))
510 return LVILatticeVal::get(VC);
512 return lookup(Val)[BB];
515 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
516 if (isa<Constant>(Val))
519 ValueCacheEntryTy &Cache = lookup(Val);
520 LVILatticeVal &BBLV = Cache[BB];
522 // OverDefinedCacheUpdater is a helper object that will update
523 // the OverDefinedCache for us when this method exits. Make sure to
524 // call markResult on it as we exist, passing a bool to indicate if the
525 // cache needs updating, i.e. if we have solve a new value or not.
526 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
528 // If we've already computed this block's value, return it.
529 if (!BBLV.isUndefined()) {
530 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
532 // Since we're reusing a cached value here, we don't need to update the
533 // OverDefinedCahce. The cache will have been properly updated
534 // whenever the cached value was inserted.
535 ODCacheUpdater.markResult(false);
539 // Otherwise, this is the first time we're seeing this block. Reset the
540 // lattice value to overdefined, so that cycles will terminate and be
541 // conservatively correct.
542 BBLV.markOverdefined();
544 Instruction *BBI = dyn_cast<Instruction>(Val);
545 if (BBI == 0 || BBI->getParent() != BB) {
546 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
549 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
550 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
553 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
554 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
555 return ODCacheUpdater.markResult(true);
558 // We can only analyze the definitions of certain classes of instructions
559 // (integral binops and casts at the moment), so bail if this isn't one.
560 LVILatticeVal Result;
561 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
562 !BBI->getType()->isIntegerTy()) {
563 DEBUG(dbgs() << " compute BB '" << BB->getName()
564 << "' - overdefined because inst def found.\n");
565 BBLV.markOverdefined();
566 return ODCacheUpdater.markResult(true);
569 // FIXME: We're currently limited to binops with a constant RHS. This should
571 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
572 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
573 DEBUG(dbgs() << " compute BB '" << BB->getName()
574 << "' - overdefined because inst def found.\n");
576 BBLV.markOverdefined();
577 return ODCacheUpdater.markResult(true);
580 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
583 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
584 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
585 return L->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(L->getPointerOperand()) ==
587 GetUnderlyingObject(Ptr);
589 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
590 return S->getPointerAddressSpace() == 0 &&
591 GetUnderlyingObject(S->getPointerOperand()) ==
592 GetUnderlyingObject(Ptr);
594 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
595 if (MI->isVolatile()) return false;
597 // FIXME: check whether it has a valuerange that excludes zero?
598 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
599 if (!Len || Len->isZero()) return false;
601 if (MI->getDestAddressSpace() == 0)
602 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
604 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
605 if (MTI->getSourceAddressSpace() == 0)
606 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
612 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
613 Value *Val, BasicBlock *BB) {
614 LVILatticeVal Result; // Start Undefined.
616 // If this is a pointer, and there's a load from that pointer in this BB,
617 // then we know that the pointer can't be NULL.
618 bool NotNull = false;
619 if (Val->getType()->isPointerTy()) {
620 if (isa<AllocaInst>(Val)) {
623 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
624 if (InstructionDereferencesPointer(BI, Val)) {
632 // If this is the entry block, we must be asking about an argument. The
633 // value is overdefined.
634 if (BB == &BB->getParent()->getEntryBlock()) {
635 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
637 PointerType *PTy = cast<PointerType>(Val->getType());
638 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
640 Result.markOverdefined();
646 // Loop over all of our predecessors, merging what we know from them into
648 bool EdgesMissing = false;
649 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
650 LVILatticeVal EdgeResult;
651 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
655 Result.mergeIn(EdgeResult);
657 // If we hit overdefined, exit early. The BlockVals entry is already set
659 if (Result.isOverdefined()) {
660 DEBUG(dbgs() << " compute BB '" << BB->getName()
661 << "' - overdefined because of pred.\n");
662 // If we previously determined that this is a pointer that can't be null
663 // then return that rather than giving up entirely.
665 PointerType *PTy = cast<PointerType>(Val->getType());
666 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
676 // Return the merged value, which is more precise than 'overdefined'.
677 assert(!Result.isOverdefined());
682 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
683 PHINode *PN, BasicBlock *BB) {
684 LVILatticeVal Result; // Start Undefined.
686 // Loop over all of our predecessors, merging what we know from them into
688 bool EdgesMissing = false;
689 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
690 BasicBlock *PhiBB = PN->getIncomingBlock(i);
691 Value *PhiVal = PN->getIncomingValue(i);
692 LVILatticeVal EdgeResult;
693 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
697 Result.mergeIn(EdgeResult);
699 // If we hit overdefined, exit early. The BlockVals entry is already set
701 if (Result.isOverdefined()) {
702 DEBUG(dbgs() << " compute BB '" << BB->getName()
703 << "' - overdefined because of pred.\n");
712 // Return the merged value, which is more precise than 'overdefined'.
713 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
718 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
721 // Figure out the range of the LHS. If that fails, bail.
722 if (!hasBlockValue(BBI->getOperand(0), BB)) {
723 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
727 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
728 if (!LHSVal.isConstantRange()) {
729 BBLV.markOverdefined();
733 ConstantRange LHSRange = LHSVal.getConstantRange();
734 ConstantRange RHSRange(1);
735 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
736 if (isa<BinaryOperator>(BBI)) {
737 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
738 RHSRange = ConstantRange(RHS->getValue());
740 BBLV.markOverdefined();
745 // NOTE: We're currently limited by the set of operations that ConstantRange
746 // can evaluate symbolically. Enhancing that set will allows us to analyze
748 LVILatticeVal Result;
749 switch (BBI->getOpcode()) {
750 case Instruction::Add:
751 Result.markConstantRange(LHSRange.add(RHSRange));
753 case Instruction::Sub:
754 Result.markConstantRange(LHSRange.sub(RHSRange));
756 case Instruction::Mul:
757 Result.markConstantRange(LHSRange.multiply(RHSRange));
759 case Instruction::UDiv:
760 Result.markConstantRange(LHSRange.udiv(RHSRange));
762 case Instruction::Shl:
763 Result.markConstantRange(LHSRange.shl(RHSRange));
765 case Instruction::LShr:
766 Result.markConstantRange(LHSRange.lshr(RHSRange));
768 case Instruction::Trunc:
769 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
771 case Instruction::SExt:
772 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
774 case Instruction::ZExt:
775 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
777 case Instruction::BitCast:
778 Result.markConstantRange(LHSRange);
780 case Instruction::And:
781 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
783 case Instruction::Or:
784 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
787 // Unhandled instructions are overdefined.
789 DEBUG(dbgs() << " compute BB '" << BB->getName()
790 << "' - overdefined because inst def found.\n");
791 Result.markOverdefined();
799 /// getEdgeValue - This method attempts to infer more complex
800 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
801 BasicBlock *BBTo, LVILatticeVal &Result) {
802 // If already a constant, there is nothing to compute.
803 if (Constant *VC = dyn_cast<Constant>(Val)) {
804 Result = LVILatticeVal::get(VC);
808 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
810 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
811 // If this is a conditional branch and only one successor goes to BBTo, then
812 // we maybe able to infer something from the condition.
813 if (BI->isConditional() &&
814 BI->getSuccessor(0) != BI->getSuccessor(1)) {
815 bool isTrueDest = BI->getSuccessor(0) == BBTo;
816 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
817 "BBTo isn't a successor of BBFrom");
819 // If V is the condition of the branch itself, then we know exactly what
821 if (BI->getCondition() == Val) {
822 Result = LVILatticeVal::get(ConstantInt::get(
823 Type::getInt1Ty(Val->getContext()), isTrueDest));
827 // If the condition of the branch is an equality comparison, we may be
828 // able to infer the value.
829 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
830 if (ICI && ICI->getOperand(0) == Val &&
831 isa<Constant>(ICI->getOperand(1))) {
832 if (ICI->isEquality()) {
833 // We know that V has the RHS constant if this is a true SETEQ or
835 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
836 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
838 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
842 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
843 // Calculate the range of values that would satisfy the comparison.
844 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
845 ConstantRange TrueValues =
846 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
848 // If we're interested in the false dest, invert the condition.
849 if (!isTrueDest) TrueValues = TrueValues.inverse();
851 // Figure out the possible values of the query BEFORE this branch.
852 if (!hasBlockValue(Val, BBFrom)) {
853 BlockValueStack.push(std::make_pair(BBFrom, Val));
857 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
858 if (!InBlock.isConstantRange()) {
859 Result = LVILatticeVal::getRange(TrueValues);
863 // Find all potential values that satisfy both the input and output
865 ConstantRange PossibleValues =
866 TrueValues.intersectWith(InBlock.getConstantRange());
868 Result = LVILatticeVal::getRange(PossibleValues);
875 // If the edge was formed by a switch on the value, then we may know exactly
877 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
878 if (SI->getCondition() == Val) {
879 // We don't know anything in the default case.
880 if (SI->getDefaultDest() == BBTo) {
881 Result.markOverdefined();
885 // We only know something if there is exactly one value that goes from
887 unsigned NumEdges = 0;
888 ConstantInt *EdgeVal = 0;
889 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
890 if (SI->getSuccessor(i) != BBTo) continue;
891 if (NumEdges++) break;
892 EdgeVal = SI->getCaseValue(i);
894 assert(EdgeVal && "Missing successor?");
896 Result = LVILatticeVal::get(EdgeVal);
902 // Otherwise see if the value is known in the block.
903 if (hasBlockValue(Val, BBFrom)) {
904 Result = getBlockValue(Val, BBFrom);
907 BlockValueStack.push(std::make_pair(BBFrom, Val));
911 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
912 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
913 << BB->getName() << "'\n");
915 BlockValueStack.push(std::make_pair(BB, V));
917 LVILatticeVal Result = getBlockValue(V, BB);
919 DEBUG(dbgs() << " Result = " << Result << "\n");
923 LVILatticeVal LazyValueInfoCache::
924 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
925 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
926 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
928 LVILatticeVal Result;
929 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
931 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
933 assert(WasFastQuery && "More work to do after problem solved?");
936 DEBUG(dbgs() << " Result = " << Result << "\n");
940 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
941 BasicBlock *NewSucc) {
942 // When an edge in the graph has been threaded, values that we could not
943 // determine a value for before (i.e. were marked overdefined) may be possible
944 // to solve now. We do NOT try to proactively update these values. Instead,
945 // we clear their entries from the cache, and allow lazy updating to recompute
948 // The updating process is fairly simple: we need to dropped cached info
949 // for all values that were marked overdefined in OldSucc, and for those same
950 // values in any successor of OldSucc (except NewSucc) in which they were
951 // also marked overdefined.
952 std::vector<BasicBlock*> worklist;
953 worklist.push_back(OldSucc);
955 DenseSet<Value*> ClearSet;
956 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
957 E = OverDefinedCache.end(); I != E; ++I) {
958 if (I->first == OldSucc)
959 ClearSet.insert(I->second);
962 // Use a worklist to perform a depth-first search of OldSucc's successors.
963 // NOTE: We do not need a visited list since any blocks we have already
964 // visited will have had their overdefined markers cleared already, and we
965 // thus won't loop to their successors.
966 while (!worklist.empty()) {
967 BasicBlock *ToUpdate = worklist.back();
970 // Skip blocks only accessible through NewSucc.
971 if (ToUpdate == NewSucc) continue;
973 bool changed = false;
974 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
976 // If a value was marked overdefined in OldSucc, and is here too...
977 DenseSet<OverDefinedPairTy>::iterator OI =
978 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
979 if (OI == OverDefinedCache.end()) continue;
981 // Remove it from the caches.
982 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
983 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
985 assert(CI != Entry.end() && "Couldn't find entry to update?");
987 OverDefinedCache.erase(OI);
989 // If we removed anything, then we potentially need to update
990 // blocks successors too.
994 if (!changed) continue;
996 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1000 //===----------------------------------------------------------------------===//
1001 // LazyValueInfo Impl
1002 //===----------------------------------------------------------------------===//
1004 /// getCache - This lazily constructs the LazyValueInfoCache.
1005 static LazyValueInfoCache &getCache(void *&PImpl) {
1007 PImpl = new LazyValueInfoCache();
1008 return *static_cast<LazyValueInfoCache*>(PImpl);
1011 bool LazyValueInfo::runOnFunction(Function &F) {
1013 getCache(PImpl).clear();
1015 TD = getAnalysisIfAvailable<TargetData>();
1016 TLI = &getAnalysis<TargetLibraryInfo>();
1022 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1023 AU.setPreservesAll();
1024 AU.addRequired<TargetLibraryInfo>();
1027 void LazyValueInfo::releaseMemory() {
1028 // If the cache was allocated, free it.
1030 delete &getCache(PImpl);
1035 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1036 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1038 if (Result.isConstant())
1039 return Result.getConstant();
1040 if (Result.isConstantRange()) {
1041 ConstantRange CR = Result.getConstantRange();
1042 if (const APInt *SingleVal = CR.getSingleElement())
1043 return ConstantInt::get(V->getContext(), *SingleVal);
1048 /// getConstantOnEdge - Determine whether the specified value is known to be a
1049 /// constant on the specified edge. Return null if not.
1050 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1052 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1054 if (Result.isConstant())
1055 return Result.getConstant();
1056 if (Result.isConstantRange()) {
1057 ConstantRange CR = Result.getConstantRange();
1058 if (const APInt *SingleVal = CR.getSingleElement())
1059 return ConstantInt::get(V->getContext(), *SingleVal);
1064 /// getPredicateOnEdge - Determine whether the specified value comparison
1065 /// with a constant is known to be true or false on the specified CFG edge.
1066 /// Pred is a CmpInst predicate.
1067 LazyValueInfo::Tristate
1068 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1069 BasicBlock *FromBB, BasicBlock *ToBB) {
1070 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1072 // If we know the value is a constant, evaluate the conditional.
1074 if (Result.isConstant()) {
1075 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1077 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1078 return ResCI->isZero() ? False : True;
1082 if (Result.isConstantRange()) {
1083 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1084 if (!CI) return Unknown;
1086 ConstantRange CR = Result.getConstantRange();
1087 if (Pred == ICmpInst::ICMP_EQ) {
1088 if (!CR.contains(CI->getValue()))
1091 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1093 } else if (Pred == ICmpInst::ICMP_NE) {
1094 if (!CR.contains(CI->getValue()))
1097 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1101 // Handle more complex predicates.
1102 ConstantRange TrueValues =
1103 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1104 if (TrueValues.contains(CR))
1106 if (TrueValues.inverse().contains(CR))
1111 if (Result.isNotConstant()) {
1112 // If this is an equality comparison, we can try to fold it knowing that
1114 if (Pred == ICmpInst::ICMP_EQ) {
1115 // !C1 == C -> false iff C1 == C.
1116 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1117 Result.getNotConstant(), C, TD,
1119 if (Res->isNullValue())
1121 } else if (Pred == ICmpInst::ICMP_NE) {
1122 // !C1 != C -> true iff C1 == C.
1123 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1124 Result.getNotConstant(), C, TD,
1126 if (Res->isNullValue())
1135 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1136 BasicBlock *NewSucc) {
1137 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1140 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1141 if (PImpl) getCache(PImpl).eraseBlock(BB);