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) {
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 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
219 if (ConstantInt *Res = dyn_cast<ConstantInt>(
220 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
222 RHS.getNotConstant())))
224 return markNotConstant(RHS.getNotConstant());
226 return markOverdefined();
229 // RHS is a ConstantRange, LHS is a non-integer Constant.
231 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
232 // a function. The correct result is to pick up RHS.
234 return markOverdefined();
237 if (isNotConstant()) {
238 if (RHS.isConstant()) {
240 return markOverdefined();
242 // Unless we can prove that the two Constants are different, we must
243 // move to overdefined.
244 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
245 if (ConstantInt *Res = dyn_cast<ConstantInt>(
246 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
252 return markOverdefined();
255 if (RHS.isNotConstant()) {
258 return markOverdefined();
261 return markOverdefined();
264 assert(isConstantRange() && "New LVILattice type?");
265 if (!RHS.isConstantRange())
266 return markOverdefined();
268 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
269 if (NewR.isFullSet())
270 return markOverdefined();
271 return markConstantRange(NewR);
275 } // end anonymous namespace.
278 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
280 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
281 if (Val.isUndefined())
282 return OS << "undefined";
283 if (Val.isOverdefined())
284 return OS << "overdefined";
286 if (Val.isNotConstant())
287 return OS << "notconstant<" << *Val.getNotConstant() << '>';
288 else if (Val.isConstantRange())
289 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
290 << Val.getConstantRange().getUpper() << '>';
291 return OS << "constant<" << *Val.getConstant() << '>';
295 //===----------------------------------------------------------------------===//
296 // LazyValueInfoCache Decl
297 //===----------------------------------------------------------------------===//
300 /// A callback value handle updates the cache when values are erased.
301 class LazyValueInfoCache;
302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
308 void deleted() override;
309 void allUsesReplacedWith(Value *V) override {
316 /// This is the cache kept by LazyValueInfo which
317 /// maintains information about queries across the clients' queries.
318 class LazyValueInfoCache {
319 /// This is all of the cached block information for exactly one Value*.
320 /// The entries are sorted by the BasicBlock* of the
321 /// entries, allowing us to do a lookup with a binary search.
322 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
324 /// This is all of the cached information for all values,
325 /// mapped from Value* to key information.
326 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
328 /// This tracks, on a per-block basis, the set of values that are
329 /// over-defined at the end of that block. This is required
330 /// for cache updating.
331 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
332 DenseSet<OverDefinedPairTy> OverDefinedCache;
334 /// Keep track of all blocks that we have ever seen, so we
335 /// don't spend time removing unused blocks from our caches.
336 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
338 /// This stack holds the state of the value solver during a query.
339 /// It basically emulates the callstack of the naive
340 /// recursive value lookup process.
341 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
343 /// Keeps track of which block-value pairs are in BlockValueStack.
344 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
346 /// Push BV onto BlockValueStack unless it's already in there.
347 /// Returns true on success.
348 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
349 if (BlockValueSet.count(BV))
350 return false; // It's already in the stack.
352 BlockValueStack.push(BV);
353 BlockValueSet.insert(BV);
357 /// A pointer to the cache of @llvm.assume calls.
359 /// An optional DL pointer.
360 const DataLayout *DL;
361 /// An optional DT pointer.
364 friend struct LVIValueHandle;
366 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
367 SeenBlocks.insert(BB);
368 lookup(Val)[BB] = Result;
369 if (Result.isOverdefined())
370 OverDefinedCache.insert(std::make_pair(BB, Val));
373 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
374 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
375 LVILatticeVal &Result,
376 Instruction *CxtI = nullptr);
377 bool hasBlockValue(Value *Val, BasicBlock *BB);
379 // These methods process one work item and may add more. A false value
380 // returned means that the work item was not completely processed and must
381 // be revisited after going through the new items.
382 bool solveBlockValue(Value *Val, BasicBlock *BB);
383 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
384 Value *Val, BasicBlock *BB);
385 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
386 PHINode *PN, BasicBlock *BB);
387 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
388 Instruction *BBI, BasicBlock *BB);
389 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
394 ValueCacheEntryTy &lookup(Value *V) {
395 return ValueCache[LVIValueHandle(V, this)];
399 /// This is the query interface to determine the lattice
400 /// value for the specified Value* at the end of the specified block.
401 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
402 Instruction *CxtI = nullptr);
404 /// This is the query interface to determine the lattice
405 /// value for the specified Value* at the specified instruction (generally
406 /// from an assume intrinsic).
407 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
409 /// This is the query interface to determine the lattice
410 /// value for the specified Value* that is true on the specified edge.
411 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
412 Instruction *CxtI = nullptr);
414 /// This is the update interface to inform the cache that an edge from
415 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
416 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
418 /// This is part of the update interface to inform the cache
419 /// that a block has been deleted.
420 void eraseBlock(BasicBlock *BB);
422 /// clear - Empty the cache.
426 OverDefinedCache.clear();
429 LazyValueInfoCache(AssumptionCache *AC, const DataLayout *DL = nullptr,
430 DominatorTree *DT = nullptr)
431 : AC(AC), DL(DL), DT(DT) {}
433 } // end anonymous namespace
435 void LVIValueHandle::deleted() {
436 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
438 SmallVector<OverDefinedPairTy, 4> ToErase;
439 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
440 if (P.second == getValPtr())
441 ToErase.push_back(P);
442 for (const OverDefinedPairTy &P : ToErase)
443 Parent->OverDefinedCache.erase(P);
445 // This erasure deallocates *this, so it MUST happen after we're done
446 // using any and all members of *this.
447 Parent->ValueCache.erase(*this);
450 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
451 // Shortcut if we have never seen this block.
452 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
453 if (I == SeenBlocks.end())
457 SmallVector<OverDefinedPairTy, 4> ToErase;
458 for (const OverDefinedPairTy& P : OverDefinedCache)
460 ToErase.push_back(P);
461 for (const OverDefinedPairTy &P : ToErase)
462 OverDefinedCache.erase(P);
464 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
465 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
469 void LazyValueInfoCache::solve() {
470 while (!BlockValueStack.empty()) {
471 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
472 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
474 if (solveBlockValue(e.second, e.first)) {
475 // The work item was completely processed.
476 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
477 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
479 BlockValueStack.pop();
480 BlockValueSet.erase(e);
482 // More work needs to be done before revisiting.
483 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
488 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
489 // If already a constant, there is nothing to compute.
490 if (isa<Constant>(Val))
493 LVIValueHandle ValHandle(Val, this);
494 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
495 ValueCache.find(ValHandle);
496 if (I == ValueCache.end()) return false;
497 return I->second.count(BB);
500 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
501 // If already a constant, there is nothing to compute.
502 if (Constant *VC = dyn_cast<Constant>(Val))
503 return LVILatticeVal::get(VC);
505 SeenBlocks.insert(BB);
506 return lookup(Val)[BB];
509 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
510 if (isa<Constant>(Val))
513 if (lookup(Val).count(BB)) {
514 // If we have a cached value, use that.
515 DEBUG(dbgs() << " reuse BB '" << BB->getName()
516 << "' val=" << lookup(Val)[BB] << '\n');
518 // Since we're reusing a cached value, we don't need to update the
519 // OverDefinedCache. The cache will have been properly updated whenever the
520 // cached value was inserted.
524 // Hold off inserting this value into the Cache in case we have to return
525 // false and come back later.
528 Instruction *BBI = dyn_cast<Instruction>(Val);
529 if (!BBI || BBI->getParent() != BB) {
530 if (!solveBlockValueNonLocal(Res, Val, BB))
532 insertResult(Val, BB, Res);
536 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
537 if (!solveBlockValuePHINode(Res, PN, BB))
539 insertResult(Val, BB, Res);
543 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
544 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
545 insertResult(Val, BB, Res);
549 // We can only analyze the definitions of certain classes of instructions
550 // (integral binops and casts at the moment), so bail if this isn't one.
551 LVILatticeVal Result;
552 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
553 !BBI->getType()->isIntegerTy()) {
554 DEBUG(dbgs() << " compute BB '" << BB->getName()
555 << "' - overdefined because inst def found.\n");
556 Res.markOverdefined();
557 insertResult(Val, BB, Res);
561 // FIXME: We're currently limited to binops with a constant RHS. This should
563 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
564 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
565 DEBUG(dbgs() << " compute BB '" << BB->getName()
566 << "' - overdefined because inst def found.\n");
568 Res.markOverdefined();
569 insertResult(Val, BB, Res);
573 if (!solveBlockValueConstantRange(Res, BBI, BB))
575 insertResult(Val, BB, Res);
579 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
580 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
581 return L->getPointerAddressSpace() == 0 &&
582 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
584 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
585 return S->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
588 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
589 if (MI->isVolatile()) return false;
591 // FIXME: check whether it has a valuerange that excludes zero?
592 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
593 if (!Len || Len->isZero()) return false;
595 if (MI->getDestAddressSpace() == 0)
596 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
598 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
599 if (MTI->getSourceAddressSpace() == 0)
600 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
606 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
607 Value *Val, BasicBlock *BB) {
608 LVILatticeVal Result; // Start Undefined.
610 // If this is a pointer, and there's a load from that pointer in this BB,
611 // then we know that the pointer can't be NULL.
612 bool NotNull = false;
613 if (Val->getType()->isPointerTy()) {
614 if (isKnownNonNull(Val)) {
617 Value *UnderlyingVal = GetUnderlyingObject(Val);
618 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
619 // inside InstructionDereferencesPointer either.
620 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
621 for (Instruction &I : *BB) {
622 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
631 // If this is the entry block, we must be asking about an argument. The
632 // value is overdefined.
633 if (BB == &BB->getParent()->getEntryBlock()) {
634 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
636 PointerType *PTy = cast<PointerType>(Val->getType());
637 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
639 Result.markOverdefined();
645 // Loop over all of our predecessors, merging what we know from them into
647 bool EdgesMissing = false;
648 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
649 LVILatticeVal EdgeResult;
650 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
654 Result.mergeIn(EdgeResult);
656 // If we hit overdefined, exit early. The BlockVals entry is already set
658 if (Result.isOverdefined()) {
659 DEBUG(dbgs() << " compute BB '" << BB->getName()
660 << "' - overdefined because of pred.\n");
661 // If we previously determined that this is a pointer that can't be null
662 // then return that rather than giving up entirely.
664 PointerType *PTy = cast<PointerType>(Val->getType());
665 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
675 // Return the merged value, which is more precise than 'overdefined'.
676 assert(!Result.isOverdefined());
681 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
682 PHINode *PN, BasicBlock *BB) {
683 LVILatticeVal Result; // Start Undefined.
685 // Loop over all of our predecessors, merging what we know from them into
687 bool EdgesMissing = false;
688 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
689 BasicBlock *PhiBB = PN->getIncomingBlock(i);
690 Value *PhiVal = PN->getIncomingValue(i);
691 LVILatticeVal EdgeResult;
692 // Note that we can provide PN as the context value to getEdgeValue, even
693 // though the results will be cached, because PN is the value being used as
694 // the cache key in the caller.
695 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
699 Result.mergeIn(EdgeResult);
701 // If we hit overdefined, exit early. The BlockVals entry is already set
703 if (Result.isOverdefined()) {
704 DEBUG(dbgs() << " compute BB '" << BB->getName()
705 << "' - overdefined because of pred.\n");
714 // Return the merged value, which is more precise than 'overdefined'.
715 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
720 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
721 LVILatticeVal &Result,
722 bool isTrueDest = true);
724 // If we can determine a constant range for the value Val in the context
725 // provided by the instruction BBI, then merge it into BBLV. If we did find a
726 // constant range, return true.
727 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
730 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
734 for (auto &AssumeVH : AC->assumptions()) {
737 auto *I = cast<CallInst>(AssumeVH);
738 if (!isValidAssumeForContext(I, BBI, DL, DT))
741 Value *C = I->getArgOperand(0);
742 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
743 LVILatticeVal Result;
744 if (getValueFromFromCondition(Val, ICI, Result)) {
745 if (BBLV.isOverdefined())
748 BBLV.mergeIn(Result);
754 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
757 // Figure out the range of the LHS. If that fails, bail.
758 if (!hasBlockValue(BBI->getOperand(0), BB)) {
759 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
761 BBLV.markOverdefined();
765 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
766 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
767 if (!LHSVal.isConstantRange()) {
768 BBLV.markOverdefined();
772 ConstantRange LHSRange = LHSVal.getConstantRange();
773 ConstantRange RHSRange(1);
774 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
775 if (isa<BinaryOperator>(BBI)) {
776 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
777 RHSRange = ConstantRange(RHS->getValue());
779 BBLV.markOverdefined();
784 // NOTE: We're currently limited by the set of operations that ConstantRange
785 // can evaluate symbolically. Enhancing that set will allows us to analyze
787 LVILatticeVal Result;
788 switch (BBI->getOpcode()) {
789 case Instruction::Add:
790 Result.markConstantRange(LHSRange.add(RHSRange));
792 case Instruction::Sub:
793 Result.markConstantRange(LHSRange.sub(RHSRange));
795 case Instruction::Mul:
796 Result.markConstantRange(LHSRange.multiply(RHSRange));
798 case Instruction::UDiv:
799 Result.markConstantRange(LHSRange.udiv(RHSRange));
801 case Instruction::Shl:
802 Result.markConstantRange(LHSRange.shl(RHSRange));
804 case Instruction::LShr:
805 Result.markConstantRange(LHSRange.lshr(RHSRange));
807 case Instruction::Trunc:
808 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
810 case Instruction::SExt:
811 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
813 case Instruction::ZExt:
814 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
816 case Instruction::BitCast:
817 Result.markConstantRange(LHSRange);
819 case Instruction::And:
820 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
822 case Instruction::Or:
823 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
826 // Unhandled instructions are overdefined.
828 DEBUG(dbgs() << " compute BB '" << BB->getName()
829 << "' - overdefined because inst def found.\n");
830 Result.markOverdefined();
838 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
839 LVILatticeVal &Result, bool isTrueDest) {
840 if (ICI && isa<Constant>(ICI->getOperand(1))) {
841 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
842 // We know that V has the RHS constant if this is a true SETEQ or
844 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
845 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
847 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
851 // Recognize the range checking idiom that InstCombine produces.
852 // (X-C1) u< C2 --> [C1, C1+C2)
853 ConstantInt *NegOffset = nullptr;
854 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
855 match(ICI->getOperand(0), m_Add(m_Specific(Val),
856 m_ConstantInt(NegOffset)));
858 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
859 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
860 // Calculate the range of values that would satisfy the comparison.
861 ConstantRange CmpRange(CI->getValue());
862 ConstantRange TrueValues =
863 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
865 if (NegOffset) // Apply the offset from above.
866 TrueValues = TrueValues.subtract(NegOffset->getValue());
868 // If we're interested in the false dest, invert the condition.
869 if (!isTrueDest) TrueValues = TrueValues.inverse();
871 Result = LVILatticeVal::getRange(TrueValues);
879 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
880 /// Val is not constrained on the edge.
881 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
882 BasicBlock *BBTo, LVILatticeVal &Result) {
883 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
885 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
886 // If this is a conditional branch and only one successor goes to BBTo, then
887 // we may be able to infer something from the condition.
888 if (BI->isConditional() &&
889 BI->getSuccessor(0) != BI->getSuccessor(1)) {
890 bool isTrueDest = BI->getSuccessor(0) == BBTo;
891 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
892 "BBTo isn't a successor of BBFrom");
894 // If V is the condition of the branch itself, then we know exactly what
896 if (BI->getCondition() == Val) {
897 Result = LVILatticeVal::get(ConstantInt::get(
898 Type::getInt1Ty(Val->getContext()), isTrueDest));
902 // If the condition of the branch is an equality comparison, we may be
903 // able to infer the value.
904 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
905 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
910 // If the edge was formed by a switch on the value, then we may know exactly
912 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
913 if (SI->getCondition() != Val)
916 bool DefaultCase = SI->getDefaultDest() == BBTo;
917 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
918 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
920 for (SwitchInst::CaseIt i : SI->cases()) {
921 ConstantRange EdgeVal(i.getCaseValue()->getValue());
923 // It is possible that the default destination is the destination of
924 // some cases. There is no need to perform difference for those cases.
925 if (i.getCaseSuccessor() != BBTo)
926 EdgesVals = EdgesVals.difference(EdgeVal);
927 } else if (i.getCaseSuccessor() == BBTo)
928 EdgesVals = EdgesVals.unionWith(EdgeVal);
930 Result = LVILatticeVal::getRange(EdgesVals);
936 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
937 /// the basic block if the edge does not constrain Val.
938 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
939 BasicBlock *BBTo, LVILatticeVal &Result,
941 // If already a constant, there is nothing to compute.
942 if (Constant *VC = dyn_cast<Constant>(Val)) {
943 Result = LVILatticeVal::get(VC);
947 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
948 if (!Result.isConstantRange() ||
949 Result.getConstantRange().getSingleElement())
952 // FIXME: this check should be moved to the beginning of the function when
953 // LVI better supports recursive values. Even for the single value case, we
954 // can intersect to detect dead code (an empty range).
955 if (!hasBlockValue(Val, BBFrom)) {
956 if (pushBlockValue(std::make_pair(BBFrom, Val)))
958 Result.markOverdefined();
962 // Try to intersect ranges of the BB and the constraint on the edge.
963 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
964 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
965 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
966 // and caching, below.
967 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
968 if (!InBlock.isConstantRange())
971 ConstantRange Range =
972 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
973 Result = LVILatticeVal::getRange(Range);
977 if (!hasBlockValue(Val, BBFrom)) {
978 if (pushBlockValue(std::make_pair(BBFrom, Val)))
980 Result.markOverdefined();
984 // If we couldn't compute the value on the edge, use the value from the BB.
985 Result = getBlockValue(Val, BBFrom);
986 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
987 // We can use the context instruction (generically the ultimate instruction
988 // the calling pass is trying to simplify) here, even though the result of
989 // this function is generally cached when called from the solve* functions
990 // (and that cached result might be used with queries using a different
991 // context instruction), because when this function is called from the solve*
992 // functions, the context instruction is not provided. When called from
993 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
994 // but then the result is not cached.
995 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
999 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1000 Instruction *CxtI) {
1001 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1002 << BB->getName() << "'\n");
1004 assert(BlockValueStack.empty() && BlockValueSet.empty());
1005 pushBlockValue(std::make_pair(BB, V));
1008 LVILatticeVal Result = getBlockValue(V, BB);
1009 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1011 DEBUG(dbgs() << " Result = " << Result << "\n");
1015 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1016 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1017 << CxtI->getName() << "'\n");
1019 LVILatticeVal Result;
1020 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1022 DEBUG(dbgs() << " Result = " << Result << "\n");
1026 LVILatticeVal LazyValueInfoCache::
1027 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1028 Instruction *CxtI) {
1029 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1030 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1032 LVILatticeVal Result;
1033 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1035 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1037 assert(WasFastQuery && "More work to do after problem solved?");
1040 DEBUG(dbgs() << " Result = " << Result << "\n");
1044 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1045 BasicBlock *NewSucc) {
1046 // When an edge in the graph has been threaded, values that we could not
1047 // determine a value for before (i.e. were marked overdefined) may be possible
1048 // to solve now. We do NOT try to proactively update these values. Instead,
1049 // we clear their entries from the cache, and allow lazy updating to recompute
1050 // them when needed.
1052 // The updating process is fairly simple: we need to drop cached info
1053 // for all values that were marked overdefined in OldSucc, and for those same
1054 // values in any successor of OldSucc (except NewSucc) in which they were
1055 // also marked overdefined.
1056 std::vector<BasicBlock*> worklist;
1057 worklist.push_back(OldSucc);
1059 DenseSet<Value*> ClearSet;
1060 for (OverDefinedPairTy &P : OverDefinedCache)
1061 if (P.first == OldSucc)
1062 ClearSet.insert(P.second);
1064 // Use a worklist to perform a depth-first search of OldSucc's successors.
1065 // NOTE: We do not need a visited list since any blocks we have already
1066 // visited will have had their overdefined markers cleared already, and we
1067 // thus won't loop to their successors.
1068 while (!worklist.empty()) {
1069 BasicBlock *ToUpdate = worklist.back();
1070 worklist.pop_back();
1072 // Skip blocks only accessible through NewSucc.
1073 if (ToUpdate == NewSucc) continue;
1075 bool changed = false;
1076 for (Value *V : ClearSet) {
1077 // If a value was marked overdefined in OldSucc, and is here too...
1078 DenseSet<OverDefinedPairTy>::iterator OI =
1079 OverDefinedCache.find(std::make_pair(ToUpdate, V));
1080 if (OI == OverDefinedCache.end()) continue;
1082 // Remove it from the caches.
1083 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
1084 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1086 assert(CI != Entry.end() && "Couldn't find entry to update?");
1088 OverDefinedCache.erase(OI);
1090 // If we removed anything, then we potentially need to update
1091 // blocks successors too.
1095 if (!changed) continue;
1097 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1101 //===----------------------------------------------------------------------===//
1102 // LazyValueInfo Impl
1103 //===----------------------------------------------------------------------===//
1105 /// This lazily constructs the LazyValueInfoCache.
1106 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1107 const DataLayout *DL = nullptr,
1108 DominatorTree *DT = nullptr) {
1110 PImpl = new LazyValueInfoCache(AC, DL, DT);
1111 return *static_cast<LazyValueInfoCache*>(PImpl);
1114 bool LazyValueInfo::runOnFunction(Function &F) {
1115 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1117 DominatorTreeWrapperPass *DTWP =
1118 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1119 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1121 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1122 DL = DLP ? &DLP->getDataLayout() : nullptr;
1124 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1127 getCache(PImpl, AC, DL, DT).clear();
1133 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1134 AU.setPreservesAll();
1135 AU.addRequired<AssumptionCacheTracker>();
1136 AU.addRequired<TargetLibraryInfoWrapperPass>();
1139 void LazyValueInfo::releaseMemory() {
1140 // If the cache was allocated, free it.
1142 delete &getCache(PImpl, AC);
1147 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1148 Instruction *CxtI) {
1149 LVILatticeVal Result =
1150 getCache(PImpl, AC, DL, DT).getValueInBlock(V, BB, CxtI);
1152 if (Result.isConstant())
1153 return Result.getConstant();
1154 if (Result.isConstantRange()) {
1155 ConstantRange CR = Result.getConstantRange();
1156 if (const APInt *SingleVal = CR.getSingleElement())
1157 return ConstantInt::get(V->getContext(), *SingleVal);
1162 /// Determine whether the specified value is known to be a
1163 /// constant on the specified edge. Return null if not.
1164 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1166 Instruction *CxtI) {
1167 LVILatticeVal Result =
1168 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1170 if (Result.isConstant())
1171 return Result.getConstant();
1172 if (Result.isConstantRange()) {
1173 ConstantRange CR = Result.getConstantRange();
1174 if (const APInt *SingleVal = CR.getSingleElement())
1175 return ConstantInt::get(V->getContext(), *SingleVal);
1180 static LazyValueInfo::Tristate
1181 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1182 const DataLayout *DL, 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 LVILatticeVal Result =
1254 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1256 return getPredicateResult(Pred, C, Result, DL, TLI);
1259 LazyValueInfo::Tristate
1260 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1261 Instruction *CxtI) {
1262 LVILatticeVal Result = getCache(PImpl, AC, DL, DT).getValueAt(V, CxtI);
1264 return getPredicateResult(Pred, C, Result, DL, TLI);
1267 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1268 BasicBlock *NewSucc) {
1270 getCache(PImpl, AC, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1273 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1275 getCache(PImpl, AC, DL, DT).eraseBlock(BB);