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 final : 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 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
321 /// This is all of the cached information for all values,
322 /// mapped from Value* to key information.
323 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
325 /// This tracks, on a per-block basis, the set of values that are
326 /// over-defined at the end of that block. This is required
327 /// for cache updating.
328 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
330 OverDefinedCacheTy OverDefinedCache;
332 /// 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 /// This stack holds the state of the value solver during a query.
337 /// It basically emulates the callstack of the naive
338 /// recursive value lookup process.
339 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
341 /// Keeps track of which block-value pairs are in BlockValueStack.
342 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
344 /// Push BV onto BlockValueStack unless it's already in there.
345 /// Returns true on success.
346 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
347 if (!BlockValueSet.insert(BV).second)
348 return false; // It's already in the stack.
350 BlockValueStack.push(BV);
354 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
355 const DataLayout &DL; ///< A mandatory DataLayout
356 DominatorTree *DT; ///< An optional DT pointer.
358 friend struct LVIValueHandle;
360 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
361 SeenBlocks.insert(BB);
362 lookup(Val)[BB] = Result;
363 if (Result.isOverdefined())
364 OverDefinedCache[BB].insert(Val);
367 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
368 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
369 LVILatticeVal &Result,
370 Instruction *CxtI = nullptr);
371 bool hasBlockValue(Value *Val, BasicBlock *BB);
373 // These methods process one work item and may add more. A false value
374 // returned means that the work item was not completely processed and must
375 // be revisited after going through the new items.
376 bool solveBlockValue(Value *Val, BasicBlock *BB);
377 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
378 Value *Val, BasicBlock *BB);
379 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
380 PHINode *PN, BasicBlock *BB);
381 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
382 Instruction *BBI, BasicBlock *BB);
383 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
388 ValueCacheEntryTy &lookup(Value *V) {
389 return ValueCache[LVIValueHandle(V, this)];
393 /// This is the query interface to determine the lattice
394 /// value for the specified Value* at the end of the specified block.
395 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
396 Instruction *CxtI = nullptr);
398 /// This is the query interface to determine the lattice
399 /// value for the specified Value* at the specified instruction (generally
400 /// from an assume intrinsic).
401 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
403 /// This is the query interface to determine the lattice
404 /// value for the specified Value* that is true on the specified edge.
405 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
406 Instruction *CxtI = nullptr);
408 /// This is the update interface to inform the cache that an edge from
409 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
410 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
412 /// This is part of the update interface to inform the cache
413 /// that a block has been deleted.
414 void eraseBlock(BasicBlock *BB);
416 /// clear - Empty the cache.
420 OverDefinedCache.clear();
423 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
424 DominatorTree *DT = nullptr)
425 : AC(AC), DL(DL), DT(DT) {}
427 } // end anonymous namespace
429 void LVIValueHandle::deleted() {
430 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
431 for (auto &I : Parent->OverDefinedCache) {
432 SmallPtrSetImpl<Value *> &ValueSet = I.second;
433 if (ValueSet.count(getValPtr()))
434 ValueSet.erase(getValPtr());
435 if (ValueSet.empty())
436 ToErase.push_back(I.first);
438 for (auto &BB : ToErase)
439 Parent->OverDefinedCache.erase(BB);
441 // This erasure deallocates *this, so it MUST happen after we're done
442 // using any and all members of *this.
443 Parent->ValueCache.erase(*this);
446 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
447 // Shortcut if we have never seen this block.
448 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
449 if (I == SeenBlocks.end())
453 auto ODI = OverDefinedCache.find(BB);
454 if (ODI != OverDefinedCache.end())
455 OverDefinedCache.erase(ODI);
457 for (auto 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 auto I = ValueCache.find(ValHandle);
487 if (I == ValueCache.end()) return false;
488 return I->second.count(BB);
491 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
492 // If already a constant, there is nothing to compute.
493 if (Constant *VC = dyn_cast<Constant>(Val))
494 return LVILatticeVal::get(VC);
496 SeenBlocks.insert(BB);
497 return lookup(Val)[BB];
500 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
501 if (isa<Constant>(Val))
504 if (lookup(Val).count(BB)) {
505 // If we have a cached value, use that.
506 DEBUG(dbgs() << " reuse BB '" << BB->getName()
507 << "' val=" << lookup(Val)[BB] << '\n');
509 // Since we're reusing a cached value, we don't need to update the
510 // OverDefinedCache. The cache will have been properly updated whenever the
511 // cached value was inserted.
515 // Hold off inserting this value into the Cache in case we have to return
516 // false and come back later.
519 Instruction *BBI = dyn_cast<Instruction>(Val);
520 if (!BBI || BBI->getParent() != BB) {
521 if (!solveBlockValueNonLocal(Res, Val, BB))
523 insertResult(Val, BB, Res);
527 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
528 if (!solveBlockValuePHINode(Res, PN, BB))
530 insertResult(Val, BB, Res);
534 // If this value is a nonnull pointer, record it's range and bailout.
535 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
536 if (PT && isKnownNonNull(BBI)) {
537 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
538 insertResult(Val, BB, Res);
542 // We can only analyze the definitions of certain classes of instructions
543 // (integral binops and casts at the moment), so bail if this isn't one.
544 LVILatticeVal Result;
545 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
546 !BBI->getType()->isIntegerTy()) {
547 DEBUG(dbgs() << " compute BB '" << BB->getName()
548 << "' - overdefined because inst def found.\n");
549 Res.markOverdefined();
550 insertResult(Val, BB, Res);
554 // FIXME: We're currently limited to binops with a constant RHS. This should
556 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
557 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
558 DEBUG(dbgs() << " compute BB '" << BB->getName()
559 << "' - overdefined because inst def found.\n");
561 Res.markOverdefined();
562 insertResult(Val, BB, Res);
566 if (!solveBlockValueConstantRange(Res, BBI, BB))
568 insertResult(Val, BB, Res);
572 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
573 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
574 return L->getPointerAddressSpace() == 0 &&
575 GetUnderlyingObject(L->getPointerOperand(),
576 L->getModule()->getDataLayout()) == Ptr;
578 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
579 return S->getPointerAddressSpace() == 0 &&
580 GetUnderlyingObject(S->getPointerOperand(),
581 S->getModule()->getDataLayout()) == Ptr;
583 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
584 if (MI->isVolatile()) return false;
586 // FIXME: check whether it has a valuerange that excludes zero?
587 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
588 if (!Len || Len->isZero()) return false;
590 if (MI->getDestAddressSpace() == 0)
591 if (GetUnderlyingObject(MI->getRawDest(),
592 MI->getModule()->getDataLayout()) == Ptr)
594 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
595 if (MTI->getSourceAddressSpace() == 0)
596 if (GetUnderlyingObject(MTI->getRawSource(),
597 MTI->getModule()->getDataLayout()) == Ptr)
603 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
604 Value *Val, BasicBlock *BB) {
605 LVILatticeVal Result; // Start Undefined.
607 // If this is a pointer, and there's a load from that pointer in this BB,
608 // then we know that the pointer can't be NULL.
609 bool NotNull = false;
610 if (Val->getType()->isPointerTy()) {
611 if (isKnownNonNull(Val)) {
614 const DataLayout &DL = BB->getModule()->getDataLayout();
615 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
616 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
617 // inside InstructionDereferencesPointer either.
618 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
619 for (Instruction &I : *BB) {
620 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
629 // If this is the entry block, we must be asking about an argument. The
630 // value is overdefined.
631 if (BB == &BB->getParent()->getEntryBlock()) {
632 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
634 PointerType *PTy = cast<PointerType>(Val->getType());
635 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
637 Result.markOverdefined();
643 // Loop over all of our predecessors, merging what we know from them into
645 bool EdgesMissing = false;
646 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
647 LVILatticeVal EdgeResult;
648 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
652 Result.mergeIn(EdgeResult, DL);
654 // If we hit overdefined, exit early. The BlockVals entry is already set
656 if (Result.isOverdefined()) {
657 DEBUG(dbgs() << " compute BB '" << BB->getName()
658 << "' - overdefined because of pred.\n");
659 // If we previously determined that this is a pointer that can't be null
660 // then return that rather than giving up entirely.
662 PointerType *PTy = cast<PointerType>(Val->getType());
663 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
673 // Return the merged value, which is more precise than 'overdefined'.
674 assert(!Result.isOverdefined());
679 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
680 PHINode *PN, BasicBlock *BB) {
681 LVILatticeVal Result; // Start Undefined.
683 // Loop over all of our predecessors, merging what we know from them into
685 bool EdgesMissing = false;
686 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
687 BasicBlock *PhiBB = PN->getIncomingBlock(i);
688 Value *PhiVal = PN->getIncomingValue(i);
689 LVILatticeVal EdgeResult;
690 // Note that we can provide PN as the context value to getEdgeValue, even
691 // though the results will be cached, because PN is the value being used as
692 // the cache key in the caller.
693 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
697 Result.mergeIn(EdgeResult, DL);
699 // If we hit overdefined, exit early. The BlockVals entry is already set
701 if (Result.isOverdefined()) {
702 DEBUG(dbgs() << " compute BB '" << BB->getName()
703 << "' - overdefined because of pred.\n");
712 // Return the merged value, which is more precise than 'overdefined'.
713 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
718 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
719 LVILatticeVal &Result,
720 bool isTrueDest = true);
722 // If we can determine a constant range for the value Val in the context
723 // provided by the instruction BBI, then merge it into BBLV. If we did find a
724 // constant range, return true.
725 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
728 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
732 for (auto &AssumeVH : AC->assumptions()) {
735 auto *I = cast<CallInst>(AssumeVH);
736 if (!isValidAssumeForContext(I, BBI, DT))
739 Value *C = I->getArgOperand(0);
740 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
741 LVILatticeVal Result;
742 if (getValueFromFromCondition(Val, ICI, Result)) {
743 if (BBLV.isOverdefined())
746 BBLV.mergeIn(Result, DL);
752 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
755 // Figure out the range of the LHS. If that fails, bail.
756 if (!hasBlockValue(BBI->getOperand(0), BB)) {
757 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
759 BBLV.markOverdefined();
763 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
764 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
765 if (!LHSVal.isConstantRange()) {
766 BBLV.markOverdefined();
770 ConstantRange LHSRange = LHSVal.getConstantRange();
771 ConstantRange RHSRange(1);
772 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
773 if (isa<BinaryOperator>(BBI)) {
774 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
775 RHSRange = ConstantRange(RHS->getValue());
777 BBLV.markOverdefined();
782 // NOTE: We're currently limited by the set of operations that ConstantRange
783 // can evaluate symbolically. Enhancing that set will allows us to analyze
785 LVILatticeVal Result;
786 switch (BBI->getOpcode()) {
787 case Instruction::Add:
788 Result.markConstantRange(LHSRange.add(RHSRange));
790 case Instruction::Sub:
791 Result.markConstantRange(LHSRange.sub(RHSRange));
793 case Instruction::Mul:
794 Result.markConstantRange(LHSRange.multiply(RHSRange));
796 case Instruction::UDiv:
797 Result.markConstantRange(LHSRange.udiv(RHSRange));
799 case Instruction::Shl:
800 Result.markConstantRange(LHSRange.shl(RHSRange));
802 case Instruction::LShr:
803 Result.markConstantRange(LHSRange.lshr(RHSRange));
805 case Instruction::Trunc:
806 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
808 case Instruction::SExt:
809 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
811 case Instruction::ZExt:
812 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
814 case Instruction::BitCast:
815 Result.markConstantRange(LHSRange);
817 case Instruction::And:
818 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
820 case Instruction::Or:
821 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
824 // Unhandled instructions are overdefined.
826 DEBUG(dbgs() << " compute BB '" << BB->getName()
827 << "' - overdefined because inst def found.\n");
828 Result.markOverdefined();
836 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
837 LVILatticeVal &Result, bool isTrueDest) {
838 if (ICI && isa<Constant>(ICI->getOperand(1))) {
839 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
840 // We know that V has the RHS constant if this is a true SETEQ or
842 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
843 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
845 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
849 // Recognize the range checking idiom that InstCombine produces.
850 // (X-C1) u< C2 --> [C1, C1+C2)
851 ConstantInt *NegOffset = nullptr;
852 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
853 match(ICI->getOperand(0), m_Add(m_Specific(Val),
854 m_ConstantInt(NegOffset)));
856 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
857 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
858 // Calculate the range of values that are allowed by the comparison
859 ConstantRange CmpRange(CI->getValue());
860 ConstantRange TrueValues =
861 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
863 if (NegOffset) // Apply the offset from above.
864 TrueValues = TrueValues.subtract(NegOffset->getValue());
866 // If we're interested in the false dest, invert the condition.
867 if (!isTrueDest) TrueValues = TrueValues.inverse();
869 Result = LVILatticeVal::getRange(TrueValues);
877 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
878 /// Val is not constrained on the edge.
879 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
880 BasicBlock *BBTo, LVILatticeVal &Result) {
881 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
883 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
884 // If this is a conditional branch and only one successor goes to BBTo, then
885 // we may be able to infer something from the condition.
886 if (BI->isConditional() &&
887 BI->getSuccessor(0) != BI->getSuccessor(1)) {
888 bool isTrueDest = BI->getSuccessor(0) == BBTo;
889 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
890 "BBTo isn't a successor of BBFrom");
892 // If V is the condition of the branch itself, then we know exactly what
894 if (BI->getCondition() == Val) {
895 Result = LVILatticeVal::get(ConstantInt::get(
896 Type::getInt1Ty(Val->getContext()), isTrueDest));
900 // If the condition of the branch is an equality comparison, we may be
901 // able to infer the value.
902 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
903 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
908 // If the edge was formed by a switch on the value, then we may know exactly
910 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
911 if (SI->getCondition() != Val)
914 bool DefaultCase = SI->getDefaultDest() == BBTo;
915 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
916 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
918 for (SwitchInst::CaseIt i : SI->cases()) {
919 ConstantRange EdgeVal(i.getCaseValue()->getValue());
921 // It is possible that the default destination is the destination of
922 // some cases. There is no need to perform difference for those cases.
923 if (i.getCaseSuccessor() != BBTo)
924 EdgesVals = EdgesVals.difference(EdgeVal);
925 } else if (i.getCaseSuccessor() == BBTo)
926 EdgesVals = EdgesVals.unionWith(EdgeVal);
928 Result = LVILatticeVal::getRange(EdgesVals);
934 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
935 /// the basic block if the edge does not constrain Val.
936 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
937 BasicBlock *BBTo, LVILatticeVal &Result,
939 // If already a constant, there is nothing to compute.
940 if (Constant *VC = dyn_cast<Constant>(Val)) {
941 Result = LVILatticeVal::get(VC);
945 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
946 if (!Result.isConstantRange() ||
947 Result.getConstantRange().getSingleElement())
950 // FIXME: this check should be moved to the beginning of the function when
951 // LVI better supports recursive values. Even for the single value case, we
952 // can intersect to detect dead code (an empty range).
953 if (!hasBlockValue(Val, BBFrom)) {
954 if (pushBlockValue(std::make_pair(BBFrom, Val)))
956 Result.markOverdefined();
960 // Try to intersect ranges of the BB and the constraint on the edge.
961 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
962 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
963 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
964 // and caching, below.
965 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
966 if (!InBlock.isConstantRange())
969 ConstantRange Range =
970 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
971 Result = LVILatticeVal::getRange(Range);
975 if (!hasBlockValue(Val, BBFrom)) {
976 if (pushBlockValue(std::make_pair(BBFrom, Val)))
978 Result.markOverdefined();
982 // If we couldn't compute the value on the edge, use the value from the BB.
983 Result = getBlockValue(Val, BBFrom);
984 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
985 // We can use the context instruction (generically the ultimate instruction
986 // the calling pass is trying to simplify) here, even though the result of
987 // this function is generally cached when called from the solve* functions
988 // (and that cached result might be used with queries using a different
989 // context instruction), because when this function is called from the solve*
990 // functions, the context instruction is not provided. When called from
991 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
992 // but then the result is not cached.
993 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
997 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
999 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1000 << BB->getName() << "'\n");
1002 assert(BlockValueStack.empty() && BlockValueSet.empty());
1003 pushBlockValue(std::make_pair(BB, V));
1006 LVILatticeVal Result = getBlockValue(V, BB);
1007 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1009 DEBUG(dbgs() << " Result = " << Result << "\n");
1013 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1014 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1015 << CxtI->getName() << "'\n");
1017 LVILatticeVal Result;
1018 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1020 DEBUG(dbgs() << " Result = " << Result << "\n");
1024 LVILatticeVal LazyValueInfoCache::
1025 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1026 Instruction *CxtI) {
1027 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1028 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1030 LVILatticeVal Result;
1031 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1033 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1035 assert(WasFastQuery && "More work to do after problem solved?");
1038 DEBUG(dbgs() << " Result = " << Result << "\n");
1042 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1043 BasicBlock *NewSucc) {
1044 // When an edge in the graph has been threaded, values that we could not
1045 // determine a value for before (i.e. were marked overdefined) may be
1046 // possible to solve now. We do NOT try to proactively update these values.
1047 // Instead, we clear their entries from the cache, and allow lazy updating to
1048 // recompute them when needed.
1050 // The updating process is fairly simple: we need to drop cached info
1051 // for all values that were marked overdefined in OldSucc, and for those same
1052 // values in any successor of OldSucc (except NewSucc) in which they were
1053 // also marked overdefined.
1054 std::vector<BasicBlock*> worklist;
1055 worklist.push_back(OldSucc);
1057 auto I = OverDefinedCache.find(OldSucc);
1058 if (I == OverDefinedCache.end())
1059 return; // Nothing to process here.
1060 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
1062 // Use a worklist to perform a depth-first search of OldSucc's successors.
1063 // NOTE: We do not need a visited list since any blocks we have already
1064 // visited will have had their overdefined markers cleared already, and we
1065 // thus won't loop to their successors.
1066 while (!worklist.empty()) {
1067 BasicBlock *ToUpdate = worklist.back();
1068 worklist.pop_back();
1070 // Skip blocks only accessible through NewSucc.
1071 if (ToUpdate == NewSucc) continue;
1073 bool changed = false;
1074 for (Value *V : ValsToClear) {
1075 // If a value was marked overdefined in OldSucc, and is here too...
1076 auto OI = OverDefinedCache.find(ToUpdate);
1077 if (OI == OverDefinedCache.end())
1079 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1080 if (!ValueSet.count(V))
1083 // Remove it from the caches.
1084 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
1085 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1087 assert(CI != Entry.end() && "Couldn't find entry to update?");
1090 if (ValueSet.empty())
1091 OverDefinedCache.erase(OI);
1093 // If we removed anything, then we potentially need to update
1094 // blocks successors too.
1098 if (!changed) continue;
1100 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1104 //===----------------------------------------------------------------------===//
1105 // LazyValueInfo Impl
1106 //===----------------------------------------------------------------------===//
1108 /// This lazily constructs the LazyValueInfoCache.
1109 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1110 const DataLayout *DL,
1111 DominatorTree *DT = nullptr) {
1113 assert(DL && "getCache() called with a null DataLayout");
1114 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1116 return *static_cast<LazyValueInfoCache*>(PImpl);
1119 bool LazyValueInfo::runOnFunction(Function &F) {
1120 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1121 const DataLayout &DL = F.getParent()->getDataLayout();
1123 DominatorTreeWrapperPass *DTWP =
1124 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1125 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1127 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1130 getCache(PImpl, AC, &DL, DT).clear();
1136 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1137 AU.setPreservesAll();
1138 AU.addRequired<AssumptionCacheTracker>();
1139 AU.addRequired<TargetLibraryInfoWrapperPass>();
1142 void LazyValueInfo::releaseMemory() {
1143 // If the cache was allocated, free it.
1145 delete &getCache(PImpl, AC, nullptr);
1150 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1151 Instruction *CxtI) {
1152 const DataLayout &DL = BB->getModule()->getDataLayout();
1153 LVILatticeVal Result =
1154 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1156 if (Result.isConstant())
1157 return Result.getConstant();
1158 if (Result.isConstantRange()) {
1159 ConstantRange CR = Result.getConstantRange();
1160 if (const APInt *SingleVal = CR.getSingleElement())
1161 return ConstantInt::get(V->getContext(), *SingleVal);
1166 /// Determine whether the specified value is known to be a
1167 /// constant on the specified edge. Return null if not.
1168 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1170 Instruction *CxtI) {
1171 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1172 LVILatticeVal Result =
1173 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1175 if (Result.isConstant())
1176 return Result.getConstant();
1177 if (Result.isConstantRange()) {
1178 ConstantRange CR = Result.getConstantRange();
1179 if (const APInt *SingleVal = CR.getSingleElement())
1180 return ConstantInt::get(V->getContext(), *SingleVal);
1185 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1186 LVILatticeVal &Result,
1187 const DataLayout &DL,
1188 TargetLibraryInfo *TLI) {
1190 // If we know the value is a constant, evaluate the conditional.
1191 Constant *Res = nullptr;
1192 if (Result.isConstant()) {
1193 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1195 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1196 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1197 return LazyValueInfo::Unknown;
1200 if (Result.isConstantRange()) {
1201 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1202 if (!CI) return LazyValueInfo::Unknown;
1204 ConstantRange CR = Result.getConstantRange();
1205 if (Pred == ICmpInst::ICMP_EQ) {
1206 if (!CR.contains(CI->getValue()))
1207 return LazyValueInfo::False;
1209 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1210 return LazyValueInfo::True;
1211 } else if (Pred == ICmpInst::ICMP_NE) {
1212 if (!CR.contains(CI->getValue()))
1213 return LazyValueInfo::True;
1215 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1216 return LazyValueInfo::False;
1219 // Handle more complex predicates.
1220 ConstantRange TrueValues =
1221 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1222 if (TrueValues.contains(CR))
1223 return LazyValueInfo::True;
1224 if (TrueValues.inverse().contains(CR))
1225 return LazyValueInfo::False;
1226 return LazyValueInfo::Unknown;
1229 if (Result.isNotConstant()) {
1230 // If this is an equality comparison, we can try to fold it knowing that
1232 if (Pred == ICmpInst::ICMP_EQ) {
1233 // !C1 == C -> false iff C1 == C.
1234 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1235 Result.getNotConstant(), C, DL,
1237 if (Res->isNullValue())
1238 return LazyValueInfo::False;
1239 } else if (Pred == ICmpInst::ICMP_NE) {
1240 // !C1 != C -> true iff C1 == C.
1241 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1242 Result.getNotConstant(), C, DL,
1244 if (Res->isNullValue())
1245 return LazyValueInfo::True;
1247 return LazyValueInfo::Unknown;
1250 return LazyValueInfo::Unknown;
1253 /// Determine whether the specified value comparison with a constant is known to
1254 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1255 LazyValueInfo::Tristate
1256 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1257 BasicBlock *FromBB, BasicBlock *ToBB,
1258 Instruction *CxtI) {
1259 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1260 LVILatticeVal Result =
1261 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1263 return getPredicateResult(Pred, C, Result, DL, TLI);
1266 LazyValueInfo::Tristate
1267 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1268 Instruction *CxtI) {
1269 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1270 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1271 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1275 // TODO: Move this logic inside getValueAt so that it can be cached rather
1276 // than re-queried on each call. This would also allow us to merge the
1277 // underlying lattice values to get more information.
1279 BasicBlock *BB = CxtI->getParent();
1281 // Function entry or an unreachable block. Bail to avoid confusing
1283 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1287 // If V is a PHI node in the same block as the context, we need to ask
1288 // questions about the predicate as applied to the incoming value along
1289 // each edge. This is useful for eliminating cases where the predicate is
1290 // known along all incoming edges.
1291 if (auto *PHI = dyn_cast<PHINode>(V))
1292 if (PHI->getParent() == BB) {
1293 Tristate Baseline = Unknown;
1294 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1295 Value *Incoming = PHI->getIncomingValue(i);
1296 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1297 // Note that PredBB may be BB itself.
1298 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1301 // Keep going as long as we've seen a consistent known result for
1303 Baseline = (i == 0) ? Result /* First iteration */
1304 : (Baseline == Result ? Baseline : Unknown); /* All others */
1305 if (Baseline == Unknown)
1308 if (Baseline != Unknown)
1312 // For a comparison where the V is outside this block, it's possible
1313 // that we've branched on it before. Look to see if the value is known
1314 // on all incoming edges.
1315 if (!isa<Instruction>(V) ||
1316 cast<Instruction>(V)->getParent() != BB) {
1317 // For predecessor edge, determine if the comparison is true or false
1318 // on that edge. If they're all true or all false, we can conclude
1319 // the value of the comparison in this block.
1320 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1321 if (Baseline != Unknown) {
1322 // Check that all remaining incoming values match the first one.
1323 while (++PI != PE) {
1324 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1325 if (Ret != Baseline) break;
1327 // If we terminated early, then one of the values didn't match.
1337 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1338 BasicBlock *NewSucc) {
1340 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1341 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1345 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1347 const DataLayout &DL = BB->getModule()->getDataLayout();
1348 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);