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/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/ConstantRange.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/PatternMatch.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
35 using namespace PatternMatch;
37 char LazyValueInfo::ID = 0;
38 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
39 "Lazy Value Information Analysis", false, true)
40 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
41 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
45 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
53 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
56 /// FIXME: This is basically just for bringup, this can be made a lot more rich
62 /// undefined - This Value has no known value yet.
65 /// constant - This Value has a specific constant value.
67 /// notconstant - This Value is known to not have the specified value.
70 /// constantrange - The Value falls within this range.
73 /// overdefined - This value is not known to be constant, and we know that
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'notconstant' value.
85 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
87 static LVILatticeVal get(Constant *C) {
89 if (!isa<UndefValue>(C))
93 static LVILatticeVal getNot(Constant *C) {
95 if (!isa<UndefValue>(C))
96 Res.markNotConstant(C);
99 static LVILatticeVal getRange(ConstantRange CR) {
101 Res.markConstantRange(CR);
105 bool isUndefined() const { return Tag == undefined; }
106 bool isConstant() const { return Tag == constant; }
107 bool isNotConstant() const { return Tag == notconstant; }
108 bool isConstantRange() const { return Tag == constantrange; }
109 bool isOverdefined() const { return Tag == overdefined; }
111 Constant *getConstant() const {
112 assert(isConstant() && "Cannot get the constant of a non-constant!");
116 Constant *getNotConstant() const {
117 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
121 ConstantRange getConstantRange() const {
122 assert(isConstantRange() &&
123 "Cannot get the constant-range of a non-constant-range!");
127 /// markOverdefined - Return true if this is a change in status.
128 bool markOverdefined() {
135 /// markConstant - Return true if this is a change in status.
136 bool markConstant(Constant *V) {
137 assert(V && "Marking constant with NULL");
138 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
139 return markConstantRange(ConstantRange(CI->getValue()));
140 if (isa<UndefValue>(V))
143 assert((!isConstant() || getConstant() == V) &&
144 "Marking constant with different value");
145 assert(isUndefined());
151 /// markNotConstant - Return true if this is a change in status.
152 bool markNotConstant(Constant *V) {
153 assert(V && "Marking constant with NULL");
154 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
155 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
156 if (isa<UndefValue>(V))
159 assert((!isConstant() || getConstant() != V) &&
160 "Marking constant !constant with same value");
161 assert((!isNotConstant() || getNotConstant() == V) &&
162 "Marking !constant with different value");
163 assert(isUndefined() || isConstant());
169 /// markConstantRange - Return true if this is a change in status.
170 bool markConstantRange(const ConstantRange NewR) {
171 if (isConstantRange()) {
172 if (NewR.isEmptySet())
173 return markOverdefined();
175 bool changed = Range != NewR;
180 assert(isUndefined());
181 if (NewR.isEmptySet())
182 return markOverdefined();
189 /// mergeIn - Merge the specified lattice value into this one, updating this
190 /// one and returning true if anything changed.
191 bool mergeIn(const LVILatticeVal &RHS) {
192 if (RHS.isUndefined() || isOverdefined()) return false;
193 if (RHS.isOverdefined()) return markOverdefined();
203 if (RHS.isConstant()) {
206 return markOverdefined();
209 if (RHS.isNotConstant()) {
211 return markOverdefined();
213 // Unless we can prove that the two Constants are different, we must
214 // move to overdefined.
215 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
216 if (ConstantInt *Res = dyn_cast<ConstantInt>(
217 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
219 RHS.getNotConstant())))
221 return markNotConstant(RHS.getNotConstant());
223 return markOverdefined();
226 // RHS is a ConstantRange, LHS is a non-integer Constant.
228 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
229 // a function. The correct result is to pick up RHS.
231 return markOverdefined();
234 if (isNotConstant()) {
235 if (RHS.isConstant()) {
237 return markOverdefined();
239 // Unless we can prove that the two Constants are different, we must
240 // move to overdefined.
241 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
242 if (ConstantInt *Res = dyn_cast<ConstantInt>(
243 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
249 return markOverdefined();
252 if (RHS.isNotConstant()) {
255 return markOverdefined();
258 return markOverdefined();
261 assert(isConstantRange() && "New LVILattice type?");
262 if (!RHS.isConstantRange())
263 return markOverdefined();
265 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
266 if (NewR.isFullSet())
267 return markOverdefined();
268 return markConstantRange(NewR);
272 } // end anonymous namespace.
275 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
277 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
278 if (Val.isUndefined())
279 return OS << "undefined";
280 if (Val.isOverdefined())
281 return OS << "overdefined";
283 if (Val.isNotConstant())
284 return OS << "notconstant<" << *Val.getNotConstant() << '>';
285 else if (Val.isConstantRange())
286 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
287 << Val.getConstantRange().getUpper() << '>';
288 return OS << "constant<" << *Val.getConstant() << '>';
292 //===----------------------------------------------------------------------===//
293 // LazyValueInfoCache Decl
294 //===----------------------------------------------------------------------===//
297 /// LVIValueHandle - A callback value handle updates the cache when
298 /// values are erased.
299 class LazyValueInfoCache;
300 struct LVIValueHandle : public CallbackVH {
301 LazyValueInfoCache *Parent;
303 LVIValueHandle(Value *V, LazyValueInfoCache *P)
304 : CallbackVH(V), Parent(P) { }
307 void allUsesReplacedWith(Value *V) {
314 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
315 /// maintains information about queries across the clients' queries.
316 class LazyValueInfoCache {
317 /// ValueCacheEntryTy - This is all of the cached block information for
318 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
319 /// entries, allowing us to do a lookup with a binary search.
320 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
322 /// ValueCache - This is all of the cached information for all values,
323 /// mapped from Value* to key information.
324 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
326 /// OverDefinedCache - This tracks, on a per-block basis, the set of
327 /// values that are over-defined at the end of that block. This is required
328 /// for cache updating.
329 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
330 DenseSet<OverDefinedPairTy> OverDefinedCache;
332 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
333 /// don't spend time removing unused blocks from our caches.
334 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
336 /// BlockValueStack - This stack holds the state of the value solver
337 /// during a query. It basically emulates the callstack of the naive
338 /// recursive value lookup process.
339 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
341 friend struct LVIValueHandle;
343 /// OverDefinedCacheUpdater - A helper object that ensures that the
344 /// OverDefinedCache is updated whenever solveBlockValue returns.
345 struct OverDefinedCacheUpdater {
346 LazyValueInfoCache *Parent;
351 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
352 LazyValueInfoCache *P)
353 : Parent(P), Val(V), BB(B), BBLV(LV) { }
355 bool markResult(bool changed) {
356 if (changed && BBLV.isOverdefined())
357 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
364 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
365 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
366 LVILatticeVal &Result);
367 bool hasBlockValue(Value *Val, BasicBlock *BB);
369 // These methods process one work item and may add more. A false value
370 // returned means that the work item was not completely processed and must
371 // be revisited after going through the new items.
372 bool solveBlockValue(Value *Val, BasicBlock *BB);
373 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
374 Value *Val, BasicBlock *BB);
375 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
376 PHINode *PN, BasicBlock *BB);
377 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
378 Instruction *BBI, BasicBlock *BB);
382 ValueCacheEntryTy &lookup(Value *V) {
383 return ValueCache[LVIValueHandle(V, this)];
387 /// getValueInBlock - This is the query interface to determine the lattice
388 /// value for the specified Value* at the end of the specified block.
389 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
391 /// getValueOnEdge - This is the query interface to determine the lattice
392 /// value for the specified Value* that is true on the specified edge.
393 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
395 /// threadEdge - This is the update interface to inform the cache that an
396 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
398 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
400 /// eraseBlock - This is part of the update interface to inform the cache
401 /// that a block has been deleted.
402 void eraseBlock(BasicBlock *BB);
404 /// clear - Empty the cache.
408 OverDefinedCache.clear();
411 } // end anonymous namespace
413 void LVIValueHandle::deleted() {
414 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
416 SmallVector<OverDefinedPairTy, 4> ToErase;
417 for (DenseSet<OverDefinedPairTy>::iterator
418 I = Parent->OverDefinedCache.begin(),
419 E = Parent->OverDefinedCache.end();
421 if (I->second == getValPtr())
422 ToErase.push_back(*I);
425 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
426 E = ToErase.end(); I != E; ++I)
427 Parent->OverDefinedCache.erase(*I);
429 // This erasure deallocates *this, so it MUST happen after we're done
430 // using any and all members of *this.
431 Parent->ValueCache.erase(*this);
434 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
435 // Shortcut if we have never seen this block.
436 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
437 if (I == SeenBlocks.end())
441 SmallVector<OverDefinedPairTy, 4> ToErase;
442 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
443 E = OverDefinedCache.end(); I != E; ++I) {
445 ToErase.push_back(*I);
448 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
449 E = ToErase.end(); I != E; ++I)
450 OverDefinedCache.erase(*I);
452 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
453 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
457 void LazyValueInfoCache::solve() {
458 while (!BlockValueStack.empty()) {
459 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
460 if (solveBlockValue(e.second, e.first)) {
461 assert(BlockValueStack.top() == e);
462 BlockValueStack.pop();
467 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
468 // If already a constant, there is nothing to compute.
469 if (isa<Constant>(Val))
472 LVIValueHandle ValHandle(Val, this);
473 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
474 ValueCache.find(ValHandle);
475 if (I == ValueCache.end()) return false;
476 return I->second.count(BB);
479 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
480 // If already a constant, there is nothing to compute.
481 if (Constant *VC = dyn_cast<Constant>(Val))
482 return LVILatticeVal::get(VC);
484 SeenBlocks.insert(BB);
485 return lookup(Val)[BB];
488 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
489 if (isa<Constant>(Val))
492 ValueCacheEntryTy &Cache = lookup(Val);
493 SeenBlocks.insert(BB);
494 LVILatticeVal &BBLV = Cache[BB];
496 // OverDefinedCacheUpdater is a helper object that will update
497 // the OverDefinedCache for us when this method exits. Make sure to
498 // call markResult on it as we exist, passing a bool to indicate if the
499 // cache needs updating, i.e. if we have solve a new value or not.
500 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
502 // If we've already computed this block's value, return it.
503 if (!BBLV.isUndefined()) {
504 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
506 // Since we're reusing a cached value here, we don't need to update the
507 // OverDefinedCahce. The cache will have been properly updated
508 // whenever the cached value was inserted.
509 ODCacheUpdater.markResult(false);
513 // Otherwise, this is the first time we're seeing this block. Reset the
514 // lattice value to overdefined, so that cycles will terminate and be
515 // conservatively correct.
516 BBLV.markOverdefined();
518 Instruction *BBI = dyn_cast<Instruction>(Val);
519 if (BBI == 0 || BBI->getParent() != BB) {
520 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
523 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
524 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
527 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
528 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
529 return ODCacheUpdater.markResult(true);
532 // We can only analyze the definitions of certain classes of instructions
533 // (integral binops and casts at the moment), so bail if this isn't one.
534 LVILatticeVal Result;
535 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
536 !BBI->getType()->isIntegerTy()) {
537 DEBUG(dbgs() << " compute BB '" << BB->getName()
538 << "' - overdefined because inst def found.\n");
539 BBLV.markOverdefined();
540 return ODCacheUpdater.markResult(true);
543 // FIXME: We're currently limited to binops with a constant RHS. This should
545 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
546 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
547 DEBUG(dbgs() << " compute BB '" << BB->getName()
548 << "' - overdefined because inst def found.\n");
550 BBLV.markOverdefined();
551 return ODCacheUpdater.markResult(true);
554 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
557 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
558 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
559 return L->getPointerAddressSpace() == 0 &&
560 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
562 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
563 return S->getPointerAddressSpace() == 0 &&
564 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
566 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
567 if (MI->isVolatile()) return false;
569 // FIXME: check whether it has a valuerange that excludes zero?
570 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
571 if (!Len || Len->isZero()) return false;
573 if (MI->getDestAddressSpace() == 0)
574 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
576 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
577 if (MTI->getSourceAddressSpace() == 0)
578 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
584 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
585 Value *Val, BasicBlock *BB) {
586 LVILatticeVal Result; // Start Undefined.
588 // If this is a pointer, and there's a load from that pointer in this BB,
589 // then we know that the pointer can't be NULL.
590 bool NotNull = false;
591 if (Val->getType()->isPointerTy()) {
592 if (isKnownNonNull(Val)) {
595 Value *UnderlyingVal = GetUnderlyingObject(Val);
596 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
597 // inside InstructionDereferencesPointer either.
598 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, NULL, 1)) {
599 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
601 if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
610 // If this is the entry block, we must be asking about an argument. The
611 // value is overdefined.
612 if (BB == &BB->getParent()->getEntryBlock()) {
613 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
615 PointerType *PTy = cast<PointerType>(Val->getType());
616 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
618 Result.markOverdefined();
624 // Loop over all of our predecessors, merging what we know from them into
626 bool EdgesMissing = false;
627 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
628 LVILatticeVal EdgeResult;
629 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
633 Result.mergeIn(EdgeResult);
635 // If we hit overdefined, exit early. The BlockVals entry is already set
637 if (Result.isOverdefined()) {
638 DEBUG(dbgs() << " compute BB '" << BB->getName()
639 << "' - overdefined because of pred.\n");
640 // If we previously determined that this is a pointer that can't be null
641 // then return that rather than giving up entirely.
643 PointerType *PTy = cast<PointerType>(Val->getType());
644 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
654 // Return the merged value, which is more precise than 'overdefined'.
655 assert(!Result.isOverdefined());
660 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
661 PHINode *PN, BasicBlock *BB) {
662 LVILatticeVal Result; // Start Undefined.
664 // Loop over all of our predecessors, merging what we know from them into
666 bool EdgesMissing = false;
667 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
668 BasicBlock *PhiBB = PN->getIncomingBlock(i);
669 Value *PhiVal = PN->getIncomingValue(i);
670 LVILatticeVal EdgeResult;
671 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
675 Result.mergeIn(EdgeResult);
677 // If we hit overdefined, exit early. The BlockVals entry is already set
679 if (Result.isOverdefined()) {
680 DEBUG(dbgs() << " compute BB '" << BB->getName()
681 << "' - overdefined because of pred.\n");
690 // Return the merged value, which is more precise than 'overdefined'.
691 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
696 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
699 // Figure out the range of the LHS. If that fails, bail.
700 if (!hasBlockValue(BBI->getOperand(0), BB)) {
701 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
705 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
706 if (!LHSVal.isConstantRange()) {
707 BBLV.markOverdefined();
711 ConstantRange LHSRange = LHSVal.getConstantRange();
712 ConstantRange RHSRange(1);
713 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
714 if (isa<BinaryOperator>(BBI)) {
715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
716 RHSRange = ConstantRange(RHS->getValue());
718 BBLV.markOverdefined();
723 // NOTE: We're currently limited by the set of operations that ConstantRange
724 // can evaluate symbolically. Enhancing that set will allows us to analyze
726 LVILatticeVal Result;
727 switch (BBI->getOpcode()) {
728 case Instruction::Add:
729 Result.markConstantRange(LHSRange.add(RHSRange));
731 case Instruction::Sub:
732 Result.markConstantRange(LHSRange.sub(RHSRange));
734 case Instruction::Mul:
735 Result.markConstantRange(LHSRange.multiply(RHSRange));
737 case Instruction::UDiv:
738 Result.markConstantRange(LHSRange.udiv(RHSRange));
740 case Instruction::Shl:
741 Result.markConstantRange(LHSRange.shl(RHSRange));
743 case Instruction::LShr:
744 Result.markConstantRange(LHSRange.lshr(RHSRange));
746 case Instruction::Trunc:
747 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
749 case Instruction::SExt:
750 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
752 case Instruction::ZExt:
753 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
755 case Instruction::BitCast:
756 Result.markConstantRange(LHSRange);
758 case Instruction::And:
759 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
761 case Instruction::Or:
762 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
765 // Unhandled instructions are overdefined.
767 DEBUG(dbgs() << " compute BB '" << BB->getName()
768 << "' - overdefined because inst def found.\n");
769 Result.markOverdefined();
777 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
778 /// Val is not constrained on the edge.
779 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
780 BasicBlock *BBTo, LVILatticeVal &Result) {
781 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
783 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
784 // If this is a conditional branch and only one successor goes to BBTo, then
785 // we maybe able to infer something from the condition.
786 if (BI->isConditional() &&
787 BI->getSuccessor(0) != BI->getSuccessor(1)) {
788 bool isTrueDest = BI->getSuccessor(0) == BBTo;
789 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
790 "BBTo isn't a successor of BBFrom");
792 // If V is the condition of the branch itself, then we know exactly what
794 if (BI->getCondition() == Val) {
795 Result = LVILatticeVal::get(ConstantInt::get(
796 Type::getInt1Ty(Val->getContext()), isTrueDest));
800 // If the condition of the branch is an equality comparison, we may be
801 // able to infer the value.
802 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
803 if (ICI && isa<Constant>(ICI->getOperand(1))) {
804 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
805 // We know that V has the RHS constant if this is a true SETEQ or
807 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
808 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
810 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
814 // Recognize the range checking idiom that InstCombine produces.
815 // (X-C1) u< C2 --> [C1, C1+C2)
816 ConstantInt *NegOffset = 0;
817 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
818 match(ICI->getOperand(0), m_Add(m_Specific(Val),
819 m_ConstantInt(NegOffset)));
821 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
822 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
823 // Calculate the range of values that would satisfy the comparison.
824 ConstantRange CmpRange(CI->getValue());
825 ConstantRange TrueValues =
826 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
828 if (NegOffset) // Apply the offset from above.
829 TrueValues = TrueValues.subtract(NegOffset->getValue());
831 // If we're interested in the false dest, invert the condition.
832 if (!isTrueDest) TrueValues = TrueValues.inverse();
834 Result = LVILatticeVal::getRange(TrueValues);
841 // If the edge was formed by a switch on the value, then we may know exactly
843 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
844 if (SI->getCondition() != Val)
847 bool DefaultCase = SI->getDefaultDest() == BBTo;
848 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
849 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
851 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
853 ConstantRange EdgeVal(i.getCaseValue()->getValue());
855 // It is possible that the default destination is the destination of
856 // some cases. There is no need to perform difference for those cases.
857 if (i.getCaseSuccessor() != BBTo)
858 EdgesVals = EdgesVals.difference(EdgeVal);
859 } else if (i.getCaseSuccessor() == BBTo)
860 EdgesVals = EdgesVals.unionWith(EdgeVal);
862 Result = LVILatticeVal::getRange(EdgesVals);
868 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
869 /// the basic block if the edge does not constraint Val.
870 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
871 BasicBlock *BBTo, LVILatticeVal &Result) {
872 // If already a constant, there is nothing to compute.
873 if (Constant *VC = dyn_cast<Constant>(Val)) {
874 Result = LVILatticeVal::get(VC);
878 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
879 if (!Result.isConstantRange() ||
880 Result.getConstantRange().getSingleElement())
883 // FIXME: this check should be moved to the beginning of the function when
884 // LVI better supports recursive values. Even for the single value case, we
885 // can intersect to detect dead code (an empty range).
886 if (!hasBlockValue(Val, BBFrom)) {
887 BlockValueStack.push(std::make_pair(BBFrom, Val));
891 // Try to intersect ranges of the BB and the constraint on the edge.
892 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
893 if (!InBlock.isConstantRange())
896 ConstantRange Range =
897 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
898 Result = LVILatticeVal::getRange(Range);
902 if (!hasBlockValue(Val, BBFrom)) {
903 BlockValueStack.push(std::make_pair(BBFrom, Val));
907 // if we couldn't compute the value on the edge, use the value from the BB
908 Result = getBlockValue(Val, BBFrom);
912 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
913 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
914 << BB->getName() << "'\n");
916 BlockValueStack.push(std::make_pair(BB, V));
918 LVILatticeVal Result = getBlockValue(V, BB);
920 DEBUG(dbgs() << " Result = " << Result << "\n");
924 LVILatticeVal LazyValueInfoCache::
925 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
926 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
927 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
929 LVILatticeVal Result;
930 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
932 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
934 assert(WasFastQuery && "More work to do after problem solved?");
937 DEBUG(dbgs() << " Result = " << Result << "\n");
941 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
942 BasicBlock *NewSucc) {
943 // When an edge in the graph has been threaded, values that we could not
944 // determine a value for before (i.e. were marked overdefined) may be possible
945 // to solve now. We do NOT try to proactively update these values. Instead,
946 // we clear their entries from the cache, and allow lazy updating to recompute
949 // The updating process is fairly simple: we need to dropped cached info
950 // for all values that were marked overdefined in OldSucc, and for those same
951 // values in any successor of OldSucc (except NewSucc) in which they were
952 // also marked overdefined.
953 std::vector<BasicBlock*> worklist;
954 worklist.push_back(OldSucc);
956 DenseSet<Value*> ClearSet;
957 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
958 E = OverDefinedCache.end(); I != E; ++I) {
959 if (I->first == OldSucc)
960 ClearSet.insert(I->second);
963 // Use a worklist to perform a depth-first search of OldSucc's successors.
964 // NOTE: We do not need a visited list since any blocks we have already
965 // visited will have had their overdefined markers cleared already, and we
966 // thus won't loop to their successors.
967 while (!worklist.empty()) {
968 BasicBlock *ToUpdate = worklist.back();
971 // Skip blocks only accessible through NewSucc.
972 if (ToUpdate == NewSucc) continue;
974 bool changed = false;
975 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
977 // If a value was marked overdefined in OldSucc, and is here too...
978 DenseSet<OverDefinedPairTy>::iterator OI =
979 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
980 if (OI == OverDefinedCache.end()) continue;
982 // Remove it from the caches.
983 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
984 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
986 assert(CI != Entry.end() && "Couldn't find entry to update?");
988 OverDefinedCache.erase(OI);
990 // If we removed anything, then we potentially need to update
991 // blocks successors too.
995 if (!changed) continue;
997 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1001 //===----------------------------------------------------------------------===//
1002 // LazyValueInfo Impl
1003 //===----------------------------------------------------------------------===//
1005 /// getCache - This lazily constructs the LazyValueInfoCache.
1006 static LazyValueInfoCache &getCache(void *&PImpl) {
1008 PImpl = new LazyValueInfoCache();
1009 return *static_cast<LazyValueInfoCache*>(PImpl);
1012 bool LazyValueInfo::runOnFunction(Function &F) {
1014 getCache(PImpl).clear();
1016 TD = getAnalysisIfAvailable<DataLayout>();
1017 TLI = &getAnalysis<TargetLibraryInfo>();
1023 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1024 AU.setPreservesAll();
1025 AU.addRequired<TargetLibraryInfo>();
1028 void LazyValueInfo::releaseMemory() {
1029 // If the cache was allocated, free it.
1031 delete &getCache(PImpl);
1036 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1037 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1039 if (Result.isConstant())
1040 return Result.getConstant();
1041 if (Result.isConstantRange()) {
1042 ConstantRange CR = Result.getConstantRange();
1043 if (const APInt *SingleVal = CR.getSingleElement())
1044 return ConstantInt::get(V->getContext(), *SingleVal);
1049 /// getConstantOnEdge - Determine whether the specified value is known to be a
1050 /// constant on the specified edge. Return null if not.
1051 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1053 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1055 if (Result.isConstant())
1056 return Result.getConstant();
1057 if (Result.isConstantRange()) {
1058 ConstantRange CR = Result.getConstantRange();
1059 if (const APInt *SingleVal = CR.getSingleElement())
1060 return ConstantInt::get(V->getContext(), *SingleVal);
1065 /// getPredicateOnEdge - Determine whether the specified value comparison
1066 /// with a constant is known to be true or false on the specified CFG edge.
1067 /// Pred is a CmpInst predicate.
1068 LazyValueInfo::Tristate
1069 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1070 BasicBlock *FromBB, BasicBlock *ToBB) {
1071 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1073 // If we know the value is a constant, evaluate the conditional.
1075 if (Result.isConstant()) {
1076 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1078 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1079 return ResCI->isZero() ? False : True;
1083 if (Result.isConstantRange()) {
1084 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1085 if (!CI) return Unknown;
1087 ConstantRange CR = Result.getConstantRange();
1088 if (Pred == ICmpInst::ICMP_EQ) {
1089 if (!CR.contains(CI->getValue()))
1092 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1094 } else if (Pred == ICmpInst::ICMP_NE) {
1095 if (!CR.contains(CI->getValue()))
1098 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1102 // Handle more complex predicates.
1103 ConstantRange TrueValues =
1104 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1105 if (TrueValues.contains(CR))
1107 if (TrueValues.inverse().contains(CR))
1112 if (Result.isNotConstant()) {
1113 // If this is an equality comparison, we can try to fold it knowing that
1115 if (Pred == ICmpInst::ICMP_EQ) {
1116 // !C1 == C -> false iff C1 == C.
1117 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1118 Result.getNotConstant(), C, TD,
1120 if (Res->isNullValue())
1122 } else if (Pred == ICmpInst::ICMP_NE) {
1123 // !C1 != C -> true iff C1 == C.
1124 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1125 Result.getNotConstant(), C, TD,
1127 if (Res->isNullValue())
1136 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1137 BasicBlock *NewSucc) {
1138 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1141 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1142 if (PImpl) getCache(PImpl).eraseBlock(BB);