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/Analysis/ConstantFolding.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/ConstantRange.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/STLExtras.h"
35 char LazyValueInfo::ID = 0;
36 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
37 "Lazy Value Information Analysis", false, true)
40 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
51 /// FIXME: This is basically just for bringup, this can be made a lot more rich
57 /// undefined - This Value has no known value yet.
60 /// constant - This Value has a specific constant value.
62 /// notconstant - This Value is known to not have the specified value.
65 /// constantrange - The Value falls within this range.
68 /// overdefined - This value is not known to be constant, and we know that
73 /// Val: This stores the current lattice value along with the Constant* for
74 /// the constant if this is a 'constant' or 'notconstant' value.
80 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
82 static LVILatticeVal get(Constant *C) {
84 if (!isa<UndefValue>(C))
88 static LVILatticeVal getNot(Constant *C) {
90 if (!isa<UndefValue>(C))
91 Res.markNotConstant(C);
94 static LVILatticeVal getRange(ConstantRange CR) {
96 Res.markConstantRange(CR);
100 bool isUndefined() const { return Tag == undefined; }
101 bool isConstant() const { return Tag == constant; }
102 bool isNotConstant() const { return Tag == notconstant; }
103 bool isConstantRange() const { return Tag == constantrange; }
104 bool isOverdefined() const { return Tag == overdefined; }
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
132 assert(V && "Marking constant with NULL");
133 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
134 return markConstantRange(ConstantRange(CI->getValue()));
135 if (isa<UndefValue>(V))
138 assert((!isConstant() || getConstant() == V) &&
139 "Marking constant with different value");
140 assert(isUndefined());
146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
148 assert(V && "Marking constant with NULL");
149 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
150 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
151 if (isa<UndefValue>(V))
154 assert((!isConstant() || getConstant() != V) &&
155 "Marking constant !constant with same value");
156 assert((!isNotConstant() || getNotConstant() == V) &&
157 "Marking !constant with different value");
158 assert(isUndefined() || isConstant());
164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
170 bool changed = Range == NewR;
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
198 if (RHS.isConstant()) {
201 return markOverdefined();
204 if (RHS.isNotConstant()) {
206 return markOverdefined();
208 // Unless we can prove that the two Constants are different, we must
209 // move to overdefined.
210 // FIXME: use TargetData for smarter constant folding.
211 if (ConstantInt *Res = dyn_cast<ConstantInt>(
212 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
214 RHS.getNotConstant())))
216 return markNotConstant(RHS.getNotConstant());
218 return markOverdefined();
221 // RHS is a ConstantRange, LHS is a non-integer Constant.
223 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
224 // a function. The correct result is to pick up RHS.
226 return markOverdefined();
229 if (isNotConstant()) {
230 if (RHS.isConstant()) {
232 return markOverdefined();
234 // Unless we can prove that the two Constants are different, we must
235 // move to overdefined.
236 // FIXME: use TargetData for smarter constant folding.
237 if (ConstantInt *Res = dyn_cast<ConstantInt>(
238 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
244 return markOverdefined();
247 if (RHS.isNotConstant()) {
250 return markOverdefined();
253 return markOverdefined();
256 assert(isConstantRange() && "New LVILattice type?");
257 if (!RHS.isConstantRange())
258 return markOverdefined();
260 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
261 if (NewR.isFullSet())
262 return markOverdefined();
263 return markConstantRange(NewR);
267 } // end anonymous namespace.
270 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
271 if (Val.isUndefined())
272 return OS << "undefined";
273 if (Val.isOverdefined())
274 return OS << "overdefined";
276 if (Val.isNotConstant())
277 return OS << "notconstant<" << *Val.getNotConstant() << '>';
278 else if (Val.isConstantRange())
279 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
280 << Val.getConstantRange().getUpper() << '>';
281 return OS << "constant<" << *Val.getConstant() << '>';
285 //===----------------------------------------------------------------------===//
286 // LazyValueInfoCache Decl
287 //===----------------------------------------------------------------------===//
290 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
291 /// maintains information about queries across the clients' queries.
292 class LazyValueInfoCache {
294 /// ValueCacheEntryTy - This is all of the cached block information for
295 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
296 /// entries, allowing us to do a lookup with a binary search.
297 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
300 /// LVIValueHandle - A callback value handle update the cache when
301 /// values are erased.
302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
309 void allUsesReplacedWith(Value *V) {
314 /// OverDefinedCacheUpdater - A helper object that ensures that the
315 /// OverDefinedCache is updated whenever solveBlockValue returns.
316 struct OverDefinedCacheUpdater {
317 LazyValueInfoCache *Parent;
322 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
323 LazyValueInfoCache *P)
324 : Parent(P), Val(V), BB(B), BBLV(LV) { }
326 bool markResult(bool changed) {
327 if (changed && BBLV.isOverdefined())
328 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
333 /// ValueCache - This is all of the cached information for all values,
334 /// mapped from Value* to key information.
335 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
337 /// OverDefinedCache - This tracks, on a per-block basis, the set of
338 /// values that are over-defined at the end of that block. This is required
339 /// for cache updating.
340 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
342 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
343 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
344 LVILatticeVal &Result);
345 bool hasBlockValue(Value *Val, BasicBlock *BB);
347 // These methods process one work item and may add more. A false value
348 // returned means that the work item was not completely processed and must
349 // be revisited after going through the new items.
350 bool solveBlockValue(Value *Val, BasicBlock *BB);
351 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
352 Value *Val, BasicBlock *BB);
353 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
354 PHINode *PN, BasicBlock *BB);
355 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
356 Instruction *BBI, BasicBlock *BB);
360 ValueCacheEntryTy &lookup(Value *V) {
361 return ValueCache[LVIValueHandle(V, this)];
364 std::stack<std::pair<BasicBlock*, Value*> > block_value_stack;
367 /// getValueInBlock - This is the query interface to determine the lattice
368 /// value for the specified Value* at the end of the specified block.
369 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
371 /// getValueOnEdge - This is the query interface to determine the lattice
372 /// value for the specified Value* that is true on the specified edge.
373 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
375 /// threadEdge - This is the update interface to inform the cache that an
376 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
378 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
380 /// eraseBlock - This is part of the update interface to inform the cache
381 /// that a block has been deleted.
382 void eraseBlock(BasicBlock *BB);
384 /// clear - Empty the cache.
387 OverDefinedCache.clear();
390 } // end anonymous namespace
392 void LazyValueInfoCache::LVIValueHandle::deleted() {
393 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
394 I = Parent->OverDefinedCache.begin(),
395 E = Parent->OverDefinedCache.end();
397 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
399 if (tmp->second == getValPtr())
400 Parent->OverDefinedCache.erase(tmp);
403 // This erasure deallocates *this, so it MUST happen after we're done
404 // using any and all members of *this.
405 Parent->ValueCache.erase(*this);
408 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
409 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
410 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
411 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
413 if (tmp->first == BB)
414 OverDefinedCache.erase(tmp);
417 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
418 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
422 void LazyValueInfoCache::solve() {
423 while (!block_value_stack.empty()) {
424 std::pair<BasicBlock*, Value*> &e = block_value_stack.top();
425 if (solveBlockValue(e.second, e.first))
426 block_value_stack.pop();
430 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
431 // If already a constant, there is nothing to compute.
432 if (isa<Constant>(Val))
435 return lookup(Val).count(BB);
438 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
439 // If already a constant, there is nothing to compute.
440 if (Constant *VC = dyn_cast<Constant>(Val))
441 return LVILatticeVal::get(VC);
443 return lookup(Val)[BB];
446 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
447 if (isa<Constant>(Val))
450 ValueCacheEntryTy &Cache = lookup(Val);
451 LVILatticeVal &BBLV = Cache[BB];
453 // OverDefinedCacheUpdater is a helper object that will update
454 // the OverDefinedCache for us when this method exits. Make sure to
455 // call markResult on it as we exist, passing a bool to indicate if the
456 // cache needs updating, i.e. if we have solve a new value or not.
457 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
459 // If we've already computed this block's value, return it.
460 if (!BBLV.isUndefined()) {
461 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
463 // Since we're reusing a cached value here, we don't need to update the
464 // OverDefinedCahce. The cache will have been properly updated
465 // whenever the cached value was inserted.
466 ODCacheUpdater.markResult(false);
470 // Otherwise, this is the first time we're seeing this block. Reset the
471 // lattice value to overdefined, so that cycles will terminate and be
472 // conservatively correct.
473 BBLV.markOverdefined();
475 Instruction *BBI = dyn_cast<Instruction>(Val);
476 if (BBI == 0 || BBI->getParent() != BB) {
477 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
480 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
481 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
484 // We can only analyze the definitions of certain classes of instructions
485 // (integral binops and casts at the moment), so bail if this isn't one.
486 LVILatticeVal Result;
487 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
488 !BBI->getType()->isIntegerTy()) {
489 DEBUG(dbgs() << " compute BB '" << BB->getName()
490 << "' - overdefined because inst def found.\n");
491 BBLV.markOverdefined();
492 return ODCacheUpdater.markResult(true);
495 // FIXME: We're currently limited to binops with a constant RHS. This should
497 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
498 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
499 DEBUG(dbgs() << " compute BB '" << BB->getName()
500 << "' - overdefined because inst def found.\n");
502 BBLV.markOverdefined();
503 return ODCacheUpdater.markResult(true);
506 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
509 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
510 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
511 return L->getPointerAddressSpace() == 0 &&
512 GetUnderlyingObject(L->getPointerOperand()) ==
513 GetUnderlyingObject(Ptr);
515 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
516 return S->getPointerAddressSpace() == 0 &&
517 GetUnderlyingObject(S->getPointerOperand()) ==
518 GetUnderlyingObject(Ptr);
520 // FIXME: llvm.memset, etc.
524 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
525 Value *Val, BasicBlock *BB) {
526 LVILatticeVal Result; // Start Undefined.
528 // If this is a pointer, and there's a load from that pointer in this BB,
529 // then we know that the pointer can't be NULL.
530 bool NotNull = false;
531 if (Val->getType()->isPointerTy()) {
532 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
533 if (InstructionDereferencesPointer(BI, Val)) {
540 // If this is the entry block, we must be asking about an argument. The
541 // value is overdefined.
542 if (BB == &BB->getParent()->getEntryBlock()) {
543 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
545 const PointerType *PTy = cast<PointerType>(Val->getType());
546 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
548 Result.markOverdefined();
554 // Loop over all of our predecessors, merging what we know from them into
556 bool EdgesMissing = false;
557 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
558 LVILatticeVal EdgeResult;
559 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
563 Result.mergeIn(EdgeResult);
565 // If we hit overdefined, exit early. The BlockVals entry is already set
567 if (Result.isOverdefined()) {
568 DEBUG(dbgs() << " compute BB '" << BB->getName()
569 << "' - overdefined because of pred.\n");
570 // If we previously determined that this is a pointer that can't be null
571 // then return that rather than giving up entirely.
573 const PointerType *PTy = cast<PointerType>(Val->getType());
574 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
584 // Return the merged value, which is more precise than 'overdefined'.
585 assert(!Result.isOverdefined());
590 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
591 PHINode *PN, BasicBlock *BB) {
592 LVILatticeVal Result; // Start Undefined.
594 // Loop over all of our predecessors, merging what we know from them into
596 bool EdgesMissing = false;
597 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
598 BasicBlock *PhiBB = PN->getIncomingBlock(i);
599 Value *PhiVal = PN->getIncomingValue(i);
600 LVILatticeVal EdgeResult;
601 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
605 Result.mergeIn(EdgeResult);
607 // If we hit overdefined, exit early. The BlockVals entry is already set
609 if (Result.isOverdefined()) {
610 DEBUG(dbgs() << " compute BB '" << BB->getName()
611 << "' - overdefined because of pred.\n");
620 // Return the merged value, which is more precise than 'overdefined'.
621 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
626 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
629 // Figure out the range of the LHS. If that fails, bail.
630 if (!hasBlockValue(BBI->getOperand(0), BB)) {
631 block_value_stack.push(std::make_pair(BB, BBI->getOperand(0)));
635 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
636 if (!LHSVal.isConstantRange()) {
637 BBLV.markOverdefined();
641 ConstantRange LHSRange = LHSVal.getConstantRange();
642 ConstantRange RHSRange(1);
643 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
644 if (isa<BinaryOperator>(BBI)) {
645 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
646 RHSRange = ConstantRange(RHS->getValue());
648 BBLV.markOverdefined();
653 // NOTE: We're currently limited by the set of operations that ConstantRange
654 // can evaluate symbolically. Enhancing that set will allows us to analyze
656 LVILatticeVal Result;
657 switch (BBI->getOpcode()) {
658 case Instruction::Add:
659 Result.markConstantRange(LHSRange.add(RHSRange));
661 case Instruction::Sub:
662 Result.markConstantRange(LHSRange.sub(RHSRange));
664 case Instruction::Mul:
665 Result.markConstantRange(LHSRange.multiply(RHSRange));
667 case Instruction::UDiv:
668 Result.markConstantRange(LHSRange.udiv(RHSRange));
670 case Instruction::Shl:
671 Result.markConstantRange(LHSRange.shl(RHSRange));
673 case Instruction::LShr:
674 Result.markConstantRange(LHSRange.lshr(RHSRange));
676 case Instruction::Trunc:
677 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
679 case Instruction::SExt:
680 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
682 case Instruction::ZExt:
683 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
685 case Instruction::BitCast:
686 Result.markConstantRange(LHSRange);
688 case Instruction::And:
689 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
691 case Instruction::Or:
692 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
695 // Unhandled instructions are overdefined.
697 DEBUG(dbgs() << " compute BB '" << BB->getName()
698 << "' - overdefined because inst def found.\n");
699 Result.markOverdefined();
707 /// getEdgeValue - This method attempts to infer more complex
708 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
709 BasicBlock *BBTo, LVILatticeVal &Result) {
710 // If already a constant, there is nothing to compute.
711 if (Constant *VC = dyn_cast<Constant>(Val)) {
712 Result = LVILatticeVal::get(VC);
716 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
718 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
719 // If this is a conditional branch and only one successor goes to BBTo, then
720 // we maybe able to infer something from the condition.
721 if (BI->isConditional() &&
722 BI->getSuccessor(0) != BI->getSuccessor(1)) {
723 bool isTrueDest = BI->getSuccessor(0) == BBTo;
724 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
725 "BBTo isn't a successor of BBFrom");
727 // If V is the condition of the branch itself, then we know exactly what
729 if (BI->getCondition() == Val) {
730 Result = LVILatticeVal::get(ConstantInt::get(
731 Type::getInt1Ty(Val->getContext()), isTrueDest));
735 // If the condition of the branch is an equality comparison, we may be
736 // able to infer the value.
737 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
738 if (ICI && ICI->getOperand(0) == Val &&
739 isa<Constant>(ICI->getOperand(1))) {
740 if (ICI->isEquality()) {
741 // We know that V has the RHS constant if this is a true SETEQ or
743 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
744 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
746 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
750 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
751 // Calculate the range of values that would satisfy the comparison.
752 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
753 ConstantRange TrueValues =
754 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
756 // If we're interested in the false dest, invert the condition.
757 if (!isTrueDest) TrueValues = TrueValues.inverse();
759 // Figure out the possible values of the query BEFORE this branch.
760 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
761 if (!InBlock.isConstantRange()) {
762 Result = LVILatticeVal::getRange(TrueValues);
766 // Find all potential values that satisfy both the input and output
768 ConstantRange PossibleValues =
769 TrueValues.intersectWith(InBlock.getConstantRange());
771 Result = LVILatticeVal::getRange(PossibleValues);
778 // If the edge was formed by a switch on the value, then we may know exactly
780 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
781 if (SI->getCondition() == Val) {
782 // We don't know anything in the default case.
783 if (SI->getDefaultDest() == BBTo) {
784 Result.markOverdefined();
788 // We only know something if there is exactly one value that goes from
790 unsigned NumEdges = 0;
791 ConstantInt *EdgeVal = 0;
792 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
793 if (SI->getSuccessor(i) != BBTo) continue;
794 if (NumEdges++) break;
795 EdgeVal = SI->getCaseValue(i);
797 assert(EdgeVal && "Missing successor?");
799 Result = LVILatticeVal::get(EdgeVal);
805 // Otherwise see if the value is known in the block.
806 if (hasBlockValue(Val, BBFrom)) {
807 Result = getBlockValue(Val, BBFrom);
810 block_value_stack.push(std::make_pair(BBFrom, Val));
814 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
815 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
816 << BB->getName() << "'\n");
818 block_value_stack.push(std::make_pair(BB, V));
820 LVILatticeVal Result = getBlockValue(V, BB);
822 DEBUG(dbgs() << " Result = " << Result << "\n");
826 LVILatticeVal LazyValueInfoCache::
827 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
828 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
829 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
831 LVILatticeVal Result;
832 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
834 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
836 assert(WasFastQuery && "More work to do after problem solved?");
839 DEBUG(dbgs() << " Result = " << Result << "\n");
843 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
844 BasicBlock *NewSucc) {
845 // When an edge in the graph has been threaded, values that we could not
846 // determine a value for before (i.e. were marked overdefined) may be possible
847 // to solve now. We do NOT try to proactively update these values. Instead,
848 // we clear their entries from the cache, and allow lazy updating to recompute
851 // The updating process is fairly simple: we need to dropped cached info
852 // for all values that were marked overdefined in OldSucc, and for those same
853 // values in any successor of OldSucc (except NewSucc) in which they were
854 // also marked overdefined.
855 std::vector<BasicBlock*> worklist;
856 worklist.push_back(OldSucc);
858 DenseSet<Value*> ClearSet;
859 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
860 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
861 if (I->first == OldSucc)
862 ClearSet.insert(I->second);
865 // Use a worklist to perform a depth-first search of OldSucc's successors.
866 // NOTE: We do not need a visited list since any blocks we have already
867 // visited will have had their overdefined markers cleared already, and we
868 // thus won't loop to their successors.
869 while (!worklist.empty()) {
870 BasicBlock *ToUpdate = worklist.back();
873 // Skip blocks only accessible through NewSucc.
874 if (ToUpdate == NewSucc) continue;
876 bool changed = false;
877 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
879 // If a value was marked overdefined in OldSucc, and is here too...
880 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
881 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
882 if (OI == OverDefinedCache.end()) continue;
884 // Remove it from the caches.
885 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
886 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
888 assert(CI != Entry.end() && "Couldn't find entry to update?");
890 OverDefinedCache.erase(OI);
892 // If we removed anything, then we potentially need to update
893 // blocks successors too.
897 if (!changed) continue;
899 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
903 //===----------------------------------------------------------------------===//
904 // LazyValueInfo Impl
905 //===----------------------------------------------------------------------===//
907 /// getCache - This lazily constructs the LazyValueInfoCache.
908 static LazyValueInfoCache &getCache(void *&PImpl) {
910 PImpl = new LazyValueInfoCache();
911 return *static_cast<LazyValueInfoCache*>(PImpl);
914 bool LazyValueInfo::runOnFunction(Function &F) {
916 getCache(PImpl).clear();
918 TD = getAnalysisIfAvailable<TargetData>();
923 void LazyValueInfo::releaseMemory() {
924 // If the cache was allocated, free it.
926 delete &getCache(PImpl);
931 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
932 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
934 if (Result.isConstant())
935 return Result.getConstant();
936 if (Result.isConstantRange()) {
937 ConstantRange CR = Result.getConstantRange();
938 if (const APInt *SingleVal = CR.getSingleElement())
939 return ConstantInt::get(V->getContext(), *SingleVal);
944 /// getConstantOnEdge - Determine whether the specified value is known to be a
945 /// constant on the specified edge. Return null if not.
946 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
948 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
950 if (Result.isConstant())
951 return Result.getConstant();
952 if (Result.isConstantRange()) {
953 ConstantRange CR = Result.getConstantRange();
954 if (const APInt *SingleVal = CR.getSingleElement())
955 return ConstantInt::get(V->getContext(), *SingleVal);
960 /// getPredicateOnEdge - Determine whether the specified value comparison
961 /// with a constant is known to be true or false on the specified CFG edge.
962 /// Pred is a CmpInst predicate.
963 LazyValueInfo::Tristate
964 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
965 BasicBlock *FromBB, BasicBlock *ToBB) {
966 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
968 // If we know the value is a constant, evaluate the conditional.
970 if (Result.isConstant()) {
971 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
972 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
973 return ResCI->isZero() ? False : True;
977 if (Result.isConstantRange()) {
978 ConstantInt *CI = dyn_cast<ConstantInt>(C);
979 if (!CI) return Unknown;
981 ConstantRange CR = Result.getConstantRange();
982 if (Pred == ICmpInst::ICMP_EQ) {
983 if (!CR.contains(CI->getValue()))
986 if (CR.isSingleElement() && CR.contains(CI->getValue()))
988 } else if (Pred == ICmpInst::ICMP_NE) {
989 if (!CR.contains(CI->getValue()))
992 if (CR.isSingleElement() && CR.contains(CI->getValue()))
996 // Handle more complex predicates.
997 ConstantRange TrueValues =
998 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
999 if (TrueValues.contains(CR))
1001 if (TrueValues.inverse().contains(CR))
1006 if (Result.isNotConstant()) {
1007 // If this is an equality comparison, we can try to fold it knowing that
1009 if (Pred == ICmpInst::ICMP_EQ) {
1010 // !C1 == C -> false iff C1 == C.
1011 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1012 Result.getNotConstant(), C, TD);
1013 if (Res->isNullValue())
1015 } else if (Pred == ICmpInst::ICMP_NE) {
1016 // !C1 != C -> true iff C1 == C.
1017 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1018 Result.getNotConstant(), C, TD);
1019 if (Res->isNullValue())
1028 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1029 BasicBlock *NewSucc) {
1030 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1033 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1034 if (PImpl) getCache(PImpl).eraseBlock(BB);