1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
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 #include "llvm/Analysis/LazyValueInfo.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 using namespace PatternMatch;
38 #define DEBUG_TYPE "lazy-value-info"
40 char LazyValueInfo::ID = 0;
41 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
43 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
44 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
45 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
46 "Lazy Value Information Analysis", false, true)
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 /// This is the information tracked by LazyValueInfo for each value.
59 /// FIXME: This is basically just for bringup, this can be made a lot more rich
65 /// This Value has no known value yet.
68 /// This Value has a specific constant value.
71 /// This Value is known to not have the specified value.
74 /// The Value falls within this range.
77 /// This value is not known to be constant, and we know that it has a value.
81 /// Val: This stores the current lattice value along with the Constant* for
82 /// the constant if this is a 'constant' or 'notconstant' value.
88 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
90 static LVILatticeVal get(Constant *C) {
92 if (!isa<UndefValue>(C))
96 static LVILatticeVal getNot(Constant *C) {
98 if (!isa<UndefValue>(C))
99 Res.markNotConstant(C);
102 static LVILatticeVal getRange(ConstantRange CR) {
104 Res.markConstantRange(CR);
108 bool isUndefined() const { return Tag == undefined; }
109 bool isConstant() const { return Tag == constant; }
110 bool isNotConstant() const { return Tag == notconstant; }
111 bool isConstantRange() const { return Tag == constantrange; }
112 bool isOverdefined() const { return Tag == overdefined; }
114 Constant *getConstant() const {
115 assert(isConstant() && "Cannot get the constant of a non-constant!");
119 Constant *getNotConstant() const {
120 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
124 ConstantRange getConstantRange() const {
125 assert(isConstantRange() &&
126 "Cannot get the constant-range of a non-constant-range!");
130 /// Return true if this is a change in status.
131 bool markOverdefined() {
138 /// Return true if this is a change in status.
139 bool markConstant(Constant *V) {
140 assert(V && "Marking constant with NULL");
141 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
142 return markConstantRange(ConstantRange(CI->getValue()));
143 if (isa<UndefValue>(V))
146 assert((!isConstant() || getConstant() == V) &&
147 "Marking constant with different value");
148 assert(isUndefined());
154 /// Return true if this is a change in status.
155 bool markNotConstant(Constant *V) {
156 assert(V && "Marking constant with NULL");
157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
158 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
159 if (isa<UndefValue>(V))
162 assert((!isConstant() || getConstant() != V) &&
163 "Marking constant !constant with same value");
164 assert((!isNotConstant() || getNotConstant() == V) &&
165 "Marking !constant with different value");
166 assert(isUndefined() || isConstant());
172 /// Return true if this is a change in status.
173 bool markConstantRange(const ConstantRange NewR) {
174 if (isConstantRange()) {
175 if (NewR.isEmptySet())
176 return markOverdefined();
178 bool changed = Range != NewR;
183 assert(isUndefined());
184 if (NewR.isEmptySet())
185 return markOverdefined();
192 /// Merge the specified lattice value into this one, updating this
193 /// one and returning true if anything changed.
194 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
195 if (RHS.isUndefined() || isOverdefined()) return false;
196 if (RHS.isOverdefined()) return markOverdefined();
206 if (RHS.isConstant()) {
209 return markOverdefined();
212 if (RHS.isNotConstant()) {
214 return markOverdefined();
216 // Unless we can prove that the two Constants are different, we must
217 // move to overdefined.
218 if (ConstantInt *Res =
219 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
220 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
222 return markNotConstant(RHS.getNotConstant());
224 return markOverdefined();
227 // RHS is a ConstantRange, LHS is a non-integer Constant.
229 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
230 // a function. The correct result is to pick up RHS.
232 return markOverdefined();
235 if (isNotConstant()) {
236 if (RHS.isConstant()) {
238 return markOverdefined();
240 // Unless we can prove that the two Constants are different, we must
241 // move to overdefined.
242 if (ConstantInt *Res =
243 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
244 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
248 return markOverdefined();
251 if (RHS.isNotConstant()) {
254 return markOverdefined();
257 return markOverdefined();
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
271 } // end anonymous namespace.
274 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
287 return OS << "constant<" << *Val.getConstant() << '>';
291 //===----------------------------------------------------------------------===//
292 // LazyValueInfoCache Decl
293 //===----------------------------------------------------------------------===//
296 /// A callback value handle updates the cache when values are erased.
297 class LazyValueInfoCache;
298 struct LVIValueHandle : public CallbackVH {
299 LazyValueInfoCache *Parent;
301 LVIValueHandle(Value *V, LazyValueInfoCache *P)
302 : CallbackVH(V), Parent(P) { }
304 void deleted() override;
305 void allUsesReplacedWith(Value *V) override {
312 /// This is the cache kept by LazyValueInfo which
313 /// maintains information about queries across the clients' queries.
314 class LazyValueInfoCache {
315 /// This is all of the cached block information for exactly one Value*.
316 /// The entries are sorted by the BasicBlock* of the
317 /// entries, allowing us to do a lookup with a binary search.
318 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
320 /// This is all of the cached information for all values,
321 /// mapped from Value* to key information.
322 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
324 /// This tracks, on a per-block basis, the set of values that are
325 /// over-defined at the end of that block. This is required
326 /// for cache updating.
327 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
328 DenseSet<OverDefinedPairTy> OverDefinedCache;
330 /// Keep track of all blocks that we have ever seen, so we
331 /// don't spend time removing unused blocks from our caches.
332 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
334 /// This stack holds the state of the value solver during a query.
335 /// It basically emulates the callstack of the naive
336 /// recursive value lookup process.
337 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
339 /// Keeps track of which block-value pairs are in BlockValueStack.
340 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
342 /// Push BV onto BlockValueStack unless it's already in there.
343 /// Returns true on success.
344 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
345 if (!BlockValueSet.insert(BV).second)
346 return false; // It's already in the stack.
348 BlockValueStack.push(BV);
352 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
353 const DataLayout &DL; ///< A mandatory DataLayout
354 DominatorTree *DT; ///< An optional DT pointer.
356 friend struct LVIValueHandle;
358 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
359 SeenBlocks.insert(BB);
360 lookup(Val)[BB] = Result;
361 if (Result.isOverdefined())
362 OverDefinedCache.insert(std::make_pair(BB, Val));
365 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
366 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
367 LVILatticeVal &Result,
368 Instruction *CxtI = nullptr);
369 bool hasBlockValue(Value *Val, BasicBlock *BB);
371 // These methods process one work item and may add more. A false value
372 // returned means that the work item was not completely processed and must
373 // be revisited after going through the new items.
374 bool solveBlockValue(Value *Val, BasicBlock *BB);
375 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
376 Value *Val, BasicBlock *BB);
377 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
378 PHINode *PN, BasicBlock *BB);
379 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
380 Instruction *BBI, BasicBlock *BB);
381 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
386 ValueCacheEntryTy &lookup(Value *V) {
387 return ValueCache[LVIValueHandle(V, this)];
391 /// This is the query interface to determine the lattice
392 /// value for the specified Value* at the end of the specified block.
393 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
394 Instruction *CxtI = nullptr);
396 /// This is the query interface to determine the lattice
397 /// value for the specified Value* at the specified instruction (generally
398 /// from an assume intrinsic).
399 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
401 /// This is the query interface to determine the lattice
402 /// value for the specified Value* that is true on the specified edge.
403 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
404 Instruction *CxtI = nullptr);
406 /// This is the update interface to inform the cache that an edge from
407 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
408 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
410 /// This is part of the update interface to inform the cache
411 /// that a block has been deleted.
412 void eraseBlock(BasicBlock *BB);
414 /// clear - Empty the cache.
418 OverDefinedCache.clear();
421 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
422 DominatorTree *DT = nullptr)
423 : AC(AC), DL(DL), DT(DT) {}
425 } // end anonymous namespace
427 void LVIValueHandle::deleted() {
428 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
430 SmallVector<OverDefinedPairTy, 4> ToErase;
431 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
432 if (P.second == getValPtr())
433 ToErase.push_back(P);
434 for (const OverDefinedPairTy &P : ToErase)
435 Parent->OverDefinedCache.erase(P);
437 // This erasure deallocates *this, so it MUST happen after we're done
438 // using any and all members of *this.
439 Parent->ValueCache.erase(*this);
442 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
443 // Shortcut if we have never seen this block.
444 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
445 if (I == SeenBlocks.end())
449 SmallVector<OverDefinedPairTy, 4> ToErase;
450 for (const OverDefinedPairTy& P : OverDefinedCache)
452 ToErase.push_back(P);
453 for (const OverDefinedPairTy &P : ToErase)
454 OverDefinedCache.erase(P);
456 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
457 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
461 void LazyValueInfoCache::solve() {
462 while (!BlockValueStack.empty()) {
463 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
464 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
466 if (solveBlockValue(e.second, e.first)) {
467 // The work item was completely processed.
468 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
469 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
471 BlockValueStack.pop();
472 BlockValueSet.erase(e);
474 // More work needs to be done before revisiting.
475 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
480 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
481 // If already a constant, there is nothing to compute.
482 if (isa<Constant>(Val))
485 LVIValueHandle ValHandle(Val, this);
486 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
487 ValueCache.find(ValHandle);
488 if (I == ValueCache.end()) return false;
489 return I->second.count(BB);
492 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
493 // If already a constant, there is nothing to compute.
494 if (Constant *VC = dyn_cast<Constant>(Val))
495 return LVILatticeVal::get(VC);
497 SeenBlocks.insert(BB);
498 return lookup(Val)[BB];
501 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
502 if (isa<Constant>(Val))
505 if (lookup(Val).count(BB)) {
506 // If we have a cached value, use that.
507 DEBUG(dbgs() << " reuse BB '" << BB->getName()
508 << "' val=" << lookup(Val)[BB] << '\n');
510 // Since we're reusing a cached value, we don't need to update the
511 // OverDefinedCache. The cache will have been properly updated whenever the
512 // cached value was inserted.
516 // Hold off inserting this value into the Cache in case we have to return
517 // false and come back later.
520 Instruction *BBI = dyn_cast<Instruction>(Val);
521 if (!BBI || BBI->getParent() != BB) {
522 if (!solveBlockValueNonLocal(Res, Val, BB))
524 insertResult(Val, BB, Res);
528 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
529 if (!solveBlockValuePHINode(Res, PN, BB))
531 insertResult(Val, BB, Res);
535 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
536 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
537 insertResult(Val, BB, Res);
541 // We can only analyze the definitions of certain classes of instructions
542 // (integral binops and casts at the moment), so bail if this isn't one.
543 LVILatticeVal Result;
544 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
545 !BBI->getType()->isIntegerTy()) {
546 DEBUG(dbgs() << " compute BB '" << BB->getName()
547 << "' - overdefined because inst def found.\n");
548 Res.markOverdefined();
549 insertResult(Val, BB, Res);
553 // FIXME: We're currently limited to binops with a constant RHS. This should
555 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
556 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
557 DEBUG(dbgs() << " compute BB '" << BB->getName()
558 << "' - overdefined because inst def found.\n");
560 Res.markOverdefined();
561 insertResult(Val, BB, Res);
565 if (!solveBlockValueConstantRange(Res, BBI, BB))
567 insertResult(Val, BB, Res);
571 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
572 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
573 return L->getPointerAddressSpace() == 0 &&
574 GetUnderlyingObject(L->getPointerOperand(),
575 L->getModule()->getDataLayout()) == Ptr;
577 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
578 return S->getPointerAddressSpace() == 0 &&
579 GetUnderlyingObject(S->getPointerOperand(),
580 S->getModule()->getDataLayout()) == Ptr;
582 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
583 if (MI->isVolatile()) return false;
585 // FIXME: check whether it has a valuerange that excludes zero?
586 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
587 if (!Len || Len->isZero()) return false;
589 if (MI->getDestAddressSpace() == 0)
590 if (GetUnderlyingObject(MI->getRawDest(),
591 MI->getModule()->getDataLayout()) == Ptr)
593 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
594 if (MTI->getSourceAddressSpace() == 0)
595 if (GetUnderlyingObject(MTI->getRawSource(),
596 MTI->getModule()->getDataLayout()) == Ptr)
602 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
603 Value *Val, BasicBlock *BB) {
604 LVILatticeVal Result; // Start Undefined.
606 // If this is a pointer, and there's a load from that pointer in this BB,
607 // then we know that the pointer can't be NULL.
608 bool NotNull = false;
609 if (Val->getType()->isPointerTy()) {
610 if (isKnownNonNull(Val)) {
613 const DataLayout &DL = BB->getModule()->getDataLayout();
614 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
615 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
616 // inside InstructionDereferencesPointer either.
617 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
618 for (Instruction &I : *BB) {
619 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
628 // If this is the entry block, we must be asking about an argument. The
629 // value is overdefined.
630 if (BB == &BB->getParent()->getEntryBlock()) {
631 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
633 PointerType *PTy = cast<PointerType>(Val->getType());
634 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
636 Result.markOverdefined();
642 // Loop over all of our predecessors, merging what we know from them into
644 bool EdgesMissing = false;
645 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
646 LVILatticeVal EdgeResult;
647 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
651 Result.mergeIn(EdgeResult, DL);
653 // If we hit overdefined, exit early. The BlockVals entry is already set
655 if (Result.isOverdefined()) {
656 DEBUG(dbgs() << " compute BB '" << BB->getName()
657 << "' - overdefined because of pred.\n");
658 // If we previously determined that this is a pointer that can't be null
659 // then return that rather than giving up entirely.
661 PointerType *PTy = cast<PointerType>(Val->getType());
662 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
672 // Return the merged value, which is more precise than 'overdefined'.
673 assert(!Result.isOverdefined());
678 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
679 PHINode *PN, BasicBlock *BB) {
680 LVILatticeVal Result; // Start Undefined.
682 // Loop over all of our predecessors, merging what we know from them into
684 bool EdgesMissing = false;
685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
686 BasicBlock *PhiBB = PN->getIncomingBlock(i);
687 Value *PhiVal = PN->getIncomingValue(i);
688 LVILatticeVal EdgeResult;
689 // Note that we can provide PN as the context value to getEdgeValue, even
690 // though the results will be cached, because PN is the value being used as
691 // the cache key in the caller.
692 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
696 Result.mergeIn(EdgeResult, DL);
698 // If we hit overdefined, exit early. The BlockVals entry is already set
700 if (Result.isOverdefined()) {
701 DEBUG(dbgs() << " compute BB '" << BB->getName()
702 << "' - overdefined because of pred.\n");
711 // Return the merged value, which is more precise than 'overdefined'.
712 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
717 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
718 LVILatticeVal &Result,
719 bool isTrueDest = true);
721 // If we can determine a constant range for the value Val in the context
722 // provided by the instruction BBI, then merge it into BBLV. If we did find a
723 // constant range, return true.
724 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
727 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
731 for (auto &AssumeVH : AC->assumptions()) {
734 auto *I = cast<CallInst>(AssumeVH);
735 if (!isValidAssumeForContext(I, BBI, DT))
738 Value *C = I->getArgOperand(0);
739 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
740 LVILatticeVal Result;
741 if (getValueFromFromCondition(Val, ICI, Result)) {
742 if (BBLV.isOverdefined())
745 BBLV.mergeIn(Result, DL);
751 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
754 // Figure out the range of the LHS. If that fails, bail.
755 if (!hasBlockValue(BBI->getOperand(0), BB)) {
756 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
758 BBLV.markOverdefined();
762 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
763 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
764 if (!LHSVal.isConstantRange()) {
765 BBLV.markOverdefined();
769 ConstantRange LHSRange = LHSVal.getConstantRange();
770 ConstantRange RHSRange(1);
771 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
772 if (isa<BinaryOperator>(BBI)) {
773 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
774 RHSRange = ConstantRange(RHS->getValue());
776 BBLV.markOverdefined();
781 // NOTE: We're currently limited by the set of operations that ConstantRange
782 // can evaluate symbolically. Enhancing that set will allows us to analyze
784 LVILatticeVal Result;
785 switch (BBI->getOpcode()) {
786 case Instruction::Add:
787 Result.markConstantRange(LHSRange.add(RHSRange));
789 case Instruction::Sub:
790 Result.markConstantRange(LHSRange.sub(RHSRange));
792 case Instruction::Mul:
793 Result.markConstantRange(LHSRange.multiply(RHSRange));
795 case Instruction::UDiv:
796 Result.markConstantRange(LHSRange.udiv(RHSRange));
798 case Instruction::Shl:
799 Result.markConstantRange(LHSRange.shl(RHSRange));
801 case Instruction::LShr:
802 Result.markConstantRange(LHSRange.lshr(RHSRange));
804 case Instruction::Trunc:
805 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
807 case Instruction::SExt:
808 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
810 case Instruction::ZExt:
811 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
813 case Instruction::BitCast:
814 Result.markConstantRange(LHSRange);
816 case Instruction::And:
817 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
819 case Instruction::Or:
820 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
823 // Unhandled instructions are overdefined.
825 DEBUG(dbgs() << " compute BB '" << BB->getName()
826 << "' - overdefined because inst def found.\n");
827 Result.markOverdefined();
835 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
836 LVILatticeVal &Result, bool isTrueDest) {
837 if (ICI && isa<Constant>(ICI->getOperand(1))) {
838 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
839 // We know that V has the RHS constant if this is a true SETEQ or
841 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
842 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
844 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
848 // Recognize the range checking idiom that InstCombine produces.
849 // (X-C1) u< C2 --> [C1, C1+C2)
850 ConstantInt *NegOffset = nullptr;
851 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
852 match(ICI->getOperand(0), m_Add(m_Specific(Val),
853 m_ConstantInt(NegOffset)));
855 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
856 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
857 // Calculate the range of values that are allowed by the comparison
858 ConstantRange CmpRange(CI->getValue());
859 ConstantRange TrueValues =
860 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
862 if (NegOffset) // Apply the offset from above.
863 TrueValues = TrueValues.subtract(NegOffset->getValue());
865 // If we're interested in the false dest, invert the condition.
866 if (!isTrueDest) TrueValues = TrueValues.inverse();
868 Result = LVILatticeVal::getRange(TrueValues);
876 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
877 /// Val is not constrained on the edge.
878 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
879 BasicBlock *BBTo, LVILatticeVal &Result) {
880 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
882 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
883 // If this is a conditional branch and only one successor goes to BBTo, then
884 // we may be able to infer something from the condition.
885 if (BI->isConditional() &&
886 BI->getSuccessor(0) != BI->getSuccessor(1)) {
887 bool isTrueDest = BI->getSuccessor(0) == BBTo;
888 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
889 "BBTo isn't a successor of BBFrom");
891 // If V is the condition of the branch itself, then we know exactly what
893 if (BI->getCondition() == Val) {
894 Result = LVILatticeVal::get(ConstantInt::get(
895 Type::getInt1Ty(Val->getContext()), isTrueDest));
899 // If the condition of the branch is an equality comparison, we may be
900 // able to infer the value.
901 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
902 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
907 // If the edge was formed by a switch on the value, then we may know exactly
909 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
910 if (SI->getCondition() != Val)
913 bool DefaultCase = SI->getDefaultDest() == BBTo;
914 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
915 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
917 for (SwitchInst::CaseIt i : SI->cases()) {
918 ConstantRange EdgeVal(i.getCaseValue()->getValue());
920 // It is possible that the default destination is the destination of
921 // some cases. There is no need to perform difference for those cases.
922 if (i.getCaseSuccessor() != BBTo)
923 EdgesVals = EdgesVals.difference(EdgeVal);
924 } else if (i.getCaseSuccessor() == BBTo)
925 EdgesVals = EdgesVals.unionWith(EdgeVal);
927 Result = LVILatticeVal::getRange(EdgesVals);
933 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
934 /// the basic block if the edge does not constrain Val.
935 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
936 BasicBlock *BBTo, LVILatticeVal &Result,
938 // If already a constant, there is nothing to compute.
939 if (Constant *VC = dyn_cast<Constant>(Val)) {
940 Result = LVILatticeVal::get(VC);
944 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
945 if (!Result.isConstantRange() ||
946 Result.getConstantRange().getSingleElement())
949 // FIXME: this check should be moved to the beginning of the function when
950 // LVI better supports recursive values. Even for the single value case, we
951 // can intersect to detect dead code (an empty range).
952 if (!hasBlockValue(Val, BBFrom)) {
953 if (pushBlockValue(std::make_pair(BBFrom, Val)))
955 Result.markOverdefined();
959 // Try to intersect ranges of the BB and the constraint on the edge.
960 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
961 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
962 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
963 // and caching, below.
964 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
965 if (!InBlock.isConstantRange())
968 ConstantRange Range =
969 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
970 Result = LVILatticeVal::getRange(Range);
974 if (!hasBlockValue(Val, BBFrom)) {
975 if (pushBlockValue(std::make_pair(BBFrom, Val)))
977 Result.markOverdefined();
981 // If we couldn't compute the value on the edge, use the value from the BB.
982 Result = getBlockValue(Val, BBFrom);
983 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
984 // We can use the context instruction (generically the ultimate instruction
985 // the calling pass is trying to simplify) here, even though the result of
986 // this function is generally cached when called from the solve* functions
987 // (and that cached result might be used with queries using a different
988 // context instruction), because when this function is called from the solve*
989 // functions, the context instruction is not provided. When called from
990 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
991 // but then the result is not cached.
992 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
996 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
998 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
999 << BB->getName() << "'\n");
1001 assert(BlockValueStack.empty() && BlockValueSet.empty());
1002 pushBlockValue(std::make_pair(BB, V));
1005 LVILatticeVal Result = getBlockValue(V, BB);
1006 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1008 DEBUG(dbgs() << " Result = " << Result << "\n");
1012 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1013 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1014 << CxtI->getName() << "'\n");
1016 LVILatticeVal Result;
1017 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1019 DEBUG(dbgs() << " Result = " << Result << "\n");
1023 LVILatticeVal LazyValueInfoCache::
1024 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1025 Instruction *CxtI) {
1026 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1027 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1029 LVILatticeVal Result;
1030 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1032 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1034 assert(WasFastQuery && "More work to do after problem solved?");
1037 DEBUG(dbgs() << " Result = " << Result << "\n");
1041 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1042 BasicBlock *NewSucc) {
1043 // When an edge in the graph has been threaded, values that we could not
1044 // determine a value for before (i.e. were marked overdefined) may be possible
1045 // to solve now. We do NOT try to proactively update these values. Instead,
1046 // we clear their entries from the cache, and allow lazy updating to recompute
1047 // them when needed.
1049 // The updating process is fairly simple: we need to drop cached info
1050 // for all values that were marked overdefined in OldSucc, and for those same
1051 // values in any successor of OldSucc (except NewSucc) in which they were
1052 // also marked overdefined.
1053 std::vector<BasicBlock*> worklist;
1054 worklist.push_back(OldSucc);
1056 DenseSet<Value*> ClearSet;
1057 for (OverDefinedPairTy &P : OverDefinedCache)
1058 if (P.first == OldSucc)
1059 ClearSet.insert(P.second);
1061 // Use a worklist to perform a depth-first search of OldSucc's successors.
1062 // NOTE: We do not need a visited list since any blocks we have already
1063 // visited will have had their overdefined markers cleared already, and we
1064 // thus won't loop to their successors.
1065 while (!worklist.empty()) {
1066 BasicBlock *ToUpdate = worklist.back();
1067 worklist.pop_back();
1069 // Skip blocks only accessible through NewSucc.
1070 if (ToUpdate == NewSucc) continue;
1072 bool changed = false;
1073 for (Value *V : ClearSet) {
1074 // If a value was marked overdefined in OldSucc, and is here too...
1075 DenseSet<OverDefinedPairTy>::iterator OI =
1076 OverDefinedCache.find(std::make_pair(ToUpdate, V));
1077 if (OI == OverDefinedCache.end()) continue;
1079 // Remove it from the caches.
1080 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
1081 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1083 assert(CI != Entry.end() && "Couldn't find entry to update?");
1085 OverDefinedCache.erase(OI);
1087 // If we removed anything, then we potentially need to update
1088 // blocks successors too.
1092 if (!changed) continue;
1094 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1098 //===----------------------------------------------------------------------===//
1099 // LazyValueInfo Impl
1100 //===----------------------------------------------------------------------===//
1102 /// This lazily constructs the LazyValueInfoCache.
1103 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1104 const DataLayout *DL,
1105 DominatorTree *DT = nullptr) {
1107 assert(DL && "getCache() called with a null DataLayout");
1108 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1110 return *static_cast<LazyValueInfoCache*>(PImpl);
1113 bool LazyValueInfo::runOnFunction(Function &F) {
1114 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1115 const DataLayout &DL = F.getParent()->getDataLayout();
1117 DominatorTreeWrapperPass *DTWP =
1118 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1119 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1121 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1124 getCache(PImpl, AC, &DL, DT).clear();
1130 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1131 AU.setPreservesAll();
1132 AU.addRequired<AssumptionCacheTracker>();
1133 AU.addRequired<TargetLibraryInfoWrapperPass>();
1136 void LazyValueInfo::releaseMemory() {
1137 // If the cache was allocated, free it.
1139 delete &getCache(PImpl, AC, nullptr);
1144 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1145 Instruction *CxtI) {
1146 const DataLayout &DL = BB->getModule()->getDataLayout();
1147 LVILatticeVal Result =
1148 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1150 if (Result.isConstant())
1151 return Result.getConstant();
1152 if (Result.isConstantRange()) {
1153 ConstantRange CR = Result.getConstantRange();
1154 if (const APInt *SingleVal = CR.getSingleElement())
1155 return ConstantInt::get(V->getContext(), *SingleVal);
1160 /// Determine whether the specified value is known to be a
1161 /// constant on the specified edge. Return null if not.
1162 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1164 Instruction *CxtI) {
1165 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1166 LVILatticeVal Result =
1167 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1169 if (Result.isConstant())
1170 return Result.getConstant();
1171 if (Result.isConstantRange()) {
1172 ConstantRange CR = Result.getConstantRange();
1173 if (const APInt *SingleVal = CR.getSingleElement())
1174 return ConstantInt::get(V->getContext(), *SingleVal);
1179 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1180 LVILatticeVal &Result,
1181 const DataLayout &DL,
1182 TargetLibraryInfo *TLI) {
1184 // If we know the value is a constant, evaluate the conditional.
1185 Constant *Res = nullptr;
1186 if (Result.isConstant()) {
1187 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1189 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1190 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1191 return LazyValueInfo::Unknown;
1194 if (Result.isConstantRange()) {
1195 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1196 if (!CI) return LazyValueInfo::Unknown;
1198 ConstantRange CR = Result.getConstantRange();
1199 if (Pred == ICmpInst::ICMP_EQ) {
1200 if (!CR.contains(CI->getValue()))
1201 return LazyValueInfo::False;
1203 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1204 return LazyValueInfo::True;
1205 } else if (Pred == ICmpInst::ICMP_NE) {
1206 if (!CR.contains(CI->getValue()))
1207 return LazyValueInfo::True;
1209 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1210 return LazyValueInfo::False;
1213 // Handle more complex predicates.
1214 ConstantRange TrueValues =
1215 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1216 if (TrueValues.contains(CR))
1217 return LazyValueInfo::True;
1218 if (TrueValues.inverse().contains(CR))
1219 return LazyValueInfo::False;
1220 return LazyValueInfo::Unknown;
1223 if (Result.isNotConstant()) {
1224 // If this is an equality comparison, we can try to fold it knowing that
1226 if (Pred == ICmpInst::ICMP_EQ) {
1227 // !C1 == C -> false iff C1 == C.
1228 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1229 Result.getNotConstant(), C, DL,
1231 if (Res->isNullValue())
1232 return LazyValueInfo::False;
1233 } else if (Pred == ICmpInst::ICMP_NE) {
1234 // !C1 != C -> true iff C1 == C.
1235 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1236 Result.getNotConstant(), C, DL,
1238 if (Res->isNullValue())
1239 return LazyValueInfo::True;
1241 return LazyValueInfo::Unknown;
1244 return LazyValueInfo::Unknown;
1247 /// Determine whether the specified value comparison with a constant is known to
1248 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1249 LazyValueInfo::Tristate
1250 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1251 BasicBlock *FromBB, BasicBlock *ToBB,
1252 Instruction *CxtI) {
1253 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1254 LVILatticeVal Result =
1255 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1257 return getPredicateResult(Pred, C, Result, DL, TLI);
1260 LazyValueInfo::Tristate
1261 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1262 Instruction *CxtI) {
1263 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1264 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1266 return getPredicateResult(Pred, C, Result, DL, TLI);
1269 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1270 BasicBlock *NewSucc) {
1272 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1273 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1277 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1279 const DataLayout &DL = BB->getModule()->getDataLayout();
1280 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);