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/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/STLExtras.h"
31 char LazyValueInfo::ID = 0;
32 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
33 "Lazy Value Information Analysis", false, true);
36 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
47 /// FIXME: This is basically just for bringup, this can be made a lot more rich
53 /// undefined - This LLVM Value has no known value yet.
56 /// constant - This LLVM Value has a specific constant value.
58 /// notconstant - This LLVM value is known to not have the specified value.
64 /// overdefined - This instruction is not known to be constant, and we know
69 /// Val: This stores the current lattice value along with the Constant* for
70 /// the constant if this is a 'constant' or 'notconstant' value.
76 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
78 static LVILatticeVal get(Constant *C) {
80 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
81 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
82 else if (!isa<UndefValue>(C))
86 static LVILatticeVal getNot(Constant *C) {
88 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
89 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
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) {
133 assert(getConstant() == V && "Marking constant with different value");
137 assert(isUndefined());
139 assert(V && "Marking constant with NULL");
144 /// markNotConstant - Return true if this is a change in status.
145 bool markNotConstant(Constant *V) {
146 if (isNotConstant()) {
147 assert(getNotConstant() == V && "Marking !constant with different value");
152 assert(getConstant() != V && "Marking not constant with different value");
154 assert(isUndefined());
157 assert(V && "Marking constant with NULL");
162 /// markConstantRange - Return true if this is a change in status.
163 bool markConstantRange(const ConstantRange NewR) {
164 if (isConstantRange()) {
165 if (NewR.isEmptySet())
166 return markOverdefined();
168 bool changed = Range == NewR;
173 assert(isUndefined());
174 if (NewR.isEmptySet())
175 return markOverdefined();
176 else if (NewR.isFullSet()) {
186 /// mergeIn - Merge the specified lattice value into this one, updating this
187 /// one and returning true if anything changed.
188 bool mergeIn(const LVILatticeVal &RHS) {
189 if (RHS.isUndefined() || isOverdefined()) return false;
190 if (RHS.isOverdefined()) return markOverdefined();
192 if (RHS.isNotConstant()) {
193 if (isNotConstant()) {
194 if (getNotConstant() != RHS.getNotConstant() ||
195 isa<ConstantExpr>(getNotConstant()) ||
196 isa<ConstantExpr>(RHS.getNotConstant()))
197 return markOverdefined();
201 if (getConstant() == RHS.getNotConstant() ||
202 isa<ConstantExpr>(RHS.getNotConstant()) ||
203 isa<ConstantExpr>(getConstant()))
204 return markOverdefined();
205 return markNotConstant(RHS.getNotConstant());
208 assert(isUndefined() && "Unexpected lattice");
209 return markNotConstant(RHS.getNotConstant());
212 if (RHS.isConstantRange()) {
213 if (isConstantRange()) {
214 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
215 if (NewR.isFullSet())
216 return markOverdefined();
218 return markConstantRange(NewR);
219 } else if (!isUndefined()) {
220 return markOverdefined();
223 assert(isUndefined() && "Unexpected lattice");
224 return markConstantRange(RHS.getConstantRange());
227 // RHS must be a constant, we must be undef, constant, or notconstant.
228 assert(!isConstantRange() &&
229 "Constant and ConstantRange cannot be merged.");
232 return markConstant(RHS.getConstant());
235 if (getConstant() != RHS.getConstant())
236 return markOverdefined();
240 // If we are known "!=4" and RHS is "==5", stay at "!=4".
241 if (getNotConstant() == RHS.getConstant() ||
242 isa<ConstantExpr>(getNotConstant()) ||
243 isa<ConstantExpr>(RHS.getConstant()))
244 return markOverdefined();
250 } // end anonymous namespace.
253 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
254 if (Val.isUndefined())
255 return OS << "undefined";
256 if (Val.isOverdefined())
257 return OS << "overdefined";
259 if (Val.isNotConstant())
260 return OS << "notconstant<" << *Val.getNotConstant() << '>';
261 else if (Val.isConstantRange())
262 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
263 << Val.getConstantRange().getUpper() << '>';
264 return OS << "constant<" << *Val.getConstant() << '>';
268 //===----------------------------------------------------------------------===//
269 // LazyValueInfoCache Decl
270 //===----------------------------------------------------------------------===//
273 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
274 /// maintains information about queries across the clients' queries.
275 class LazyValueInfoCache {
277 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
278 /// specified basic block for a Value* that depends on context.
279 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
281 /// ValueCacheEntryTy - This is all of the cached block information for
282 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
283 /// entries, allowing us to do a lookup with a binary search.
284 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
287 /// LVIValueHandle - A callback value handle update the cache when
288 /// values are erased.
289 struct LVIValueHandle : public CallbackVH {
290 LazyValueInfoCache *Parent;
292 LVIValueHandle(Value *V, LazyValueInfoCache *P)
293 : CallbackVH(V), Parent(P) { }
296 void allUsesReplacedWith(Value* V) {
300 LVIValueHandle &operator=(Value *V) {
301 return *this = LVIValueHandle(V, Parent);
305 /// ValueCache - This is all of the cached information for all values,
306 /// mapped from Value* to key information.
307 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
309 /// OverDefinedCache - This tracks, on a per-block basis, the set of
310 /// values that are over-defined at the end of that block. This is required
311 /// for cache updating.
312 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
316 /// getValueInBlock - This is the query interface to determine the lattice
317 /// value for the specified Value* at the end of the specified block.
318 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
320 /// getValueOnEdge - This is the query interface to determine the lattice
321 /// value for the specified Value* that is true on the specified edge.
322 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
324 /// threadEdge - This is the update interface to inform the cache that an
325 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
327 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
329 /// eraseBlock - This is part of the update interface to inform the cache
330 /// that a block has been deleted.
331 void eraseBlock(BasicBlock *BB);
333 /// clear - Empty the cache.
336 OverDefinedCache.clear();
339 } // end anonymous namespace
341 //===----------------------------------------------------------------------===//
343 //===----------------------------------------------------------------------===//
346 /// LVIQuery - This is a transient object that exists while a query is
349 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
350 /// reallocation of the densemap on every query.
352 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
353 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
355 /// This is the current value being queried for.
358 /// This is a pointer to the owning cache, for recursive queries.
359 LazyValueInfoCache &Parent;
361 /// This is all of the cached information about this value.
362 ValueCacheEntryTy &Cache;
364 /// This tracks, for each block, what values are overdefined.
365 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
367 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
368 /// added to cache but that are not in sorted order.
369 DenseSet<BasicBlock*> NewBlockInfo;
372 LVIQuery(Value *V, LazyValueInfoCache &P,
373 ValueCacheEntryTy &VC,
374 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
375 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
379 // When the query is done, insert the newly discovered facts into the
380 // cache in sorted order.
381 if (NewBlockInfo.empty()) return;
383 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
384 E = NewBlockInfo.end(); I != E; ++I) {
385 if (Cache[*I].isOverdefined())
386 OverDefinedCache.insert(std::make_pair(*I, Val));
390 LVILatticeVal getBlockValue(BasicBlock *BB);
391 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
394 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
396 } // end anonymous namespace
398 void LazyValueInfoCache::LVIValueHandle::deleted() {
399 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
400 I = Parent->OverDefinedCache.begin(),
401 E = Parent->OverDefinedCache.end();
403 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
405 if (tmp->second == getValPtr())
406 Parent->OverDefinedCache.erase(tmp);
409 // This erasure deallocates *this, so it MUST happen after we're done
410 // using any and all members of *this.
411 Parent->ValueCache.erase(*this);
414 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
415 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
416 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
417 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
419 if (tmp->first == BB)
420 OverDefinedCache.erase(tmp);
423 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
424 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
428 /// getCachedEntryForBlock - See if we already have a value for this block. If
429 /// so, return it, otherwise create a new entry in the Cache map to use.
430 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
431 NewBlockInfo.insert(BB);
435 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
436 // See if we already have a value for this block.
437 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
439 // If we've already computed this block's value, return it.
440 if (!BBLV.isUndefined()) {
441 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
445 // Otherwise, this is the first time we're seeing this block. Reset the
446 // lattice value to overdefined, so that cycles will terminate and be
447 // conservatively correct.
448 BBLV.markOverdefined();
451 // If V is live into BB, see if our predecessors know anything about it.
452 Instruction *BBI = dyn_cast<Instruction>(Val);
453 if (BBI == 0 || BBI->getParent() != BB) {
454 LVILatticeVal Result; // Start Undefined.
455 unsigned NumPreds = 0;
457 // Loop over all of our predecessors, merging what we know from them into
459 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
460 Result.mergeIn(getEdgeValue(*PI, BB));
462 // If we hit overdefined, exit early. The BlockVals entry is already set
464 if (Result.isOverdefined()) {
465 DEBUG(dbgs() << " compute BB '" << BB->getName()
466 << "' - overdefined because of pred.\n");
472 // If this is the entry block, we must be asking about an argument. The
473 // value is overdefined.
474 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
475 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
476 Result.markOverdefined();
480 // Return the merged value, which is more precise than 'overdefined'.
481 assert(!Result.isOverdefined());
482 return Cache[BB] = Result;
485 // If this value is defined by an instruction in this block, we have to
486 // process it here somehow or return overdefined.
487 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
488 LVILatticeVal Result; // Start Undefined.
490 // Loop over all of our predecessors, merging what we know from them into
492 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
493 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
494 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
496 // If we hit overdefined, exit early. The BlockVals entry is already set
498 if (Result.isOverdefined()) {
499 DEBUG(dbgs() << " compute BB '" << BB->getName()
500 << "' - overdefined because of pred.\n");
505 // Return the merged value, which is more precise than 'overdefined'.
506 assert(!Result.isOverdefined());
507 return Cache[BB] = Result;
510 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
512 // We can only analyze the definitions of certain classes of instructions
513 // (integral binops and casts at the moment), so bail if this isn't one.
514 LVILatticeVal Result;
515 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
516 !BBI->getType()->isIntegerTy()) {
517 DEBUG(dbgs() << " compute BB '" << BB->getName()
518 << "' - overdefined because inst def found.\n");
519 Result.markOverdefined();
523 // FIXME: We're currently limited to binops with a constant RHS. This should
525 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
526 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
527 DEBUG(dbgs() << " compute BB '" << BB->getName()
528 << "' - overdefined because inst def found.\n");
530 Result.markOverdefined();
534 // Figure out the range of the LHS. If that fails, bail.
535 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
536 if (!LHSVal.isConstantRange()) {
537 Result.markOverdefined();
541 ConstantInt *RHS = 0;
542 ConstantRange LHSRange = LHSVal.getConstantRange();
543 ConstantRange RHSRange(1);
544 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
545 if (isa<BinaryOperator>(BBI)) {
546 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
548 Result.markOverdefined();
552 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
555 // NOTE: We're currently limited by the set of operations that ConstantRange
556 // can evaluate symbolically. Enhancing that set will allows us to analyze
558 switch (BBI->getOpcode()) {
559 case Instruction::Add:
560 Result.markConstantRange(LHSRange.add(RHSRange));
562 case Instruction::Sub:
563 Result.markConstantRange(LHSRange.sub(RHSRange));
565 case Instruction::Mul:
566 Result.markConstantRange(LHSRange.multiply(RHSRange));
568 case Instruction::UDiv:
569 Result.markConstantRange(LHSRange.udiv(RHSRange));
571 case Instruction::Shl:
572 Result.markConstantRange(LHSRange.shl(RHSRange));
574 case Instruction::LShr:
575 Result.markConstantRange(LHSRange.lshr(RHSRange));
577 case Instruction::Trunc:
578 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
580 case Instruction::SExt:
581 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
583 case Instruction::ZExt:
584 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
586 case Instruction::BitCast:
587 Result.markConstantRange(LHSRange);
590 // Unhandled instructions are overdefined.
592 DEBUG(dbgs() << " compute BB '" << BB->getName()
593 << "' - overdefined because inst def found.\n");
594 Result.markOverdefined();
598 return Cache[BB] = Result;
602 /// getEdgeValue - This method attempts to infer more complex
603 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
604 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
606 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
607 // If this is a conditional branch and only one successor goes to BBTo, then
608 // we maybe able to infer something from the condition.
609 if (BI->isConditional() &&
610 BI->getSuccessor(0) != BI->getSuccessor(1)) {
611 bool isTrueDest = BI->getSuccessor(0) == BBTo;
612 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
613 "BBTo isn't a successor of BBFrom");
615 // If V is the condition of the branch itself, then we know exactly what
617 if (BI->getCondition() == Val)
618 return LVILatticeVal::get(ConstantInt::get(
619 Type::getInt1Ty(Val->getContext()), isTrueDest));
621 // If the condition of the branch is an equality comparison, we may be
622 // able to infer the value.
623 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
624 if (ICI && ICI->getOperand(0) == Val &&
625 isa<Constant>(ICI->getOperand(1))) {
626 if (ICI->isEquality()) {
627 // We know that V has the RHS constant if this is a true SETEQ or
629 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
630 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
631 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
634 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
635 // Calculate the range of values that would satisfy the comparison.
636 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
637 ConstantRange TrueValues =
638 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
640 // If we're interested in the false dest, invert the condition.
641 if (!isTrueDest) TrueValues = TrueValues.inverse();
643 // Figure out the possible values of the query BEFORE this branch.
644 LVILatticeVal InBlock = getBlockValue(BBFrom);
645 if (!InBlock.isConstantRange()) return InBlock;
647 // Find all potential values that satisfy both the input and output
649 ConstantRange PossibleValues =
650 TrueValues.intersectWith(InBlock.getConstantRange());
652 return LVILatticeVal::getRange(PossibleValues);
658 // If the edge was formed by a switch on the value, then we may know exactly
660 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
661 // If BBTo is the default destination of the switch, we don't know anything.
662 // Given a more powerful range analysis we could know stuff.
663 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
664 // We only know something if there is exactly one value that goes from
666 unsigned NumEdges = 0;
667 ConstantInt *EdgeVal = 0;
668 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
669 if (SI->getSuccessor(i) != BBTo) continue;
670 if (NumEdges++) break;
671 EdgeVal = SI->getCaseValue(i);
673 assert(EdgeVal && "Missing successor?");
675 return LVILatticeVal::get(EdgeVal);
679 // Otherwise see if the value is known in the block.
680 return getBlockValue(BBFrom);
684 //===----------------------------------------------------------------------===//
685 // LazyValueInfoCache Impl
686 //===----------------------------------------------------------------------===//
688 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
689 // If already a constant, there is nothing to compute.
690 if (Constant *VC = dyn_cast<Constant>(V))
691 return LVILatticeVal::get(VC);
693 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
694 << BB->getName() << "'\n");
696 LVILatticeVal Result = LVIQuery(V, *this,
697 ValueCache[LVIValueHandle(V, this)],
698 OverDefinedCache).getBlockValue(BB);
700 DEBUG(dbgs() << " Result = " << Result << "\n");
704 LVILatticeVal LazyValueInfoCache::
705 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
706 // If already a constant, there is nothing to compute.
707 if (Constant *VC = dyn_cast<Constant>(V))
708 return LVILatticeVal::get(VC);
710 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
711 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
713 LVILatticeVal Result =
714 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
715 OverDefinedCache).getEdgeValue(FromBB, ToBB);
717 DEBUG(dbgs() << " Result = " << Result << "\n");
722 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
723 BasicBlock *NewSucc) {
724 // When an edge in the graph has been threaded, values that we could not
725 // determine a value for before (i.e. were marked overdefined) may be possible
726 // to solve now. We do NOT try to proactively update these values. Instead,
727 // we clear their entries from the cache, and allow lazy updating to recompute
730 // The updating process is fairly simple: we need to dropped cached info
731 // for all values that were marked overdefined in OldSucc, and for those same
732 // values in any successor of OldSucc (except NewSucc) in which they were
733 // also marked overdefined.
734 std::vector<BasicBlock*> worklist;
735 worklist.push_back(OldSucc);
737 DenseSet<Value*> ClearSet;
738 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
739 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
740 if (I->first == OldSucc)
741 ClearSet.insert(I->second);
744 // Use a worklist to perform a depth-first search of OldSucc's successors.
745 // NOTE: We do not need a visited list since any blocks we have already
746 // visited will have had their overdefined markers cleared already, and we
747 // thus won't loop to their successors.
748 while (!worklist.empty()) {
749 BasicBlock *ToUpdate = worklist.back();
752 // Skip blocks only accessible through NewSucc.
753 if (ToUpdate == NewSucc) continue;
755 bool changed = false;
756 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
758 // If a value was marked overdefined in OldSucc, and is here too...
759 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
760 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
761 if (OI == OverDefinedCache.end()) continue;
763 // Remove it from the caches.
764 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
765 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
767 assert(CI != Entry.end() && "Couldn't find entry to update?");
769 OverDefinedCache.erase(OI);
771 // If we removed anything, then we potentially need to update
772 // blocks successors too.
776 if (!changed) continue;
778 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
782 //===----------------------------------------------------------------------===//
783 // LazyValueInfo Impl
784 //===----------------------------------------------------------------------===//
786 /// getCache - This lazily constructs the LazyValueInfoCache.
787 static LazyValueInfoCache &getCache(void *&PImpl) {
789 PImpl = new LazyValueInfoCache();
790 return *static_cast<LazyValueInfoCache*>(PImpl);
793 bool LazyValueInfo::runOnFunction(Function &F) {
795 getCache(PImpl).clear();
797 TD = getAnalysisIfAvailable<TargetData>();
802 void LazyValueInfo::releaseMemory() {
803 // If the cache was allocated, free it.
805 delete &getCache(PImpl);
810 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
811 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
813 if (Result.isConstant())
814 return Result.getConstant();
818 /// getConstantOnEdge - Determine whether the specified value is known to be a
819 /// constant on the specified edge. Return null if not.
820 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
822 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
824 if (Result.isConstant())
825 return Result.getConstant();
826 else if (Result.isConstantRange()) {
827 ConstantRange CR = Result.getConstantRange();
828 if (const APInt *SingleVal = CR.getSingleElement())
829 return ConstantInt::get(V->getContext(), *SingleVal);
834 /// getPredicateOnEdge - Determine whether the specified value comparison
835 /// with a constant is known to be true or false on the specified CFG edge.
836 /// Pred is a CmpInst predicate.
837 LazyValueInfo::Tristate
838 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
839 BasicBlock *FromBB, BasicBlock *ToBB) {
840 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
842 // If we know the value is a constant, evaluate the conditional.
844 if (Result.isConstant()) {
845 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
846 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
847 return ResCI->isZero() ? False : True;
851 if (Result.isConstantRange()) {
852 ConstantInt *CI = dyn_cast<ConstantInt>(C);
853 if (!CI) return Unknown;
855 ConstantRange CR = Result.getConstantRange();
856 if (Pred == ICmpInst::ICMP_EQ) {
857 if (!CR.contains(CI->getValue()))
860 if (CR.isSingleElement() && CR.contains(CI->getValue()))
862 } else if (Pred == ICmpInst::ICMP_NE) {
863 if (!CR.contains(CI->getValue()))
866 if (CR.isSingleElement() && CR.contains(CI->getValue()))
870 // Handle more complex predicates.
871 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
872 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
873 if (CR.intersectWith(TrueValues).isEmptySet())
875 else if (TrueValues.contains(CR))
881 if (Result.isNotConstant()) {
882 // If this is an equality comparison, we can try to fold it knowing that
884 if (Pred == ICmpInst::ICMP_EQ) {
885 // !C1 == C -> false iff C1 == C.
886 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
887 Result.getNotConstant(), C, TD);
888 if (Res->isNullValue())
890 } else if (Pred == ICmpInst::ICMP_NE) {
891 // !C1 != C -> true iff C1 == C.
892 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
893 Result.getNotConstant(), C, TD);
894 if (Res->isNullValue())
903 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
904 BasicBlock* NewSucc) {
905 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
908 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
909 if (PImpl) getCache(PImpl).eraseBlock(BB);