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();
199 } else if (isConstant()) {
200 if (getConstant() == RHS.getNotConstant() ||
201 isa<ConstantExpr>(RHS.getNotConstant()) ||
202 isa<ConstantExpr>(getConstant()))
203 return markOverdefined();
204 return markNotConstant(RHS.getNotConstant());
205 } else if (isConstantRange()) {
206 return markOverdefined();
209 assert(isUndefined() && "Unexpected lattice");
210 return markNotConstant(RHS.getNotConstant());
213 if (RHS.isConstantRange()) {
214 if (isConstantRange()) {
215 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
216 if (NewR.isFullSet())
217 return markOverdefined();
219 return markConstantRange(NewR);
220 } else if (!isUndefined()) {
221 return markOverdefined();
224 assert(isUndefined() && "Unexpected lattice");
225 return markConstantRange(RHS.getConstantRange());
228 // RHS must be a constant, we must be undef, constant, or notconstant.
229 assert(!isConstantRange() &&
230 "Constant and ConstantRange cannot be merged.");
233 return markConstant(RHS.getConstant());
236 if (getConstant() != RHS.getConstant())
237 return markOverdefined();
241 // If we are known "!=4" and RHS is "==5", stay at "!=4".
242 if (getNotConstant() == RHS.getConstant() ||
243 isa<ConstantExpr>(getNotConstant()) ||
244 isa<ConstantExpr>(RHS.getConstant()))
245 return markOverdefined();
251 } // end anonymous namespace.
254 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
255 if (Val.isUndefined())
256 return OS << "undefined";
257 if (Val.isOverdefined())
258 return OS << "overdefined";
260 if (Val.isNotConstant())
261 return OS << "notconstant<" << *Val.getNotConstant() << '>';
262 else if (Val.isConstantRange())
263 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
264 << Val.getConstantRange().getUpper() << '>';
265 return OS << "constant<" << *Val.getConstant() << '>';
269 //===----------------------------------------------------------------------===//
270 // LazyValueInfoCache Decl
271 //===----------------------------------------------------------------------===//
274 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
275 /// maintains information about queries across the clients' queries.
276 class LazyValueInfoCache {
278 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
279 /// specified basic block for a Value* that depends on context.
280 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
282 /// ValueCacheEntryTy - This is all of the cached block information for
283 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
284 /// entries, allowing us to do a lookup with a binary search.
285 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
288 /// LVIValueHandle - A callback value handle update the cache when
289 /// values are erased.
290 struct LVIValueHandle : public CallbackVH {
291 LazyValueInfoCache *Parent;
293 LVIValueHandle(Value *V, LazyValueInfoCache *P)
294 : CallbackVH(V), Parent(P) { }
297 void allUsesReplacedWith(Value* V) {
301 LVIValueHandle &operator=(Value *V) {
302 return *this = LVIValueHandle(V, Parent);
306 /// ValueCache - This is all of the cached information for all values,
307 /// mapped from Value* to key information.
308 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
310 /// OverDefinedCache - This tracks, on a per-block basis, the set of
311 /// values that are over-defined at the end of that block. This is required
312 /// for cache updating.
313 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
317 /// getValueInBlock - This is the query interface to determine the lattice
318 /// value for the specified Value* at the end of the specified block.
319 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
321 /// getValueOnEdge - This is the query interface to determine the lattice
322 /// value for the specified Value* that is true on the specified edge.
323 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
325 /// threadEdge - This is the update interface to inform the cache that an
326 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
328 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
330 /// eraseBlock - This is part of the update interface to inform the cache
331 /// that a block has been deleted.
332 void eraseBlock(BasicBlock *BB);
334 /// clear - Empty the cache.
337 OverDefinedCache.clear();
340 } // end anonymous namespace
342 //===----------------------------------------------------------------------===//
344 //===----------------------------------------------------------------------===//
347 /// LVIQuery - This is a transient object that exists while a query is
350 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
351 /// reallocation of the densemap on every query.
353 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
354 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
356 /// This is the current value being queried for.
359 /// This is a pointer to the owning cache, for recursive queries.
360 LazyValueInfoCache &Parent;
362 /// This is all of the cached information about this value.
363 ValueCacheEntryTy &Cache;
365 /// This tracks, for each block, what values are overdefined.
366 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
368 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
369 /// added to cache but that are not in sorted order.
370 DenseSet<BasicBlock*> NewBlockInfo;
374 LVIQuery(Value *V, LazyValueInfoCache &P,
375 ValueCacheEntryTy &VC,
376 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
377 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
381 // When the query is done, insert the newly discovered facts into the
382 // cache in sorted order.
383 if (NewBlockInfo.empty()) return;
385 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
386 E = NewBlockInfo.end(); I != E; ++I) {
387 if (Cache[*I].isOverdefined())
388 OverDefinedCache.insert(std::make_pair(*I, Val));
392 LVILatticeVal getBlockValue(BasicBlock *BB);
393 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
396 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
398 } // end anonymous namespace
400 void LazyValueInfoCache::LVIValueHandle::deleted() {
401 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
402 I = Parent->OverDefinedCache.begin(),
403 E = Parent->OverDefinedCache.end();
405 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
407 if (tmp->second == getValPtr())
408 Parent->OverDefinedCache.erase(tmp);
411 // This erasure deallocates *this, so it MUST happen after we're done
412 // using any and all members of *this.
413 Parent->ValueCache.erase(*this);
416 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
417 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
418 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
419 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
421 if (tmp->first == BB)
422 OverDefinedCache.erase(tmp);
425 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
426 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
430 /// getCachedEntryForBlock - See if we already have a value for this block. If
431 /// so, return it, otherwise create a new entry in the Cache map to use.
432 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
433 NewBlockInfo.insert(BB);
437 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
438 // See if we already have a value for this block.
439 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
441 // If we've already computed this block's value, return it.
442 if (!BBLV.isUndefined()) {
443 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
447 // Otherwise, this is the first time we're seeing this block. Reset the
448 // lattice value to overdefined, so that cycles will terminate and be
449 // conservatively correct.
450 BBLV.markOverdefined();
453 Instruction *BBI = dyn_cast<Instruction>(Val);
454 if (BBI == 0 || BBI->getParent() != BB) {
455 LVILatticeVal Result; // Start Undefined.
457 // If this is a pointer, and there's a load from that pointer in this BB,
458 // then we know that the pointer can't be NULL.
459 if (Val->getType()->isPointerTy()) {
460 const PointerType *PTy = cast<PointerType>(Val->getType());
461 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
462 LoadInst *L = dyn_cast<LoadInst>(BI);
463 if (L && L->getPointerAddressSpace() == 0 &&
464 L->getPointerOperand()->getUnderlyingObject() ==
465 Val->getUnderlyingObject()) {
466 return LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
471 unsigned NumPreds = 0;
472 // Loop over all of our predecessors, merging what we know from them into
474 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
475 Result.mergeIn(getEdgeValue(*PI, BB));
477 // If we hit overdefined, exit early. The BlockVals entry is already set
479 if (Result.isOverdefined()) {
480 DEBUG(dbgs() << " compute BB '" << BB->getName()
481 << "' - overdefined because of pred.\n");
487 // If this is the entry block, we must be asking about an argument. The
488 // value is overdefined.
489 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
490 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
491 Result.markOverdefined();
495 // Return the merged value, which is more precise than 'overdefined'.
496 assert(!Result.isOverdefined());
497 return Cache[BB] = Result;
500 // If this value is defined by an instruction in this block, we have to
501 // process it here somehow or return overdefined.
502 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
503 LVILatticeVal Result; // Start Undefined.
505 // Loop over all of our predecessors, merging what we know from them into
507 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
508 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
509 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
511 // If we hit overdefined, exit early. The BlockVals entry is already set
513 if (Result.isOverdefined()) {
514 DEBUG(dbgs() << " compute BB '" << BB->getName()
515 << "' - overdefined because of pred.\n");
520 // Return the merged value, which is more precise than 'overdefined'.
521 assert(!Result.isOverdefined());
522 return Cache[BB] = Result;
525 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
527 // We can only analyze the definitions of certain classes of instructions
528 // (integral binops and casts at the moment), so bail if this isn't one.
529 LVILatticeVal Result;
530 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
531 !BBI->getType()->isIntegerTy()) {
532 DEBUG(dbgs() << " compute BB '" << BB->getName()
533 << "' - overdefined because inst def found.\n");
534 Result.markOverdefined();
538 // FIXME: We're currently limited to binops with a constant RHS. This should
540 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
541 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
542 DEBUG(dbgs() << " compute BB '" << BB->getName()
543 << "' - overdefined because inst def found.\n");
545 Result.markOverdefined();
549 // Figure out the range of the LHS. If that fails, bail.
550 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
551 if (!LHSVal.isConstantRange()) {
552 Result.markOverdefined();
556 ConstantInt *RHS = 0;
557 ConstantRange LHSRange = LHSVal.getConstantRange();
558 ConstantRange RHSRange(1);
559 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
560 if (isa<BinaryOperator>(BBI)) {
561 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
563 Result.markOverdefined();
567 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
570 // NOTE: We're currently limited by the set of operations that ConstantRange
571 // can evaluate symbolically. Enhancing that set will allows us to analyze
573 switch (BBI->getOpcode()) {
574 case Instruction::Add:
575 Result.markConstantRange(LHSRange.add(RHSRange));
577 case Instruction::Sub:
578 Result.markConstantRange(LHSRange.sub(RHSRange));
580 case Instruction::Mul:
581 Result.markConstantRange(LHSRange.multiply(RHSRange));
583 case Instruction::UDiv:
584 Result.markConstantRange(LHSRange.udiv(RHSRange));
586 case Instruction::Shl:
587 Result.markConstantRange(LHSRange.shl(RHSRange));
589 case Instruction::LShr:
590 Result.markConstantRange(LHSRange.lshr(RHSRange));
592 case Instruction::Trunc:
593 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
595 case Instruction::SExt:
596 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
598 case Instruction::ZExt:
599 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
601 case Instruction::BitCast:
602 Result.markConstantRange(LHSRange);
605 // Unhandled instructions are overdefined.
607 DEBUG(dbgs() << " compute BB '" << BB->getName()
608 << "' - overdefined because inst def found.\n");
609 Result.markOverdefined();
613 return Cache[BB] = Result;
617 /// getEdgeValue - This method attempts to infer more complex
618 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
619 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
621 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
622 // If this is a conditional branch and only one successor goes to BBTo, then
623 // we maybe able to infer something from the condition.
624 if (BI->isConditional() &&
625 BI->getSuccessor(0) != BI->getSuccessor(1)) {
626 bool isTrueDest = BI->getSuccessor(0) == BBTo;
627 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
628 "BBTo isn't a successor of BBFrom");
630 // If V is the condition of the branch itself, then we know exactly what
632 if (BI->getCondition() == Val)
633 return LVILatticeVal::get(ConstantInt::get(
634 Type::getInt1Ty(Val->getContext()), isTrueDest));
636 // If the condition of the branch is an equality comparison, we may be
637 // able to infer the value.
638 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
639 if (ICI && ICI->getOperand(0) == Val &&
640 isa<Constant>(ICI->getOperand(1))) {
641 if (ICI->isEquality()) {
642 // We know that V has the RHS constant if this is a true SETEQ or
644 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
645 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
646 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
649 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
650 // Calculate the range of values that would satisfy the comparison.
651 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
652 ConstantRange TrueValues =
653 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
655 // If we're interested in the false dest, invert the condition.
656 if (!isTrueDest) TrueValues = TrueValues.inverse();
658 // Figure out the possible values of the query BEFORE this branch.
659 LVILatticeVal InBlock = getBlockValue(BBFrom);
660 if (!InBlock.isConstantRange())
661 return LVILatticeVal::getRange(TrueValues);
663 // Find all potential values that satisfy both the input and output
665 ConstantRange PossibleValues =
666 TrueValues.intersectWith(InBlock.getConstantRange());
668 return LVILatticeVal::getRange(PossibleValues);
674 // If the edge was formed by a switch on the value, then we may know exactly
676 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
677 // If BBTo is the default destination of the switch, we know that it
678 // doesn't have the same value as any of the cases.
679 if (SI->getCondition() == Val) {
680 if (SI->getDefaultDest() == BBTo) {
681 const IntegerType *IT = cast<IntegerType>(Val->getType());
682 ConstantRange CR(IT->getBitWidth());
684 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
685 const APInt CaseVal = SI->getCaseValue(i)->getValue();
686 ConstantRange CaseRange(CaseVal, CaseVal+1);
687 CaseRange = CaseRange.inverse();
688 CR = CR.intersectWith(CaseRange);
691 LVILatticeVal Result;
692 if (CR.isFullSet() || CR.isEmptySet())
693 Result.markOverdefined();
695 Result.markConstantRange(CR);
699 // We only know something if there is exactly one value that goes from
701 unsigned NumEdges = 0;
702 ConstantInt *EdgeVal = 0;
703 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
704 if (SI->getSuccessor(i) != BBTo) continue;
705 if (NumEdges++) break;
706 EdgeVal = SI->getCaseValue(i);
708 assert(EdgeVal && "Missing successor?");
710 return LVILatticeVal::get(EdgeVal);
714 // Otherwise see if the value is known in the block.
715 return getBlockValue(BBFrom);
719 //===----------------------------------------------------------------------===//
720 // LazyValueInfoCache Impl
721 //===----------------------------------------------------------------------===//
723 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
724 // If already a constant, there is nothing to compute.
725 if (Constant *VC = dyn_cast<Constant>(V))
726 return LVILatticeVal::get(VC);
728 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
729 << BB->getName() << "'\n");
731 LVILatticeVal Result = LVIQuery(V, *this,
732 ValueCache[LVIValueHandle(V, this)],
733 OverDefinedCache).getBlockValue(BB);
735 DEBUG(dbgs() << " Result = " << Result << "\n");
739 LVILatticeVal LazyValueInfoCache::
740 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
741 // If already a constant, there is nothing to compute.
742 if (Constant *VC = dyn_cast<Constant>(V))
743 return LVILatticeVal::get(VC);
745 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
746 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
748 LVILatticeVal Result =
749 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
750 OverDefinedCache).getEdgeValue(FromBB, ToBB);
752 DEBUG(dbgs() << " Result = " << Result << "\n");
757 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
758 BasicBlock *NewSucc) {
759 // When an edge in the graph has been threaded, values that we could not
760 // determine a value for before (i.e. were marked overdefined) may be possible
761 // to solve now. We do NOT try to proactively update these values. Instead,
762 // we clear their entries from the cache, and allow lazy updating to recompute
765 // The updating process is fairly simple: we need to dropped cached info
766 // for all values that were marked overdefined in OldSucc, and for those same
767 // values in any successor of OldSucc (except NewSucc) in which they were
768 // also marked overdefined.
769 std::vector<BasicBlock*> worklist;
770 worklist.push_back(OldSucc);
772 DenseSet<Value*> ClearSet;
773 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
774 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
775 if (I->first == OldSucc)
776 ClearSet.insert(I->second);
779 // Use a worklist to perform a depth-first search of OldSucc's successors.
780 // NOTE: We do not need a visited list since any blocks we have already
781 // visited will have had their overdefined markers cleared already, and we
782 // thus won't loop to their successors.
783 while (!worklist.empty()) {
784 BasicBlock *ToUpdate = worklist.back();
787 // Skip blocks only accessible through NewSucc.
788 if (ToUpdate == NewSucc) continue;
790 bool changed = false;
791 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
793 // If a value was marked overdefined in OldSucc, and is here too...
794 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
795 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
796 if (OI == OverDefinedCache.end()) continue;
798 // Remove it from the caches.
799 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
800 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
802 assert(CI != Entry.end() && "Couldn't find entry to update?");
804 OverDefinedCache.erase(OI);
806 // If we removed anything, then we potentially need to update
807 // blocks successors too.
811 if (!changed) continue;
813 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
817 //===----------------------------------------------------------------------===//
818 // LazyValueInfo Impl
819 //===----------------------------------------------------------------------===//
821 /// getCache - This lazily constructs the LazyValueInfoCache.
822 static LazyValueInfoCache &getCache(void *&PImpl) {
824 PImpl = new LazyValueInfoCache();
825 return *static_cast<LazyValueInfoCache*>(PImpl);
828 bool LazyValueInfo::runOnFunction(Function &F) {
830 getCache(PImpl).clear();
832 TD = getAnalysisIfAvailable<TargetData>();
837 void LazyValueInfo::releaseMemory() {
838 // If the cache was allocated, free it.
840 delete &getCache(PImpl);
845 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
846 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
848 if (Result.isConstant())
849 return Result.getConstant();
850 else if (Result.isConstantRange()) {
851 ConstantRange CR = Result.getConstantRange();
852 if (const APInt *SingleVal = CR.getSingleElement())
853 return ConstantInt::get(V->getContext(), *SingleVal);
858 /// getConstantOnEdge - Determine whether the specified value is known to be a
859 /// constant on the specified edge. Return null if not.
860 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
862 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
864 if (Result.isConstant())
865 return Result.getConstant();
866 else if (Result.isConstantRange()) {
867 ConstantRange CR = Result.getConstantRange();
868 if (const APInt *SingleVal = CR.getSingleElement())
869 return ConstantInt::get(V->getContext(), *SingleVal);
874 /// getPredicateOnEdge - Determine whether the specified value comparison
875 /// with a constant is known to be true or false on the specified CFG edge.
876 /// Pred is a CmpInst predicate.
877 LazyValueInfo::Tristate
878 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
879 BasicBlock *FromBB, BasicBlock *ToBB) {
880 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
882 // If we know the value is a constant, evaluate the conditional.
884 if (Result.isConstant()) {
885 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
886 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
887 return ResCI->isZero() ? False : True;
891 if (Result.isConstantRange()) {
892 ConstantInt *CI = dyn_cast<ConstantInt>(C);
893 if (!CI) return Unknown;
895 ConstantRange CR = Result.getConstantRange();
896 if (Pred == ICmpInst::ICMP_EQ) {
897 if (!CR.contains(CI->getValue()))
900 if (CR.isSingleElement() && CR.contains(CI->getValue()))
902 } else if (Pred == ICmpInst::ICMP_NE) {
903 if (!CR.contains(CI->getValue()))
906 if (CR.isSingleElement() && CR.contains(CI->getValue()))
910 // Handle more complex predicates.
911 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
912 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
913 if (CR.intersectWith(TrueValues).isEmptySet())
915 else if (TrueValues.contains(CR))
921 if (Result.isNotConstant()) {
922 // If this is an equality comparison, we can try to fold it knowing that
924 if (Pred == ICmpInst::ICMP_EQ) {
925 // !C1 == C -> false iff C1 == C.
926 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
927 Result.getNotConstant(), C, TD);
928 if (Res->isNullValue())
930 } else if (Pred == ICmpInst::ICMP_NE) {
931 // !C1 != C -> true iff C1 == C.
932 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
933 Result.getNotConstant(), C, TD);
934 if (Res->isNullValue())
943 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
944 BasicBlock* NewSucc) {
945 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
948 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
949 if (PImpl) getCache(PImpl).eraseBlock(BB);