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/AssumptionTracker.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLibraryInfo.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(AssumptionTracker)
44 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
45 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
46 "Lazy Value Information Analysis", false, true)
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
60 /// FIXME: This is basically just for bringup, this can be made a lot more rich
66 /// undefined - This Value has no known value yet.
69 /// constant - This Value has a specific constant value.
71 /// notconstant - This Value is known to not have the specified value.
74 /// constantrange - The Value falls within this range.
77 /// overdefined - This value is not known to be constant, and we know that
82 /// Val: This stores the current lattice value along with the Constant* for
83 /// the constant if this is a 'constant' or 'notconstant' value.
89 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
91 static LVILatticeVal get(Constant *C) {
93 if (!isa<UndefValue>(C))
97 static LVILatticeVal getNot(Constant *C) {
99 if (!isa<UndefValue>(C))
100 Res.markNotConstant(C);
103 static LVILatticeVal getRange(ConstantRange CR) {
105 Res.markConstantRange(CR);
109 bool isUndefined() const { return Tag == undefined; }
110 bool isConstant() const { return Tag == constant; }
111 bool isNotConstant() const { return Tag == notconstant; }
112 bool isConstantRange() const { return Tag == constantrange; }
113 bool isOverdefined() const { return Tag == overdefined; }
115 Constant *getConstant() const {
116 assert(isConstant() && "Cannot get the constant of a non-constant!");
120 Constant *getNotConstant() const {
121 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
125 ConstantRange getConstantRange() const {
126 assert(isConstantRange() &&
127 "Cannot get the constant-range of a non-constant-range!");
131 /// markOverdefined - Return true if this is a change in status.
132 bool markOverdefined() {
139 /// markConstant - Return true if this is a change in status.
140 bool markConstant(Constant *V) {
141 assert(V && "Marking constant with NULL");
142 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
143 return markConstantRange(ConstantRange(CI->getValue()));
144 if (isa<UndefValue>(V))
147 assert((!isConstant() || getConstant() == V) &&
148 "Marking constant with different value");
149 assert(isUndefined());
155 /// markNotConstant - Return true if this is a change in status.
156 bool markNotConstant(Constant *V) {
157 assert(V && "Marking constant with NULL");
158 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
159 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
160 if (isa<UndefValue>(V))
163 assert((!isConstant() || getConstant() != V) &&
164 "Marking constant !constant with same value");
165 assert((!isNotConstant() || getNotConstant() == V) &&
166 "Marking !constant with different value");
167 assert(isUndefined() || isConstant());
173 /// markConstantRange - Return true if this is a change in status.
174 bool markConstantRange(const ConstantRange NewR) {
175 if (isConstantRange()) {
176 if (NewR.isEmptySet())
177 return markOverdefined();
179 bool changed = Range != NewR;
184 assert(isUndefined());
185 if (NewR.isEmptySet())
186 return markOverdefined();
193 /// mergeIn - Merge the specified lattice value into this one, updating this
194 /// one and returning true if anything changed.
195 bool mergeIn(const LVILatticeVal &RHS) {
196 if (RHS.isUndefined() || isOverdefined()) return false;
197 if (RHS.isOverdefined()) return markOverdefined();
207 if (RHS.isConstant()) {
210 return markOverdefined();
213 if (RHS.isNotConstant()) {
215 return markOverdefined();
217 // Unless we can prove that the two Constants are different, we must
218 // move to overdefined.
219 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
220 if (ConstantInt *Res = dyn_cast<ConstantInt>(
221 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
223 RHS.getNotConstant())))
225 return markNotConstant(RHS.getNotConstant());
227 return markOverdefined();
230 // RHS is a ConstantRange, LHS is a non-integer Constant.
232 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
233 // a function. The correct result is to pick up RHS.
235 return markOverdefined();
238 if (isNotConstant()) {
239 if (RHS.isConstant()) {
241 return markOverdefined();
243 // Unless we can prove that the two Constants are different, we must
244 // move to overdefined.
245 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
246 if (ConstantInt *Res = dyn_cast<ConstantInt>(
247 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
253 return markOverdefined();
256 if (RHS.isNotConstant()) {
259 return markOverdefined();
262 return markOverdefined();
265 assert(isConstantRange() && "New LVILattice type?");
266 if (!RHS.isConstantRange())
267 return markOverdefined();
269 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
270 if (NewR.isFullSet())
271 return markOverdefined();
272 return markConstantRange(NewR);
276 } // end anonymous namespace.
279 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
281 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
282 if (Val.isUndefined())
283 return OS << "undefined";
284 if (Val.isOverdefined())
285 return OS << "overdefined";
287 if (Val.isNotConstant())
288 return OS << "notconstant<" << *Val.getNotConstant() << '>';
289 else if (Val.isConstantRange())
290 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
291 << Val.getConstantRange().getUpper() << '>';
292 return OS << "constant<" << *Val.getConstant() << '>';
296 //===----------------------------------------------------------------------===//
297 // LazyValueInfoCache Decl
298 //===----------------------------------------------------------------------===//
301 /// LVIValueHandle - A callback value handle updates the cache when
302 /// values are erased.
303 class LazyValueInfoCache;
304 struct LVIValueHandle : public CallbackVH {
305 LazyValueInfoCache *Parent;
307 LVIValueHandle(Value *V, LazyValueInfoCache *P)
308 : CallbackVH(V), Parent(P) { }
310 void deleted() override;
311 void allUsesReplacedWith(Value *V) override {
318 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
319 /// maintains information about queries across the clients' queries.
320 class LazyValueInfoCache {
321 /// ValueCacheEntryTy - This is all of the cached block information for
322 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
323 /// entries, allowing us to do a lookup with a binary search.
324 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
326 /// ValueCache - This is all of the cached information for all values,
327 /// mapped from Value* to key information.
328 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
330 /// OverDefinedCache - This tracks, on a per-block basis, the set of
331 /// values that are over-defined at the end of that block. This is required
332 /// for cache updating.
333 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
334 DenseSet<OverDefinedPairTy> OverDefinedCache;
336 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
337 /// don't spend time removing unused blocks from our caches.
338 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
340 /// BlockValueStack - This stack holds the state of the value solver
341 /// during a query. It basically emulates the callstack of the naive
342 /// recursive value lookup process.
343 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
345 /// BlockValueSet - Keeps track of which block-value pairs are in
347 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
349 /// pushBlockValue - Push BV onto BlockValueStack unless it's already in
350 /// there. Returns true on success.
351 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
352 if (BlockValueSet.count(BV))
353 return false; // It's already in the stack.
355 BlockValueStack.push(BV);
356 BlockValueSet.insert(BV);
360 /// A pointer to the cache of @llvm.assume calls.
361 AssumptionTracker *AT;
362 /// An optional DL pointer.
363 const DataLayout *DL;
364 /// An optional DT pointer.
367 friend struct LVIValueHandle;
369 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
370 SeenBlocks.insert(BB);
371 lookup(Val)[BB] = Result;
372 if (Result.isOverdefined())
373 OverDefinedCache.insert(std::make_pair(BB, Val));
376 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
377 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
378 LVILatticeVal &Result,
379 Instruction *CxtI = nullptr);
380 bool hasBlockValue(Value *Val, BasicBlock *BB);
382 // These methods process one work item and may add more. A false value
383 // returned means that the work item was not completely processed and must
384 // be revisited after going through the new items.
385 bool solveBlockValue(Value *Val, BasicBlock *BB);
386 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
387 Value *Val, BasicBlock *BB);
388 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
389 PHINode *PN, BasicBlock *BB);
390 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
391 Instruction *BBI, BasicBlock *BB);
392 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
397 ValueCacheEntryTy &lookup(Value *V) {
398 return ValueCache[LVIValueHandle(V, this)];
402 /// getValueInBlock - This is the query interface to determine the lattice
403 /// value for the specified Value* at the end of the specified block.
404 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
405 Instruction *CxtI = nullptr);
407 /// getValueAt - This is the query interface to determine the lattice
408 /// value for the specified Value* at the specified instruction (generally
409 /// from an assume intrinsic).
410 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
412 /// getValueOnEdge - This is the query interface to determine the lattice
413 /// value for the specified Value* that is true on the specified edge.
414 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
415 Instruction *CxtI = nullptr);
417 /// threadEdge - This is the update interface to inform the cache that an
418 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
420 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
422 /// eraseBlock - This is part of the update interface to inform the cache
423 /// that a block has been deleted.
424 void eraseBlock(BasicBlock *BB);
426 /// clear - Empty the cache.
430 OverDefinedCache.clear();
433 LazyValueInfoCache(AssumptionTracker *AT,
434 const DataLayout *DL = nullptr,
435 DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {}
437 } // end anonymous namespace
439 void LVIValueHandle::deleted() {
440 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
442 SmallVector<OverDefinedPairTy, 4> ToErase;
443 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
444 if (P.second == getValPtr())
445 ToErase.push_back(P);
446 for (const OverDefinedPairTy &P : ToErase)
447 Parent->OverDefinedCache.erase(P);
449 // This erasure deallocates *this, so it MUST happen after we're done
450 // using any and all members of *this.
451 Parent->ValueCache.erase(*this);
454 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
455 // Shortcut if we have never seen this block.
456 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
457 if (I == SeenBlocks.end())
461 SmallVector<OverDefinedPairTy, 4> ToErase;
462 for (const OverDefinedPairTy& P : OverDefinedCache)
464 ToErase.push_back(P);
465 for (const OverDefinedPairTy &P : ToErase)
466 OverDefinedCache.erase(P);
468 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
469 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
473 void LazyValueInfoCache::solve() {
474 while (!BlockValueStack.empty()) {
475 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
476 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
478 if (solveBlockValue(e.second, e.first)) {
479 // The work item was completely processed.
480 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
481 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
483 BlockValueStack.pop();
484 BlockValueSet.erase(e);
486 // More work needs to be done before revisiting.
487 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
492 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
493 // If already a constant, there is nothing to compute.
494 if (isa<Constant>(Val))
497 LVIValueHandle ValHandle(Val, this);
498 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
499 ValueCache.find(ValHandle);
500 if (I == ValueCache.end()) return false;
501 return I->second.count(BB);
504 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
505 // If already a constant, there is nothing to compute.
506 if (Constant *VC = dyn_cast<Constant>(Val))
507 return LVILatticeVal::get(VC);
509 SeenBlocks.insert(BB);
510 return lookup(Val)[BB];
513 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
514 if (isa<Constant>(Val))
517 if (lookup(Val).count(BB)) {
518 // If we have a cached value, use that.
519 DEBUG(dbgs() << " reuse BB '" << BB->getName()
520 << "' val=" << lookup(Val)[BB] << '\n');
522 // Since we're reusing a cached value, we don't need to update the
523 // OverDefinedCache. The cache will have been properly updated whenever the
524 // cached value was inserted.
528 // Hold off inserting this value into the Cache in case we have to return
529 // false and come back later.
532 Instruction *BBI = dyn_cast<Instruction>(Val);
533 if (!BBI || BBI->getParent() != BB) {
534 if (!solveBlockValueNonLocal(Res, Val, BB))
536 insertResult(Val, BB, Res);
540 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
541 if (!solveBlockValuePHINode(Res, PN, BB))
543 insertResult(Val, BB, Res);
547 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
548 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
549 insertResult(Val, BB, Res);
553 // We can only analyze the definitions of certain classes of instructions
554 // (integral binops and casts at the moment), so bail if this isn't one.
555 LVILatticeVal Result;
556 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
557 !BBI->getType()->isIntegerTy()) {
558 DEBUG(dbgs() << " compute BB '" << BB->getName()
559 << "' - overdefined because inst def found.\n");
560 Res.markOverdefined();
561 insertResult(Val, BB, Res);
565 // FIXME: We're currently limited to binops with a constant RHS. This should
567 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
568 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
569 DEBUG(dbgs() << " compute BB '" << BB->getName()
570 << "' - overdefined because inst def found.\n");
572 Res.markOverdefined();
573 insertResult(Val, BB, Res);
577 if (!solveBlockValueConstantRange(Res, BBI, BB))
579 insertResult(Val, BB, Res);
583 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
584 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
585 return L->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
588 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
589 return S->getPointerAddressSpace() == 0 &&
590 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
592 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
593 if (MI->isVolatile()) return false;
595 // FIXME: check whether it has a valuerange that excludes zero?
596 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
597 if (!Len || Len->isZero()) return false;
599 if (MI->getDestAddressSpace() == 0)
600 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
602 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
603 if (MTI->getSourceAddressSpace() == 0)
604 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
610 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
611 Value *Val, BasicBlock *BB) {
612 LVILatticeVal Result; // Start Undefined.
614 // If this is a pointer, and there's a load from that pointer in this BB,
615 // then we know that the pointer can't be NULL.
616 bool NotNull = false;
617 if (Val->getType()->isPointerTy()) {
618 if (isKnownNonNull(Val)) {
621 Value *UnderlyingVal = GetUnderlyingObject(Val);
622 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
623 // inside InstructionDereferencesPointer either.
624 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
625 for (Instruction &I : *BB) {
626 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
635 // If this is the entry block, we must be asking about an argument. The
636 // value is overdefined.
637 if (BB == &BB->getParent()->getEntryBlock()) {
638 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
640 PointerType *PTy = cast<PointerType>(Val->getType());
641 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
643 Result.markOverdefined();
649 // Loop over all of our predecessors, merging what we know from them into
651 bool EdgesMissing = false;
652 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
653 LVILatticeVal EdgeResult;
654 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
658 Result.mergeIn(EdgeResult);
660 // If we hit overdefined, exit early. The BlockVals entry is already set
662 if (Result.isOverdefined()) {
663 DEBUG(dbgs() << " compute BB '" << BB->getName()
664 << "' - overdefined because of pred.\n");
665 // If we previously determined that this is a pointer that can't be null
666 // then return that rather than giving up entirely.
668 PointerType *PTy = cast<PointerType>(Val->getType());
669 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
679 // Return the merged value, which is more precise than 'overdefined'.
680 assert(!Result.isOverdefined());
685 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
686 PHINode *PN, BasicBlock *BB) {
687 LVILatticeVal Result; // Start Undefined.
689 // Loop over all of our predecessors, merging what we know from them into
691 bool EdgesMissing = false;
692 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
693 BasicBlock *PhiBB = PN->getIncomingBlock(i);
694 Value *PhiVal = PN->getIncomingValue(i);
695 LVILatticeVal EdgeResult;
696 // Note that we can provide PN as the context value to getEdgeValue, even
697 // though the results will be cached, because PN is the value being used as
698 // the cache key in the caller.
699 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
703 Result.mergeIn(EdgeResult);
705 // If we hit overdefined, exit early. The BlockVals entry is already set
707 if (Result.isOverdefined()) {
708 DEBUG(dbgs() << " compute BB '" << BB->getName()
709 << "' - overdefined because of pred.\n");
718 // Return the merged value, which is more precise than 'overdefined'.
719 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
724 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
725 LVILatticeVal &Result,
726 bool isTrueDest = true);
728 // If we can determine a constant range for the value Val in the context
729 // provided by the instruction BBI, then merge it into BBLV. If we did find a
730 // constant range, return true.
731 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
734 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
738 for (auto &I : AT->assumptions(BBI->getParent()->getParent())) {
739 if (!isValidAssumeForContext(I, BBI, DL, DT))
742 Value *C = I->getArgOperand(0);
743 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
744 LVILatticeVal Result;
745 if (getValueFromFromCondition(Val, ICI, Result)) {
746 if (BBLV.isOverdefined())
749 BBLV.mergeIn(Result);
755 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
758 // Figure out the range of the LHS. If that fails, bail.
759 if (!hasBlockValue(BBI->getOperand(0), BB)) {
760 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
762 BBLV.markOverdefined();
766 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
767 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
768 if (!LHSVal.isConstantRange()) {
769 BBLV.markOverdefined();
773 ConstantRange LHSRange = LHSVal.getConstantRange();
774 ConstantRange RHSRange(1);
775 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
776 if (isa<BinaryOperator>(BBI)) {
777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
778 RHSRange = ConstantRange(RHS->getValue());
780 BBLV.markOverdefined();
785 // NOTE: We're currently limited by the set of operations that ConstantRange
786 // can evaluate symbolically. Enhancing that set will allows us to analyze
788 LVILatticeVal Result;
789 switch (BBI->getOpcode()) {
790 case Instruction::Add:
791 Result.markConstantRange(LHSRange.add(RHSRange));
793 case Instruction::Sub:
794 Result.markConstantRange(LHSRange.sub(RHSRange));
796 case Instruction::Mul:
797 Result.markConstantRange(LHSRange.multiply(RHSRange));
799 case Instruction::UDiv:
800 Result.markConstantRange(LHSRange.udiv(RHSRange));
802 case Instruction::Shl:
803 Result.markConstantRange(LHSRange.shl(RHSRange));
805 case Instruction::LShr:
806 Result.markConstantRange(LHSRange.lshr(RHSRange));
808 case Instruction::Trunc:
809 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
811 case Instruction::SExt:
812 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
814 case Instruction::ZExt:
815 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
817 case Instruction::BitCast:
818 Result.markConstantRange(LHSRange);
820 case Instruction::And:
821 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
823 case Instruction::Or:
824 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
827 // Unhandled instructions are overdefined.
829 DEBUG(dbgs() << " compute BB '" << BB->getName()
830 << "' - overdefined because inst def found.\n");
831 Result.markOverdefined();
839 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
840 LVILatticeVal &Result, bool isTrueDest) {
841 if (ICI && isa<Constant>(ICI->getOperand(1))) {
842 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
843 // We know that V has the RHS constant if this is a true SETEQ or
845 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
846 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
848 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
852 // Recognize the range checking idiom that InstCombine produces.
853 // (X-C1) u< C2 --> [C1, C1+C2)
854 ConstantInt *NegOffset = nullptr;
855 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
856 match(ICI->getOperand(0), m_Add(m_Specific(Val),
857 m_ConstantInt(NegOffset)));
859 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
860 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
861 // Calculate the range of values that would satisfy the comparison.
862 ConstantRange CmpRange(CI->getValue());
863 ConstantRange TrueValues =
864 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
866 if (NegOffset) // Apply the offset from above.
867 TrueValues = TrueValues.subtract(NegOffset->getValue());
869 // If we're interested in the false dest, invert the condition.
870 if (!isTrueDest) TrueValues = TrueValues.inverse();
872 Result = LVILatticeVal::getRange(TrueValues);
880 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
881 /// Val is not constrained on the edge.
882 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
883 BasicBlock *BBTo, LVILatticeVal &Result) {
884 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
886 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
887 // If this is a conditional branch and only one successor goes to BBTo, then
888 // we maybe able to infer something from the condition.
889 if (BI->isConditional() &&
890 BI->getSuccessor(0) != BI->getSuccessor(1)) {
891 bool isTrueDest = BI->getSuccessor(0) == BBTo;
892 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
893 "BBTo isn't a successor of BBFrom");
895 // If V is the condition of the branch itself, then we know exactly what
897 if (BI->getCondition() == Val) {
898 Result = LVILatticeVal::get(ConstantInt::get(
899 Type::getInt1Ty(Val->getContext()), isTrueDest));
903 // If the condition of the branch is an equality comparison, we may be
904 // able to infer the value.
905 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
906 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
911 // If the edge was formed by a switch on the value, then we may know exactly
913 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
914 if (SI->getCondition() != Val)
917 bool DefaultCase = SI->getDefaultDest() == BBTo;
918 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
919 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
921 for (SwitchInst::CaseIt i : SI->cases()) {
922 ConstantRange EdgeVal(i.getCaseValue()->getValue());
924 // It is possible that the default destination is the destination of
925 // some cases. There is no need to perform difference for those cases.
926 if (i.getCaseSuccessor() != BBTo)
927 EdgesVals = EdgesVals.difference(EdgeVal);
928 } else if (i.getCaseSuccessor() == BBTo)
929 EdgesVals = EdgesVals.unionWith(EdgeVal);
931 Result = LVILatticeVal::getRange(EdgesVals);
937 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
938 /// the basic block if the edge does not constraint Val.
939 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
940 BasicBlock *BBTo, LVILatticeVal &Result,
942 // If already a constant, there is nothing to compute.
943 if (Constant *VC = dyn_cast<Constant>(Val)) {
944 Result = LVILatticeVal::get(VC);
948 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
949 if (!Result.isConstantRange() ||
950 Result.getConstantRange().getSingleElement())
953 // FIXME: this check should be moved to the beginning of the function when
954 // LVI better supports recursive values. Even for the single value case, we
955 // can intersect to detect dead code (an empty range).
956 if (!hasBlockValue(Val, BBFrom)) {
957 if (pushBlockValue(std::make_pair(BBFrom, Val)))
959 Result.markOverdefined();
963 // Try to intersect ranges of the BB and the constraint on the edge.
964 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
965 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
966 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
967 // and caching, below.
968 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
969 if (!InBlock.isConstantRange())
972 ConstantRange Range =
973 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
974 Result = LVILatticeVal::getRange(Range);
978 if (!hasBlockValue(Val, BBFrom)) {
979 if (pushBlockValue(std::make_pair(BBFrom, Val)))
981 Result.markOverdefined();
985 // If we couldn't compute the value on the edge, use the value from the BB.
986 Result = getBlockValue(Val, BBFrom);
987 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
988 // We can use the context instruction (generically the ultimate instruction
989 // the calling pass is trying to simplify) here, even though the result of
990 // this function is generally cached when called from the solve* functions
991 // (and that cached result might be used with queries using a different
992 // context instruction), because when this function is called from the solve*
993 // functions, the context instruction is not provided. When called from
994 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
995 // but then the result is not cached.
996 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
1000 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1001 Instruction *CxtI) {
1002 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1003 << BB->getName() << "'\n");
1005 assert(BlockValueStack.empty() && BlockValueSet.empty());
1006 pushBlockValue(std::make_pair(BB, V));
1009 LVILatticeVal Result = getBlockValue(V, BB);
1010 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1012 DEBUG(dbgs() << " Result = " << Result << "\n");
1016 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1017 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1018 << CxtI->getName() << "'\n");
1020 LVILatticeVal Result;
1021 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1023 DEBUG(dbgs() << " Result = " << Result << "\n");
1027 LVILatticeVal LazyValueInfoCache::
1028 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1029 Instruction *CxtI) {
1030 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1031 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1033 LVILatticeVal Result;
1034 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1036 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1038 assert(WasFastQuery && "More work to do after problem solved?");
1041 DEBUG(dbgs() << " Result = " << Result << "\n");
1045 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1046 BasicBlock *NewSucc) {
1047 // When an edge in the graph has been threaded, values that we could not
1048 // determine a value for before (i.e. were marked overdefined) may be possible
1049 // to solve now. We do NOT try to proactively update these values. Instead,
1050 // we clear their entries from the cache, and allow lazy updating to recompute
1051 // them when needed.
1053 // The updating process is fairly simple: we need to drop cached info
1054 // for all values that were marked overdefined in OldSucc, and for those same
1055 // values in any successor of OldSucc (except NewSucc) in which they were
1056 // also marked overdefined.
1057 std::vector<BasicBlock*> worklist;
1058 worklist.push_back(OldSucc);
1060 DenseSet<Value*> ClearSet;
1061 for (OverDefinedPairTy &P : OverDefinedCache)
1062 if (P.first == OldSucc)
1063 ClearSet.insert(P.second);
1065 // Use a worklist to perform a depth-first search of OldSucc's successors.
1066 // NOTE: We do not need a visited list since any blocks we have already
1067 // visited will have had their overdefined markers cleared already, and we
1068 // thus won't loop to their successors.
1069 while (!worklist.empty()) {
1070 BasicBlock *ToUpdate = worklist.back();
1071 worklist.pop_back();
1073 // Skip blocks only accessible through NewSucc.
1074 if (ToUpdate == NewSucc) continue;
1076 bool changed = false;
1077 for (Value *V : ClearSet) {
1078 // If a value was marked overdefined in OldSucc, and is here too...
1079 DenseSet<OverDefinedPairTy>::iterator OI =
1080 OverDefinedCache.find(std::make_pair(ToUpdate, V));
1081 if (OI == OverDefinedCache.end()) continue;
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?");
1089 OverDefinedCache.erase(OI);
1091 // If we removed anything, then we potentially need to update
1092 // blocks successors too.
1096 if (!changed) continue;
1098 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1102 //===----------------------------------------------------------------------===//
1103 // LazyValueInfo Impl
1104 //===----------------------------------------------------------------------===//
1106 /// getCache - This lazily constructs the LazyValueInfoCache.
1107 static LazyValueInfoCache &getCache(void *&PImpl,
1108 AssumptionTracker *AT,
1109 const DataLayout *DL = nullptr,
1110 DominatorTree *DT = nullptr) {
1112 PImpl = new LazyValueInfoCache(AT, DL, DT);
1113 return *static_cast<LazyValueInfoCache*>(PImpl);
1116 bool LazyValueInfo::runOnFunction(Function &F) {
1117 AT = &getAnalysis<AssumptionTracker>();
1119 DominatorTreeWrapperPass *DTWP =
1120 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1121 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1123 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1124 DL = DLP ? &DLP->getDataLayout() : nullptr;
1126 TLI = &getAnalysis<TargetLibraryInfo>();
1129 getCache(PImpl, AT, DL, DT).clear();
1135 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1136 AU.setPreservesAll();
1137 AU.addRequired<AssumptionTracker>();
1138 AU.addRequired<TargetLibraryInfo>();
1141 void LazyValueInfo::releaseMemory() {
1142 // If the cache was allocated, free it.
1144 delete &getCache(PImpl, AT);
1149 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1150 Instruction *CxtI) {
1151 LVILatticeVal Result =
1152 getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI);
1154 if (Result.isConstant())
1155 return Result.getConstant();
1156 if (Result.isConstantRange()) {
1157 ConstantRange CR = Result.getConstantRange();
1158 if (const APInt *SingleVal = CR.getSingleElement())
1159 return ConstantInt::get(V->getContext(), *SingleVal);
1164 /// getConstantOnEdge - Determine whether the specified value is known to be a
1165 /// constant on the specified edge. Return null if not.
1166 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1168 Instruction *CxtI) {
1169 LVILatticeVal Result =
1170 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1172 if (Result.isConstant())
1173 return Result.getConstant();
1174 if (Result.isConstantRange()) {
1175 ConstantRange CR = Result.getConstantRange();
1176 if (const APInt *SingleVal = CR.getSingleElement())
1177 return ConstantInt::get(V->getContext(), *SingleVal);
1182 static LazyValueInfo::Tristate
1183 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1184 const DataLayout *DL, TargetLibraryInfo *TLI) {
1186 // If we know the value is a constant, evaluate the conditional.
1187 Constant *Res = nullptr;
1188 if (Result.isConstant()) {
1189 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1191 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1192 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1193 return LazyValueInfo::Unknown;
1196 if (Result.isConstantRange()) {
1197 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1198 if (!CI) return LazyValueInfo::Unknown;
1200 ConstantRange CR = Result.getConstantRange();
1201 if (Pred == ICmpInst::ICMP_EQ) {
1202 if (!CR.contains(CI->getValue()))
1203 return LazyValueInfo::False;
1205 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1206 return LazyValueInfo::True;
1207 } else if (Pred == ICmpInst::ICMP_NE) {
1208 if (!CR.contains(CI->getValue()))
1209 return LazyValueInfo::True;
1211 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1212 return LazyValueInfo::False;
1215 // Handle more complex predicates.
1216 ConstantRange TrueValues =
1217 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1218 if (TrueValues.contains(CR))
1219 return LazyValueInfo::True;
1220 if (TrueValues.inverse().contains(CR))
1221 return LazyValueInfo::False;
1222 return LazyValueInfo::Unknown;
1225 if (Result.isNotConstant()) {
1226 // If this is an equality comparison, we can try to fold it knowing that
1228 if (Pred == ICmpInst::ICMP_EQ) {
1229 // !C1 == C -> false iff C1 == C.
1230 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1231 Result.getNotConstant(), C, DL,
1233 if (Res->isNullValue())
1234 return LazyValueInfo::False;
1235 } else if (Pred == ICmpInst::ICMP_NE) {
1236 // !C1 != C -> true iff C1 == C.
1237 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1238 Result.getNotConstant(), C, DL,
1240 if (Res->isNullValue())
1241 return LazyValueInfo::True;
1243 return LazyValueInfo::Unknown;
1246 return LazyValueInfo::Unknown;
1249 /// getPredicateOnEdge - Determine whether the specified value comparison
1250 /// with a constant is known to be true or false on the specified CFG edge.
1251 /// Pred is a CmpInst predicate.
1252 LazyValueInfo::Tristate
1253 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1254 BasicBlock *FromBB, BasicBlock *ToBB,
1255 Instruction *CxtI) {
1256 LVILatticeVal Result =
1257 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1259 return getPredicateResult(Pred, C, Result, DL, TLI);
1262 LazyValueInfo::Tristate
1263 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1264 Instruction *CxtI) {
1265 LVILatticeVal Result =
1266 getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI);
1268 return getPredicateResult(Pred, C, Result, DL, TLI);
1271 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1272 BasicBlock *NewSucc) {
1273 if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1276 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1277 if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB);