1 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for lazy computation of value constraint
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/ValueHandle.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/STLExtras.h"
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
41 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
52 /// FIXME: This is basically just for bringup, this can be made a lot more rich
58 /// undefined - This Value has no known value yet.
61 /// constant - This Value has a specific constant value.
63 /// notconstant - This Value is known to not have the specified value.
66 /// constantrange - The Value falls within this range.
69 /// overdefined - This value is not known to be constant, and we know that
74 /// Val: This stores the current lattice value along with the Constant* for
75 /// the constant if this is a 'constant' or 'notconstant' value.
81 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
83 static LVILatticeVal get(Constant *C) {
85 if (!isa<UndefValue>(C))
89 static LVILatticeVal getNot(Constant *C) {
91 if (!isa<UndefValue>(C))
92 Res.markNotConstant(C);
95 static LVILatticeVal getRange(ConstantRange CR) {
97 Res.markConstantRange(CR);
101 bool isUndefined() const { return Tag == undefined; }
102 bool isConstant() const { return Tag == constant; }
103 bool isNotConstant() const { return Tag == notconstant; }
104 bool isConstantRange() const { return Tag == constantrange; }
105 bool isOverdefined() const { return Tag == overdefined; }
107 Constant *getConstant() const {
108 assert(isConstant() && "Cannot get the constant of a non-constant!");
112 Constant *getNotConstant() const {
113 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
117 ConstantRange getConstantRange() const {
118 assert(isConstantRange() &&
119 "Cannot get the constant-range of a non-constant-range!");
123 /// markOverdefined - Return true if this is a change in status.
124 bool markOverdefined() {
131 /// markConstant - Return true if this is a change in status.
132 bool markConstant(Constant *V) {
133 assert(V && "Marking constant with NULL");
134 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
135 return markConstantRange(ConstantRange(CI->getValue()));
136 if (isa<UndefValue>(V))
139 assert((!isConstant() || getConstant() == V) &&
140 "Marking constant with different value");
141 assert(isUndefined());
147 /// markNotConstant - Return true if this is a change in status.
148 bool markNotConstant(Constant *V) {
149 assert(V && "Marking constant with NULL");
150 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
151 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
152 if (isa<UndefValue>(V))
155 assert((!isConstant() || getConstant() != V) &&
156 "Marking constant !constant with same value");
157 assert((!isNotConstant() || getNotConstant() == V) &&
158 "Marking !constant with different value");
159 assert(isUndefined() || isConstant());
165 /// markConstantRange - Return true if this is a change in status.
166 bool markConstantRange(const ConstantRange NewR) {
167 if (isConstantRange()) {
168 if (NewR.isEmptySet())
169 return markOverdefined();
171 bool changed = Range == NewR;
176 assert(isUndefined());
177 if (NewR.isEmptySet())
178 return markOverdefined();
185 /// mergeIn - Merge the specified lattice value into this one, updating this
186 /// one and returning true if anything changed.
187 bool mergeIn(const LVILatticeVal &RHS) {
188 if (RHS.isUndefined() || isOverdefined()) return false;
189 if (RHS.isOverdefined()) return markOverdefined();
199 if (RHS.isConstant()) {
202 return markOverdefined();
205 if (RHS.isNotConstant()) {
207 return markOverdefined();
209 // Unless we can prove that the two Constants are different, we must
210 // move to overdefined.
211 // FIXME: use TargetData for smarter constant folding.
212 if (ConstantInt *Res = dyn_cast<ConstantInt>(
213 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
215 RHS.getNotConstant())))
217 return markNotConstant(RHS.getNotConstant());
219 return markOverdefined();
222 // RHS is a ConstantRange, LHS is a non-integer Constant.
224 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
225 // a function. The correct result is to pick up RHS.
227 return markOverdefined();
230 if (isNotConstant()) {
231 if (RHS.isConstant()) {
233 return markOverdefined();
235 // Unless we can prove that the two Constants are different, we must
236 // move to overdefined.
237 // FIXME: use TargetData for smarter constant folding.
238 if (ConstantInt *Res = dyn_cast<ConstantInt>(
239 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
245 return markOverdefined();
248 if (RHS.isNotConstant()) {
251 return markOverdefined();
254 return markOverdefined();
257 assert(isConstantRange() && "New LVILattice type?");
258 if (!RHS.isConstantRange())
259 return markOverdefined();
261 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
262 if (NewR.isFullSet())
263 return markOverdefined();
264 return markConstantRange(NewR);
268 } // end anonymous namespace.
271 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
273 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
274 if (Val.isUndefined())
275 return OS << "undefined";
276 if (Val.isOverdefined())
277 return OS << "overdefined";
279 if (Val.isNotConstant())
280 return OS << "notconstant<" << *Val.getNotConstant() << '>';
281 else if (Val.isConstantRange())
282 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
283 << Val.getConstantRange().getUpper() << '>';
284 return OS << "constant<" << *Val.getConstant() << '>';
288 //===----------------------------------------------------------------------===//
289 // LazyValueInfoCache Decl
290 //===----------------------------------------------------------------------===//
293 /// LVIValueHandle - A callback value handle update the cache when
294 /// values are erased.
295 class LazyValueInfoCache;
296 struct LVIValueHandle : public CallbackVH {
297 LazyValueInfoCache *Parent;
299 LVIValueHandle(Value *V, LazyValueInfoCache *P)
300 : CallbackVH(V), Parent(P) { }
303 void allUsesReplacedWith(Value *V) {
311 struct DenseMapInfo<LVIValueHandle> {
312 typedef DenseMapInfo<Value*> PointerInfo;
313 static inline LVIValueHandle getEmptyKey() {
314 return LVIValueHandle(PointerInfo::getEmptyKey(),
315 static_cast<LazyValueInfoCache*>(0));
317 static inline LVIValueHandle getTombstoneKey() {
318 return LVIValueHandle(PointerInfo::getTombstoneKey(),
319 static_cast<LazyValueInfoCache*>(0));
321 static unsigned getHashValue(const LVIValueHandle &Val) {
322 return PointerInfo::getHashValue(Val);
324 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
330 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
331 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
332 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
333 typedef DenseMapInfo<Value*> BPointerInfo;
334 static inline PairTy getEmptyKey() {
335 return std::make_pair(APointerInfo::getEmptyKey(),
336 BPointerInfo::getEmptyKey());
338 static inline PairTy getTombstoneKey() {
339 return std::make_pair(APointerInfo::getTombstoneKey(),
340 BPointerInfo::getTombstoneKey());
342 static unsigned getHashValue( const PairTy &Val) {
343 return APointerInfo::getHashValue(Val.first) ^
344 BPointerInfo::getHashValue(Val.second);
346 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
347 return APointerInfo::isEqual(LHS.first, RHS.first) &&
348 BPointerInfo::isEqual(LHS.second, RHS.second);
354 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
355 /// maintains information about queries across the clients' queries.
356 class LazyValueInfoCache {
357 /// ValueCacheEntryTy - This is all of the cached block information for
358 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
359 /// entries, allowing us to do a lookup with a binary search.
360 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
362 /// ValueCache - This is all of the cached information for all values,
363 /// mapped from Value* to key information.
364 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
366 /// OverDefinedCache - This tracks, on a per-block basis, the set of
367 /// values that are over-defined at the end of that block. This is required
368 /// for cache updating.
369 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
370 DenseSet<OverDefinedPairTy> OverDefinedCache;
372 /// BlockValueStack - This stack holds the state of the value solver
373 /// during a query. It basically emulates the callstack of the naive
374 /// recursive value lookup process.
375 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
377 friend struct LVIValueHandle;
379 /// OverDefinedCacheUpdater - A helper object that ensures that the
380 /// OverDefinedCache is updated whenever solveBlockValue returns.
381 struct OverDefinedCacheUpdater {
382 LazyValueInfoCache *Parent;
387 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
388 LazyValueInfoCache *P)
389 : Parent(P), Val(V), BB(B), BBLV(LV) { }
391 bool markResult(bool changed) {
392 if (changed && BBLV.isOverdefined())
393 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
400 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
401 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
402 LVILatticeVal &Result);
403 bool hasBlockValue(Value *Val, BasicBlock *BB);
405 // These methods process one work item and may add more. A false value
406 // returned means that the work item was not completely processed and must
407 // be revisited after going through the new items.
408 bool solveBlockValue(Value *Val, BasicBlock *BB);
409 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
410 Value *Val, BasicBlock *BB);
411 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
412 PHINode *PN, BasicBlock *BB);
413 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
414 Instruction *BBI, BasicBlock *BB);
418 ValueCacheEntryTy &lookup(Value *V) {
419 return ValueCache[LVIValueHandle(V, this)];
423 /// getValueInBlock - This is the query interface to determine the lattice
424 /// value for the specified Value* at the end of the specified block.
425 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
427 /// getValueOnEdge - This is the query interface to determine the lattice
428 /// value for the specified Value* that is true on the specified edge.
429 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
431 /// threadEdge - This is the update interface to inform the cache that an
432 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
434 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
436 /// eraseBlock - This is part of the update interface to inform the cache
437 /// that a block has been deleted.
438 void eraseBlock(BasicBlock *BB);
440 /// clear - Empty the cache.
443 OverDefinedCache.clear();
446 } // end anonymous namespace
448 void LVIValueHandle::deleted() {
449 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
451 SmallVector<OverDefinedPairTy, 4> ToErase;
452 for (DenseSet<OverDefinedPairTy>::iterator
453 I = Parent->OverDefinedCache.begin(),
454 E = Parent->OverDefinedCache.end();
456 if (I->second == getValPtr())
457 ToErase.push_back(*I);
460 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
461 E = ToErase.end(); I != E; ++I)
462 Parent->OverDefinedCache.erase(*I);
464 // This erasure deallocates *this, so it MUST happen after we're done
465 // using any and all members of *this.
466 Parent->ValueCache.erase(*this);
469 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
470 SmallVector<OverDefinedPairTy, 4> ToErase;
471 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
472 E = OverDefinedCache.end(); I != E; ++I) {
474 ToErase.push_back(*I);
477 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
478 E = ToErase.end(); I != E; ++I)
479 OverDefinedCache.erase(*I);
481 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
482 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
486 void LazyValueInfoCache::solve() {
487 while (!BlockValueStack.empty()) {
488 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
489 if (solveBlockValue(e.second, e.first))
490 BlockValueStack.pop();
494 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
495 // If already a constant, there is nothing to compute.
496 if (isa<Constant>(Val))
499 LVIValueHandle ValHandle(Val, this);
500 if (!ValueCache.count(ValHandle)) return false;
501 return ValueCache[ValHandle].count(BB);
504 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
505 // If already a constant, there is nothing to compute.
506 if (Constant *VC = dyn_cast<Constant>(Val))
507 return LVILatticeVal::get(VC);
509 return lookup(Val)[BB];
512 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
513 if (isa<Constant>(Val))
516 ValueCacheEntryTy &Cache = lookup(Val);
517 LVILatticeVal &BBLV = Cache[BB];
519 // OverDefinedCacheUpdater is a helper object that will update
520 // the OverDefinedCache for us when this method exits. Make sure to
521 // call markResult on it as we exist, passing a bool to indicate if the
522 // cache needs updating, i.e. if we have solve a new value or not.
523 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
525 // If we've already computed this block's value, return it.
526 if (!BBLV.isUndefined()) {
527 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
529 // Since we're reusing a cached value here, we don't need to update the
530 // OverDefinedCahce. The cache will have been properly updated
531 // whenever the cached value was inserted.
532 ODCacheUpdater.markResult(false);
536 // Otherwise, this is the first time we're seeing this block. Reset the
537 // lattice value to overdefined, so that cycles will terminate and be
538 // conservatively correct.
539 BBLV.markOverdefined();
541 Instruction *BBI = dyn_cast<Instruction>(Val);
542 if (BBI == 0 || BBI->getParent() != BB) {
543 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
546 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
547 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
550 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
551 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
552 return ODCacheUpdater.markResult(true);
555 // We can only analyze the definitions of certain classes of instructions
556 // (integral binops and casts at the moment), so bail if this isn't one.
557 LVILatticeVal Result;
558 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
559 !BBI->getType()->isIntegerTy()) {
560 DEBUG(dbgs() << " compute BB '" << BB->getName()
561 << "' - overdefined because inst def found.\n");
562 BBLV.markOverdefined();
563 return ODCacheUpdater.markResult(true);
566 // FIXME: We're currently limited to binops with a constant RHS. This should
568 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
569 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
570 DEBUG(dbgs() << " compute BB '" << BB->getName()
571 << "' - overdefined because inst def found.\n");
573 BBLV.markOverdefined();
574 return ODCacheUpdater.markResult(true);
577 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
580 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
581 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
582 return L->getPointerAddressSpace() == 0 &&
583 GetUnderlyingObject(L->getPointerOperand()) ==
584 GetUnderlyingObject(Ptr);
586 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
587 return S->getPointerAddressSpace() == 0 &&
588 GetUnderlyingObject(S->getPointerOperand()) ==
589 GetUnderlyingObject(Ptr);
591 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
592 if (MI->isVolatile()) return false;
593 if (MI->getAddressSpace() != 0) return false;
595 // FIXME: check whether it has a valuerange that excludes zero?
596 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
597 if (!Len || Len->isZero()) return false;
599 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
601 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
602 return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
607 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
608 Value *Val, BasicBlock *BB) {
609 LVILatticeVal Result; // Start Undefined.
611 // If this is a pointer, and there's a load from that pointer in this BB,
612 // then we know that the pointer can't be NULL.
613 bool NotNull = false;
614 if (Val->getType()->isPointerTy()) {
615 if (isa<AllocaInst>(Val)) {
618 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
619 if (InstructionDereferencesPointer(BI, Val)) {
627 // If this is the entry block, we must be asking about an argument. The
628 // value is overdefined.
629 if (BB == &BB->getParent()->getEntryBlock()) {
630 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
632 const PointerType *PTy = cast<PointerType>(Val->getType());
633 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
635 Result.markOverdefined();
641 // Loop over all of our predecessors, merging what we know from them into
643 bool EdgesMissing = false;
644 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
645 LVILatticeVal EdgeResult;
646 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
650 Result.mergeIn(EdgeResult);
652 // If we hit overdefined, exit early. The BlockVals entry is already set
654 if (Result.isOverdefined()) {
655 DEBUG(dbgs() << " compute BB '" << BB->getName()
656 << "' - overdefined because of pred.\n");
657 // If we previously determined that this is a pointer that can't be null
658 // then return that rather than giving up entirely.
660 const PointerType *PTy = cast<PointerType>(Val->getType());
661 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
671 // Return the merged value, which is more precise than 'overdefined'.
672 assert(!Result.isOverdefined());
677 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
678 PHINode *PN, BasicBlock *BB) {
679 LVILatticeVal Result; // Start Undefined.
681 // Loop over all of our predecessors, merging what we know from them into
683 bool EdgesMissing = false;
684 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
685 BasicBlock *PhiBB = PN->getIncomingBlock(i);
686 Value *PhiVal = PN->getIncomingValue(i);
687 LVILatticeVal EdgeResult;
688 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
692 Result.mergeIn(EdgeResult);
694 // If we hit overdefined, exit early. The BlockVals entry is already set
696 if (Result.isOverdefined()) {
697 DEBUG(dbgs() << " compute BB '" << BB->getName()
698 << "' - overdefined because of pred.\n");
707 // Return the merged value, which is more precise than 'overdefined'.
708 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
713 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
716 // Figure out the range of the LHS. If that fails, bail.
717 if (!hasBlockValue(BBI->getOperand(0), BB)) {
718 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
722 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
723 if (!LHSVal.isConstantRange()) {
724 BBLV.markOverdefined();
728 ConstantRange LHSRange = LHSVal.getConstantRange();
729 ConstantRange RHSRange(1);
730 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
731 if (isa<BinaryOperator>(BBI)) {
732 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
733 RHSRange = ConstantRange(RHS->getValue());
735 BBLV.markOverdefined();
740 // NOTE: We're currently limited by the set of operations that ConstantRange
741 // can evaluate symbolically. Enhancing that set will allows us to analyze
743 LVILatticeVal Result;
744 switch (BBI->getOpcode()) {
745 case Instruction::Add:
746 Result.markConstantRange(LHSRange.add(RHSRange));
748 case Instruction::Sub:
749 Result.markConstantRange(LHSRange.sub(RHSRange));
751 case Instruction::Mul:
752 Result.markConstantRange(LHSRange.multiply(RHSRange));
754 case Instruction::UDiv:
755 Result.markConstantRange(LHSRange.udiv(RHSRange));
757 case Instruction::Shl:
758 Result.markConstantRange(LHSRange.shl(RHSRange));
760 case Instruction::LShr:
761 Result.markConstantRange(LHSRange.lshr(RHSRange));
763 case Instruction::Trunc:
764 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
766 case Instruction::SExt:
767 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
769 case Instruction::ZExt:
770 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
772 case Instruction::BitCast:
773 Result.markConstantRange(LHSRange);
775 case Instruction::And:
776 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
778 case Instruction::Or:
779 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
782 // Unhandled instructions are overdefined.
784 DEBUG(dbgs() << " compute BB '" << BB->getName()
785 << "' - overdefined because inst def found.\n");
786 Result.markOverdefined();
794 /// getEdgeValue - This method attempts to infer more complex
795 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
796 BasicBlock *BBTo, LVILatticeVal &Result) {
797 // If already a constant, there is nothing to compute.
798 if (Constant *VC = dyn_cast<Constant>(Val)) {
799 Result = LVILatticeVal::get(VC);
803 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
805 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
806 // If this is a conditional branch and only one successor goes to BBTo, then
807 // we maybe able to infer something from the condition.
808 if (BI->isConditional() &&
809 BI->getSuccessor(0) != BI->getSuccessor(1)) {
810 bool isTrueDest = BI->getSuccessor(0) == BBTo;
811 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
812 "BBTo isn't a successor of BBFrom");
814 // If V is the condition of the branch itself, then we know exactly what
816 if (BI->getCondition() == Val) {
817 Result = LVILatticeVal::get(ConstantInt::get(
818 Type::getInt1Ty(Val->getContext()), isTrueDest));
822 // If the condition of the branch is an equality comparison, we may be
823 // able to infer the value.
824 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
825 if (ICI && ICI->getOperand(0) == Val &&
826 isa<Constant>(ICI->getOperand(1))) {
827 if (ICI->isEquality()) {
828 // We know that V has the RHS constant if this is a true SETEQ or
830 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
831 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
833 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
837 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
838 // Calculate the range of values that would satisfy the comparison.
839 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
840 ConstantRange TrueValues =
841 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
843 // If we're interested in the false dest, invert the condition.
844 if (!isTrueDest) TrueValues = TrueValues.inverse();
846 // Figure out the possible values of the query BEFORE this branch.
847 if (!hasBlockValue(Val, BBFrom)) {
848 BlockValueStack.push(std::make_pair(BBFrom, Val));
852 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
853 if (!InBlock.isConstantRange()) {
854 Result = LVILatticeVal::getRange(TrueValues);
858 // Find all potential values that satisfy both the input and output
860 ConstantRange PossibleValues =
861 TrueValues.intersectWith(InBlock.getConstantRange());
863 Result = LVILatticeVal::getRange(PossibleValues);
870 // If the edge was formed by a switch on the value, then we may know exactly
872 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
873 if (SI->getCondition() == Val) {
874 // We don't know anything in the default case.
875 if (SI->getDefaultDest() == BBTo) {
876 Result.markOverdefined();
880 // We only know something if there is exactly one value that goes from
882 unsigned NumEdges = 0;
883 ConstantInt *EdgeVal = 0;
884 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
885 if (SI->getSuccessor(i) != BBTo) continue;
886 if (NumEdges++) break;
887 EdgeVal = SI->getCaseValue(i);
889 assert(EdgeVal && "Missing successor?");
891 Result = LVILatticeVal::get(EdgeVal);
897 // Otherwise see if the value is known in the block.
898 if (hasBlockValue(Val, BBFrom)) {
899 Result = getBlockValue(Val, BBFrom);
902 BlockValueStack.push(std::make_pair(BBFrom, Val));
906 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
907 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
908 << BB->getName() << "'\n");
910 BlockValueStack.push(std::make_pair(BB, V));
912 LVILatticeVal Result = getBlockValue(V, BB);
914 DEBUG(dbgs() << " Result = " << Result << "\n");
918 LVILatticeVal LazyValueInfoCache::
919 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
920 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
921 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
923 LVILatticeVal Result;
924 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
926 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
928 assert(WasFastQuery && "More work to do after problem solved?");
931 DEBUG(dbgs() << " Result = " << Result << "\n");
935 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
936 BasicBlock *NewSucc) {
937 // When an edge in the graph has been threaded, values that we could not
938 // determine a value for before (i.e. were marked overdefined) may be possible
939 // to solve now. We do NOT try to proactively update these values. Instead,
940 // we clear their entries from the cache, and allow lazy updating to recompute
943 // The updating process is fairly simple: we need to dropped cached info
944 // for all values that were marked overdefined in OldSucc, and for those same
945 // values in any successor of OldSucc (except NewSucc) in which they were
946 // also marked overdefined.
947 std::vector<BasicBlock*> worklist;
948 worklist.push_back(OldSucc);
950 DenseSet<Value*> ClearSet;
951 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
952 E = OverDefinedCache.end(); I != E; ++I) {
953 if (I->first == OldSucc)
954 ClearSet.insert(I->second);
957 // Use a worklist to perform a depth-first search of OldSucc's successors.
958 // NOTE: We do not need a visited list since any blocks we have already
959 // visited will have had their overdefined markers cleared already, and we
960 // thus won't loop to their successors.
961 while (!worklist.empty()) {
962 BasicBlock *ToUpdate = worklist.back();
965 // Skip blocks only accessible through NewSucc.
966 if (ToUpdate == NewSucc) continue;
968 bool changed = false;
969 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
971 // If a value was marked overdefined in OldSucc, and is here too...
972 DenseSet<OverDefinedPairTy>::iterator OI =
973 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
974 if (OI == OverDefinedCache.end()) continue;
976 // Remove it from the caches.
977 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
978 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
980 assert(CI != Entry.end() && "Couldn't find entry to update?");
982 OverDefinedCache.erase(OI);
984 // If we removed anything, then we potentially need to update
985 // blocks successors too.
989 if (!changed) continue;
991 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
995 //===----------------------------------------------------------------------===//
996 // LazyValueInfo Impl
997 //===----------------------------------------------------------------------===//
999 /// getCache - This lazily constructs the LazyValueInfoCache.
1000 static LazyValueInfoCache &getCache(void *&PImpl) {
1002 PImpl = new LazyValueInfoCache();
1003 return *static_cast<LazyValueInfoCache*>(PImpl);
1006 bool LazyValueInfo::runOnFunction(Function &F) {
1008 getCache(PImpl).clear();
1010 TD = getAnalysisIfAvailable<TargetData>();
1015 void LazyValueInfo::releaseMemory() {
1016 // If the cache was allocated, free it.
1018 delete &getCache(PImpl);
1023 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1024 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1026 if (Result.isConstant())
1027 return Result.getConstant();
1028 if (Result.isConstantRange()) {
1029 ConstantRange CR = Result.getConstantRange();
1030 if (const APInt *SingleVal = CR.getSingleElement())
1031 return ConstantInt::get(V->getContext(), *SingleVal);
1036 /// getConstantOnEdge - Determine whether the specified value is known to be a
1037 /// constant on the specified edge. Return null if not.
1038 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1040 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1042 if (Result.isConstant())
1043 return Result.getConstant();
1044 if (Result.isConstantRange()) {
1045 ConstantRange CR = Result.getConstantRange();
1046 if (const APInt *SingleVal = CR.getSingleElement())
1047 return ConstantInt::get(V->getContext(), *SingleVal);
1052 /// getPredicateOnEdge - Determine whether the specified value comparison
1053 /// with a constant is known to be true or false on the specified CFG edge.
1054 /// Pred is a CmpInst predicate.
1055 LazyValueInfo::Tristate
1056 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1057 BasicBlock *FromBB, BasicBlock *ToBB) {
1058 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1060 // If we know the value is a constant, evaluate the conditional.
1062 if (Result.isConstant()) {
1063 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
1064 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1065 return ResCI->isZero() ? False : True;
1069 if (Result.isConstantRange()) {
1070 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1071 if (!CI) return Unknown;
1073 ConstantRange CR = Result.getConstantRange();
1074 if (Pred == ICmpInst::ICMP_EQ) {
1075 if (!CR.contains(CI->getValue()))
1078 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1080 } else if (Pred == ICmpInst::ICMP_NE) {
1081 if (!CR.contains(CI->getValue()))
1084 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1088 // Handle more complex predicates.
1089 ConstantRange TrueValues =
1090 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1091 if (TrueValues.contains(CR))
1093 if (TrueValues.inverse().contains(CR))
1098 if (Result.isNotConstant()) {
1099 // If this is an equality comparison, we can try to fold it knowing that
1101 if (Pred == ICmpInst::ICMP_EQ) {
1102 // !C1 == C -> false iff C1 == C.
1103 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1104 Result.getNotConstant(), C, TD);
1105 if (Res->isNullValue())
1107 } else if (Pred == ICmpInst::ICMP_NE) {
1108 // !C1 != C -> true iff C1 == C.
1109 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1110 Result.getNotConstant(), C, TD);
1111 if (Res->isNullValue())
1120 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1121 BasicBlock *NewSucc) {
1122 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1125 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1126 if (PImpl) getCache(PImpl).eraseBlock(BB);