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"
33 char LazyValueInfo::ID = 0;
34 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
35 "Lazy Value Information Analysis", false, true);
38 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
49 /// FIXME: This is basically just for bringup, this can be made a lot more rich
55 /// undefined - This LLVM Value has no known value yet.
58 /// constant - This LLVM Value has a specific constant value.
60 /// notconstant - This LLVM value is known to not have the specified value.
66 /// overdefined - This instruction is not known to be constant, and we know
71 /// Val: This stores the current lattice value along with the Constant* for
72 /// the constant if this is a 'constant' or 'notconstant' value.
78 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
80 static LVILatticeVal get(Constant *C) {
82 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
83 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
84 else if (!isa<UndefValue>(C))
88 static LVILatticeVal getNot(Constant *C) {
90 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
91 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
93 Res.markNotConstant(C);
96 static LVILatticeVal getRange(ConstantRange CR) {
98 Res.markConstantRange(CR);
102 bool isUndefined() const { return Tag == undefined; }
103 bool isConstant() const { return Tag == constant; }
104 bool isNotConstant() const { return Tag == notconstant; }
105 bool isConstantRange() const { return Tag == constantrange; }
106 bool isOverdefined() const { return Tag == overdefined; }
108 Constant *getConstant() const {
109 assert(isConstant() && "Cannot get the constant of a non-constant!");
113 Constant *getNotConstant() const {
114 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
118 ConstantRange getConstantRange() const {
119 assert(isConstantRange() &&
120 "Cannot get the constant-range of a non-constant-range!");
124 /// markOverdefined - Return true if this is a change in status.
125 bool markOverdefined() {
132 /// markConstant - Return true if this is a change in status.
133 bool markConstant(Constant *V) {
135 assert(getConstant() == V && "Marking constant with different value");
139 assert(isUndefined());
141 assert(V && "Marking constant with NULL");
146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
148 if (isNotConstant()) {
149 assert(getNotConstant() == V && "Marking !constant with different value");
154 assert(getConstant() != V && "Marking not constant with different value");
156 assert(isUndefined());
159 assert(V && "Marking constant with NULL");
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();
190 if (RHS.isNotConstant()) {
191 if (isNotConstant()) {
192 if (getNotConstant() != RHS.getNotConstant() ||
193 isa<ConstantExpr>(getNotConstant()) ||
194 isa<ConstantExpr>(RHS.getNotConstant()))
195 return markOverdefined();
197 } else if (isConstant()) {
198 if (getConstant() == RHS.getNotConstant() ||
199 isa<ConstantExpr>(RHS.getNotConstant()) ||
200 isa<ConstantExpr>(getConstant()))
201 return markOverdefined();
202 return markNotConstant(RHS.getNotConstant());
203 } else if (isConstantRange()) {
204 return markOverdefined();
207 assert(isUndefined() && "Unexpected lattice");
208 return markNotConstant(RHS.getNotConstant());
211 if (RHS.isConstantRange()) {
212 if (isConstantRange()) {
213 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
214 if (NewR.isFullSet())
215 return markOverdefined();
217 return markConstantRange(NewR);
218 } else if (!isUndefined()) {
219 return markOverdefined();
222 assert(isUndefined() && "Unexpected lattice");
223 return markConstantRange(RHS.getConstantRange());
226 // RHS must be a constant, we must be undef, constant, or notconstant.
227 assert(!isConstantRange() &&
228 "Constant and ConstantRange cannot be merged.");
231 return markConstant(RHS.getConstant());
234 if (getConstant() != RHS.getConstant())
235 return markOverdefined();
239 // If we are known "!=4" and RHS is "==5", stay at "!=4".
240 if (getNotConstant() == RHS.getConstant() ||
241 isa<ConstantExpr>(getNotConstant()) ||
242 isa<ConstantExpr>(RHS.getConstant()))
243 return markOverdefined();
249 } // end anonymous namespace.
252 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
253 if (Val.isUndefined())
254 return OS << "undefined";
255 if (Val.isOverdefined())
256 return OS << "overdefined";
258 if (Val.isNotConstant())
259 return OS << "notconstant<" << *Val.getNotConstant() << '>';
260 else if (Val.isConstantRange())
261 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
262 << Val.getConstantRange().getUpper() << '>';
263 return OS << "constant<" << *Val.getConstant() << '>';
267 //===----------------------------------------------------------------------===//
268 // LazyValueInfoCache Decl
269 //===----------------------------------------------------------------------===//
272 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
273 /// maintains information about queries across the clients' queries.
274 class LazyValueInfoCache {
276 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
277 /// specified basic block for a Value* that depends on context.
278 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
280 /// ValueCacheEntryTy - This is all of the cached block information for
281 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
282 /// entries, allowing us to do a lookup with a binary search.
283 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
286 /// LVIValueHandle - A callback value handle update the cache when
287 /// values are erased.
288 struct LVIValueHandle : public CallbackVH {
289 LazyValueInfoCache *Parent;
291 LVIValueHandle(Value *V, LazyValueInfoCache *P)
292 : CallbackVH(V), Parent(P) { }
295 void allUsesReplacedWith(Value* V) {
300 /// ValueCache - This is all of the cached information for all values,
301 /// mapped from Value* to key information.
302 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
304 /// OverDefinedCache - This tracks, on a per-block basis, the set of
305 /// values that are over-defined at the end of that block. This is required
306 /// for cache updating.
307 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
311 /// getValueInBlock - This is the query interface to determine the lattice
312 /// value for the specified Value* at the end of the specified block.
313 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
315 /// getValueOnEdge - This is the query interface to determine the lattice
316 /// value for the specified Value* that is true on the specified edge.
317 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
319 /// threadEdge - This is the update interface to inform the cache that an
320 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
322 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
324 /// eraseBlock - This is part of the update interface to inform the cache
325 /// that a block has been deleted.
326 void eraseBlock(BasicBlock *BB);
328 /// clear - Empty the cache.
331 OverDefinedCache.clear();
334 } // end anonymous namespace
336 //===----------------------------------------------------------------------===//
338 //===----------------------------------------------------------------------===//
341 /// LVIQuery - This is a transient object that exists while a query is
344 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
345 /// reallocation of the densemap on every query.
347 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
348 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
350 /// This is the current value being queried for.
353 /// This is a pointer to the owning cache, for recursive queries.
354 LazyValueInfoCache &Parent;
356 /// This is all of the cached information about this value.
357 ValueCacheEntryTy &Cache;
359 /// This tracks, for each block, what values are overdefined.
360 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
362 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
363 /// added to cache but that are not in sorted order.
364 DenseSet<BasicBlock*> NewBlockInfo;
368 LVIQuery(Value *V, LazyValueInfoCache &P,
369 ValueCacheEntryTy &VC,
370 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
371 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
375 // When the query is done, insert the newly discovered facts into the
376 // cache in sorted order.
377 if (NewBlockInfo.empty()) return;
379 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
380 E = NewBlockInfo.end(); I != E; ++I) {
381 if (Cache[*I].isOverdefined())
382 OverDefinedCache.insert(std::make_pair(*I, Val));
386 LVILatticeVal getBlockValue(BasicBlock *BB);
387 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
390 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
392 } // end anonymous namespace
394 void LazyValueInfoCache::LVIValueHandle::deleted() {
395 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
396 I = Parent->OverDefinedCache.begin(),
397 E = Parent->OverDefinedCache.end();
399 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
401 if (tmp->second == getValPtr())
402 Parent->OverDefinedCache.erase(tmp);
405 // This erasure deallocates *this, so it MUST happen after we're done
406 // using any and all members of *this.
407 Parent->ValueCache.erase(*this);
410 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
411 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
412 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
413 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
415 if (tmp->first == BB)
416 OverDefinedCache.erase(tmp);
419 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
420 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
424 /// getCachedEntryForBlock - See if we already have a value for this block. If
425 /// so, return it, otherwise create a new entry in the Cache map to use.
426 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
427 NewBlockInfo.insert(BB);
431 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
432 // See if we already have a value for this block.
433 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
435 // If we've already computed this block's value, return it.
436 if (!BBLV.isUndefined()) {
437 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
441 // Otherwise, this is the first time we're seeing this block. Reset the
442 // lattice value to overdefined, so that cycles will terminate and be
443 // conservatively correct.
444 BBLV.markOverdefined();
447 Instruction *BBI = dyn_cast<Instruction>(Val);
448 if (BBI == 0 || BBI->getParent() != BB) {
449 LVILatticeVal Result; // Start Undefined.
451 // If this is a pointer, and there's a load from that pointer in this BB,
452 // then we know that the pointer can't be NULL.
453 bool NotNull = false;
454 if (Val->getType()->isPointerTy()) {
455 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
456 LoadInst *L = dyn_cast<LoadInst>(BI);
457 if (L && L->getPointerAddressSpace() == 0 &&
458 L->getPointerOperand()->getUnderlyingObject() ==
459 Val->getUnderlyingObject()) {
466 unsigned NumPreds = 0;
467 // Loop over all of our predecessors, merging what we know from them into
469 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
470 Result.mergeIn(getEdgeValue(*PI, BB));
472 // If we hit overdefined, exit early. The BlockVals entry is already set
474 if (Result.isOverdefined()) {
475 DEBUG(dbgs() << " compute BB '" << BB->getName()
476 << "' - overdefined because of pred.\n");
477 // If we previously determined that this is a pointer that can't be null
478 // then return that rather than giving up entirely.
480 const PointerType *PTy = cast<PointerType>(Val->getType());
481 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
490 // If this is the entry block, we must be asking about an argument. The
491 // value is overdefined.
492 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
493 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
494 Result.markOverdefined();
498 // Return the merged value, which is more precise than 'overdefined'.
499 assert(!Result.isOverdefined());
500 return Cache[BB] = Result;
503 // If this value is defined by an instruction in this block, we have to
504 // process it here somehow or return overdefined.
505 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
506 LVILatticeVal Result; // Start Undefined.
508 // Loop over all of our predecessors, merging what we know from them into
510 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
511 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
512 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
514 // If we hit overdefined, exit early. The BlockVals entry is already set
516 if (Result.isOverdefined()) {
517 DEBUG(dbgs() << " compute BB '" << BB->getName()
518 << "' - overdefined because of pred.\n");
523 // Return the merged value, which is more precise than 'overdefined'.
524 assert(!Result.isOverdefined());
525 return Cache[BB] = Result;
528 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
530 // We can only analyze the definitions of certain classes of instructions
531 // (integral binops and casts at the moment), so bail if this isn't one.
532 LVILatticeVal Result;
533 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
534 !BBI->getType()->isIntegerTy()) {
535 DEBUG(dbgs() << " compute BB '" << BB->getName()
536 << "' - overdefined because inst def found.\n");
537 Result.markOverdefined();
541 // FIXME: We're currently limited to binops with a constant RHS. This should
543 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
544 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
545 DEBUG(dbgs() << " compute BB '" << BB->getName()
546 << "' - overdefined because inst def found.\n");
548 Result.markOverdefined();
552 // Figure out the range of the LHS. If that fails, bail.
553 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
554 if (!LHSVal.isConstantRange()) {
555 Result.markOverdefined();
559 ConstantInt *RHS = 0;
560 ConstantRange LHSRange = LHSVal.getConstantRange();
561 ConstantRange RHSRange(1);
562 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
563 if (isa<BinaryOperator>(BBI)) {
564 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
566 Result.markOverdefined();
570 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
573 // NOTE: We're currently limited by the set of operations that ConstantRange
574 // can evaluate symbolically. Enhancing that set will allows us to analyze
576 switch (BBI->getOpcode()) {
577 case Instruction::Add:
578 Result.markConstantRange(LHSRange.add(RHSRange));
580 case Instruction::Sub:
581 Result.markConstantRange(LHSRange.sub(RHSRange));
583 case Instruction::Mul:
584 Result.markConstantRange(LHSRange.multiply(RHSRange));
586 case Instruction::UDiv:
587 Result.markConstantRange(LHSRange.udiv(RHSRange));
589 case Instruction::Shl:
590 Result.markConstantRange(LHSRange.shl(RHSRange));
592 case Instruction::LShr:
593 Result.markConstantRange(LHSRange.lshr(RHSRange));
595 case Instruction::Trunc:
596 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
598 case Instruction::SExt:
599 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
601 case Instruction::ZExt:
602 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
604 case Instruction::BitCast:
605 Result.markConstantRange(LHSRange);
607 case Instruction::And:
608 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
610 case Instruction::Or:
611 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
614 // Unhandled instructions are overdefined.
616 DEBUG(dbgs() << " compute BB '" << BB->getName()
617 << "' - overdefined because inst def found.\n");
618 Result.markOverdefined();
622 return Cache[BB] = Result;
626 /// getEdgeValue - This method attempts to infer more complex
627 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
628 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
630 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
631 // If this is a conditional branch and only one successor goes to BBTo, then
632 // we maybe able to infer something from the condition.
633 if (BI->isConditional() &&
634 BI->getSuccessor(0) != BI->getSuccessor(1)) {
635 bool isTrueDest = BI->getSuccessor(0) == BBTo;
636 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
637 "BBTo isn't a successor of BBFrom");
639 // If V is the condition of the branch itself, then we know exactly what
641 if (BI->getCondition() == Val)
642 return LVILatticeVal::get(ConstantInt::get(
643 Type::getInt1Ty(Val->getContext()), isTrueDest));
645 // If the condition of the branch is an equality comparison, we may be
646 // able to infer the value.
647 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
648 if (ICI && ICI->getOperand(0) == Val &&
649 isa<Constant>(ICI->getOperand(1))) {
650 if (ICI->isEquality()) {
651 // We know that V has the RHS constant if this is a true SETEQ or
653 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
654 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
655 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
658 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
659 // Calculate the range of values that would satisfy the comparison.
660 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
661 ConstantRange TrueValues =
662 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
664 // If we're interested in the false dest, invert the condition.
665 if (!isTrueDest) TrueValues = TrueValues.inverse();
667 // Figure out the possible values of the query BEFORE this branch.
668 LVILatticeVal InBlock = getBlockValue(BBFrom);
669 if (!InBlock.isConstantRange())
670 return LVILatticeVal::getRange(TrueValues);
672 // Find all potential values that satisfy both the input and output
674 ConstantRange PossibleValues =
675 TrueValues.intersectWith(InBlock.getConstantRange());
677 return LVILatticeVal::getRange(PossibleValues);
683 // If the edge was formed by a switch on the value, then we may know exactly
685 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
686 if (SI->getCondition() == Val) {
687 // We don't know anything in the default case.
688 if (SI->getDefaultDest() == BBTo) {
689 LVILatticeVal Result;
690 Result.markOverdefined();
694 // We only know something if there is exactly one value that goes from
696 unsigned NumEdges = 0;
697 ConstantInt *EdgeVal = 0;
698 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
699 if (SI->getSuccessor(i) != BBTo) continue;
700 if (NumEdges++) break;
701 EdgeVal = SI->getCaseValue(i);
703 assert(EdgeVal && "Missing successor?");
705 return LVILatticeVal::get(EdgeVal);
709 // Otherwise see if the value is known in the block.
710 return getBlockValue(BBFrom);
714 //===----------------------------------------------------------------------===//
715 // LazyValueInfoCache Impl
716 //===----------------------------------------------------------------------===//
718 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
719 // If already a constant, there is nothing to compute.
720 if (Constant *VC = dyn_cast<Constant>(V))
721 return LVILatticeVal::get(VC);
723 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
724 << BB->getName() << "'\n");
726 LVILatticeVal Result = LVIQuery(V, *this,
727 ValueCache[LVIValueHandle(V, this)],
728 OverDefinedCache).getBlockValue(BB);
730 DEBUG(dbgs() << " Result = " << Result << "\n");
734 LVILatticeVal LazyValueInfoCache::
735 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
736 // If already a constant, there is nothing to compute.
737 if (Constant *VC = dyn_cast<Constant>(V))
738 return LVILatticeVal::get(VC);
740 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
741 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
743 LVILatticeVal Result =
744 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
745 OverDefinedCache).getEdgeValue(FromBB, ToBB);
747 DEBUG(dbgs() << " Result = " << Result << "\n");
752 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
753 BasicBlock *NewSucc) {
754 // When an edge in the graph has been threaded, values that we could not
755 // determine a value for before (i.e. were marked overdefined) may be possible
756 // to solve now. We do NOT try to proactively update these values. Instead,
757 // we clear their entries from the cache, and allow lazy updating to recompute
760 // The updating process is fairly simple: we need to dropped cached info
761 // for all values that were marked overdefined in OldSucc, and for those same
762 // values in any successor of OldSucc (except NewSucc) in which they were
763 // also marked overdefined.
764 std::vector<BasicBlock*> worklist;
765 worklist.push_back(OldSucc);
767 DenseSet<Value*> ClearSet;
768 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
769 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
770 if (I->first == OldSucc)
771 ClearSet.insert(I->second);
774 // Use a worklist to perform a depth-first search of OldSucc's successors.
775 // NOTE: We do not need a visited list since any blocks we have already
776 // visited will have had their overdefined markers cleared already, and we
777 // thus won't loop to their successors.
778 while (!worklist.empty()) {
779 BasicBlock *ToUpdate = worklist.back();
782 // Skip blocks only accessible through NewSucc.
783 if (ToUpdate == NewSucc) continue;
785 bool changed = false;
786 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
788 // If a value was marked overdefined in OldSucc, and is here too...
789 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
790 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
791 if (OI == OverDefinedCache.end()) continue;
793 // Remove it from the caches.
794 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
795 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
797 assert(CI != Entry.end() && "Couldn't find entry to update?");
799 OverDefinedCache.erase(OI);
801 // If we removed anything, then we potentially need to update
802 // blocks successors too.
806 if (!changed) continue;
808 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
812 //===----------------------------------------------------------------------===//
813 // LazyValueInfo Impl
814 //===----------------------------------------------------------------------===//
816 /// getCache - This lazily constructs the LazyValueInfoCache.
817 static LazyValueInfoCache &getCache(void *&PImpl) {
819 PImpl = new LazyValueInfoCache();
820 return *static_cast<LazyValueInfoCache*>(PImpl);
823 bool LazyValueInfo::runOnFunction(Function &F) {
825 getCache(PImpl).clear();
827 TD = getAnalysisIfAvailable<TargetData>();
832 void LazyValueInfo::releaseMemory() {
833 // If the cache was allocated, free it.
835 delete &getCache(PImpl);
840 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
841 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
843 if (Result.isConstant())
844 return Result.getConstant();
845 else if (Result.isConstantRange()) {
846 ConstantRange CR = Result.getConstantRange();
847 if (const APInt *SingleVal = CR.getSingleElement())
848 return ConstantInt::get(V->getContext(), *SingleVal);
853 /// getConstantOnEdge - Determine whether the specified value is known to be a
854 /// constant on the specified edge. Return null if not.
855 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
857 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
859 if (Result.isConstant())
860 return Result.getConstant();
861 else if (Result.isConstantRange()) {
862 ConstantRange CR = Result.getConstantRange();
863 if (const APInt *SingleVal = CR.getSingleElement())
864 return ConstantInt::get(V->getContext(), *SingleVal);
869 /// getPredicateOnEdge - Determine whether the specified value comparison
870 /// with a constant is known to be true or false on the specified CFG edge.
871 /// Pred is a CmpInst predicate.
872 LazyValueInfo::Tristate
873 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
874 BasicBlock *FromBB, BasicBlock *ToBB) {
875 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
877 // If we know the value is a constant, evaluate the conditional.
879 if (Result.isConstant()) {
880 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
881 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
882 return ResCI->isZero() ? False : True;
886 if (Result.isConstantRange()) {
887 ConstantInt *CI = dyn_cast<ConstantInt>(C);
888 if (!CI) return Unknown;
890 ConstantRange CR = Result.getConstantRange();
891 if (Pred == ICmpInst::ICMP_EQ) {
892 if (!CR.contains(CI->getValue()))
895 if (CR.isSingleElement() && CR.contains(CI->getValue()))
897 } else if (Pred == ICmpInst::ICMP_NE) {
898 if (!CR.contains(CI->getValue()))
901 if (CR.isSingleElement() && CR.contains(CI->getValue()))
905 // Handle more complex predicates.
906 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
907 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
908 if (CR.intersectWith(TrueValues).isEmptySet())
910 else if (TrueValues.contains(CR))
916 if (Result.isNotConstant()) {
917 // If this is an equality comparison, we can try to fold it knowing that
919 if (Pred == ICmpInst::ICMP_EQ) {
920 // !C1 == C -> false iff C1 == C.
921 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
922 Result.getNotConstant(), C, TD);
923 if (Res->isNullValue())
925 } else if (Pred == ICmpInst::ICMP_NE) {
926 // !C1 != C -> true iff C1 == C.
927 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
928 Result.getNotConstant(), C, TD);
929 if (Res->isNullValue())
938 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
939 BasicBlock* NewSucc) {
940 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
943 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
944 if (PImpl) getCache(PImpl).eraseBlock(BB);