1 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for lazy computation of value constraint
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/STLExtras.h"
30 char LazyValueInfo::ID = 0;
31 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
32 "Lazy Value Information Analysis", false, true);
35 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
46 /// FIXME: This is basically just for bringup, this can be made a lot more rich
52 /// undefined - This LLVM Value has no known value yet.
54 /// constant - This LLVM Value has a specific constant value.
57 /// notconstant - This LLVM value is known to not have the specified value.
60 /// overdefined - This instruction is not known to be constant, and we know
65 /// Val: This stores the current lattice value along with the Constant* for
66 /// the constant if this is a 'constant' or 'notconstant' value.
71 LVILatticeVal() : Tag(undefined), Val(0) {}
73 static LVILatticeVal get(Constant *C) {
78 static LVILatticeVal getNot(Constant *C) {
80 Res.markNotConstant(C);
84 bool isUndefined() const { return Tag == undefined; }
85 bool isConstant() const { return Tag == constant; }
86 bool isNotConstant() const { return Tag == notconstant; }
87 bool isOverdefined() const { return Tag == overdefined; }
89 Constant *getConstant() const {
90 assert(isConstant() && "Cannot get the constant of a non-constant!");
94 Constant *getNotConstant() const {
95 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
99 /// markOverdefined - Return true if this is a change in status.
100 bool markOverdefined() {
107 /// markConstant - Return true if this is a change in status.
108 bool markConstant(Constant *V) {
110 assert(getConstant() == V && "Marking constant with different value");
114 assert(isUndefined());
116 assert(V && "Marking constant with NULL");
121 /// markNotConstant - Return true if this is a change in status.
122 bool markNotConstant(Constant *V) {
123 if (isNotConstant()) {
124 assert(getNotConstant() == V && "Marking !constant with different value");
129 assert(getConstant() != V && "Marking not constant with different value");
131 assert(isUndefined());
134 assert(V && "Marking constant with NULL");
139 /// mergeIn - Merge the specified lattice value into this one, updating this
140 /// one and returning true if anything changed.
141 bool mergeIn(const LVILatticeVal &RHS) {
142 if (RHS.isUndefined() || isOverdefined()) return false;
143 if (RHS.isOverdefined()) return markOverdefined();
145 if (RHS.isNotConstant()) {
146 if (isNotConstant()) {
147 if (getNotConstant() != RHS.getNotConstant() ||
148 isa<ConstantExpr>(getNotConstant()) ||
149 isa<ConstantExpr>(RHS.getNotConstant()))
150 return markOverdefined();
154 if (getConstant() == RHS.getNotConstant() ||
155 isa<ConstantExpr>(RHS.getNotConstant()) ||
156 isa<ConstantExpr>(getConstant()))
157 return markOverdefined();
158 return markNotConstant(RHS.getNotConstant());
161 assert(isUndefined() && "Unexpected lattice");
162 return markNotConstant(RHS.getNotConstant());
165 // RHS must be a constant, we must be undef, constant, or notconstant.
167 return markConstant(RHS.getConstant());
170 if (getConstant() != RHS.getConstant())
171 return markOverdefined();
175 // If we are known "!=4" and RHS is "==5", stay at "!=4".
176 if (getNotConstant() == RHS.getConstant() ||
177 isa<ConstantExpr>(getNotConstant()) ||
178 isa<ConstantExpr>(RHS.getConstant()))
179 return markOverdefined();
185 } // end anonymous namespace.
188 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
189 if (Val.isUndefined())
190 return OS << "undefined";
191 if (Val.isOverdefined())
192 return OS << "overdefined";
194 if (Val.isNotConstant())
195 return OS << "notconstant<" << *Val.getNotConstant() << '>';
196 return OS << "constant<" << *Val.getConstant() << '>';
200 //===----------------------------------------------------------------------===//
201 // LazyValueInfoCache Decl
202 //===----------------------------------------------------------------------===//
205 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
206 /// maintains information about queries across the clients' queries.
207 class LazyValueInfoCache {
209 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
210 /// specified basic block for a Value* that depends on context.
211 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
213 /// ValueCacheEntryTy - This is all of the cached block information for
214 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
215 /// entries, allowing us to do a lookup with a binary search.
216 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
219 /// LVIValueHandle - A callback value handle update the cache when
220 /// values are erased.
221 struct LVIValueHandle : public CallbackVH {
222 LazyValueInfoCache *Parent;
224 LVIValueHandle(Value *V, LazyValueInfoCache *P)
225 : CallbackVH(V), Parent(P) { }
228 void allUsesReplacedWith(Value* V) {
232 LVIValueHandle &operator=(Value *V) {
233 return *this = LVIValueHandle(V, Parent);
237 /// ValueCache - This is all of the cached information for all values,
238 /// mapped from Value* to key information.
239 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
241 /// OverDefinedCache - This tracks, on a per-block basis, the set of
242 /// values that are over-defined at the end of that block. This is required
243 /// for cache updating.
244 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
248 /// getValueInBlock - This is the query interface to determine the lattice
249 /// value for the specified Value* at the end of the specified block.
250 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
252 /// getValueOnEdge - This is the query interface to determine the lattice
253 /// value for the specified Value* that is true on the specified edge.
254 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
256 /// threadEdge - This is the update interface to inform the cache that an
257 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
259 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
261 } // end anonymous namespace
263 //===----------------------------------------------------------------------===//
265 //===----------------------------------------------------------------------===//
268 /// LVIQuery - This is a transient object that exists while a query is
271 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
272 /// reallocation of the densemap on every query.
274 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
275 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
277 /// This is the current value being queried for.
280 /// This is a pointer to the owning cache, for recursive queries.
281 LazyValueInfoCache &Parent;
283 /// This is all of the cached information about this value.
284 ValueCacheEntryTy &Cache;
286 /// This tracks, for each block, what values are overdefined.
287 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
289 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
290 /// added to cache but that are not in sorted order.
291 DenseSet<BasicBlock*> NewBlockInfo;
294 LVIQuery(Value *V, LazyValueInfoCache &P,
295 ValueCacheEntryTy &VC,
296 std::set<std::pair<BasicBlock*, Value*> > &ODC)
297 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
301 // When the query is done, insert the newly discovered facts into the
302 // cache in sorted order.
303 if (NewBlockInfo.empty()) return;
305 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
306 E = NewBlockInfo.end(); I != E; ++I) {
307 if (Cache[*I].isOverdefined())
308 OverDefinedCache.insert(std::make_pair(*I, Val));
312 LVILatticeVal getBlockValue(BasicBlock *BB);
313 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
316 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
318 } // end anonymous namespace
320 void LazyValueInfoCache::LVIValueHandle::deleted() {
321 Parent->ValueCache.erase(*this);
322 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
323 I = Parent->OverDefinedCache.begin(),
324 E = Parent->OverDefinedCache.end();
326 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
328 if (tmp->second == getValPtr())
329 Parent->OverDefinedCache.erase(tmp);
334 /// getCachedEntryForBlock - See if we already have a value for this block. If
335 /// so, return it, otherwise create a new entry in the Cache map to use.
336 LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
337 NewBlockInfo.insert(BB);
341 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
342 // See if we already have a value for this block.
343 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
345 // If we've already computed this block's value, return it.
346 if (!BBLV.isUndefined()) {
347 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
351 // Otherwise, this is the first time we're seeing this block. Reset the
352 // lattice value to overdefined, so that cycles will terminate and be
353 // conservatively correct.
354 BBLV.markOverdefined();
356 // If V is live into BB, see if our predecessors know anything about it.
357 Instruction *BBI = dyn_cast<Instruction>(Val);
358 if (BBI == 0 || BBI->getParent() != BB) {
359 LVILatticeVal Result; // Start Undefined.
360 unsigned NumPreds = 0;
362 // Loop over all of our predecessors, merging what we know from them into
364 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
365 Result.mergeIn(getEdgeValue(*PI, BB));
367 // If we hit overdefined, exit early. The BlockVals entry is already set
369 if (Result.isOverdefined()) {
370 DEBUG(dbgs() << " compute BB '" << BB->getName()
371 << "' - overdefined because of pred.\n");
377 // If this is the entry block, we must be asking about an argument. The
378 // value is overdefined.
379 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
380 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
381 Result.markOverdefined();
385 // Return the merged value, which is more precise than 'overdefined'.
386 assert(!Result.isOverdefined());
387 return getCachedEntryForBlock(BB) = Result;
390 // If this value is defined by an instruction in this block, we have to
391 // process it here somehow or return overdefined.
392 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
393 LVILatticeVal Result; // Start Undefined.
395 // Loop over all of our predecessors, merging what we know from them into
397 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
398 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
399 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
401 // If we hit overdefined, exit early. The BlockVals entry is already set
403 if (Result.isOverdefined()) {
404 DEBUG(dbgs() << " compute BB '" << BB->getName()
405 << "' - overdefined because of pred.\n");
410 // Return the merged value, which is more precise than 'overdefined'.
411 assert(!Result.isOverdefined());
412 return getCachedEntryForBlock(BB) = Result;
418 DEBUG(dbgs() << " compute BB '" << BB->getName()
419 << "' - overdefined because inst def found.\n");
421 LVILatticeVal Result;
422 Result.markOverdefined();
423 return getCachedEntryForBlock(BB) = Result;
427 /// getEdgeValue - This method attempts to infer more complex
428 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
429 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
431 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
432 // If this is a conditional branch and only one successor goes to BBTo, then
433 // we maybe able to infer something from the condition.
434 if (BI->isConditional() &&
435 BI->getSuccessor(0) != BI->getSuccessor(1)) {
436 bool isTrueDest = BI->getSuccessor(0) == BBTo;
437 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
438 "BBTo isn't a successor of BBFrom");
440 // If V is the condition of the branch itself, then we know exactly what
442 if (BI->getCondition() == Val)
443 return LVILatticeVal::get(ConstantInt::get(
444 Type::getInt1Ty(Val->getContext()), isTrueDest));
446 // If the condition of the branch is an equality comparison, we may be
447 // able to infer the value.
448 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
449 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
450 isa<Constant>(ICI->getOperand(1))) {
451 // We know that V has the RHS constant if this is a true SETEQ or
453 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
454 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
455 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
460 // If the edge was formed by a switch on the value, then we may know exactly
462 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
463 // If BBTo is the default destination of the switch, we don't know anything.
464 // Given a more powerful range analysis we could know stuff.
465 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
466 // We only know something if there is exactly one value that goes from
468 unsigned NumEdges = 0;
469 ConstantInt *EdgeVal = 0;
470 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
471 if (SI->getSuccessor(i) != BBTo) continue;
472 if (NumEdges++) break;
473 EdgeVal = SI->getCaseValue(i);
475 assert(EdgeVal && "Missing successor?");
477 return LVILatticeVal::get(EdgeVal);
481 // Otherwise see if the value is known in the block.
482 return getBlockValue(BBFrom);
486 //===----------------------------------------------------------------------===//
487 // LazyValueInfoCache Impl
488 //===----------------------------------------------------------------------===//
490 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
491 // If already a constant, there is nothing to compute.
492 if (Constant *VC = dyn_cast<Constant>(V))
493 return LVILatticeVal::get(VC);
495 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
496 << BB->getName() << "'\n");
498 LVILatticeVal Result = LVIQuery(V, *this,
499 ValueCache[LVIValueHandle(V, this)],
500 OverDefinedCache).getBlockValue(BB);
502 DEBUG(dbgs() << " Result = " << Result << "\n");
506 LVILatticeVal LazyValueInfoCache::
507 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
508 // If already a constant, there is nothing to compute.
509 if (Constant *VC = dyn_cast<Constant>(V))
510 return LVILatticeVal::get(VC);
512 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
513 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
515 LVILatticeVal Result =
516 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
517 OverDefinedCache).getEdgeValue(FromBB, ToBB);
519 DEBUG(dbgs() << " Result = " << Result << "\n");
524 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
525 BasicBlock *NewSucc) {
526 // When an edge in the graph has been threaded, values that we could not
527 // determine a value for before (i.e. were marked overdefined) may be possible
528 // to solve now. We do NOT try to proactively update these values. Instead,
529 // we clear their entries from the cache, and allow lazy updating to recompute
532 // The updating process is fairly simple: we need to dropped cached info
533 // for all values that were marked overdefined in OldSucc, and for those same
534 // values in any successor of OldSucc (except NewSucc) in which they were
535 // also marked overdefined.
536 std::vector<BasicBlock*> worklist;
537 worklist.push_back(OldSucc);
539 DenseSet<Value*> ClearSet;
540 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
541 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
542 if (I->first == OldSucc)
543 ClearSet.insert(I->second);
546 // Use a worklist to perform a depth-first search of OldSucc's successors.
547 // NOTE: We do not need a visited list since any blocks we have already
548 // visited will have had their overdefined markers cleared already, and we
549 // thus won't loop to their successors.
550 while (!worklist.empty()) {
551 BasicBlock *ToUpdate = worklist.back();
554 // Skip blocks only accessible through NewSucc.
555 if (ToUpdate == NewSucc) continue;
557 bool changed = false;
558 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
560 // If a value was marked overdefined in OldSucc, and is here too...
561 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
562 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
563 if (OI == OverDefinedCache.end()) continue;
565 // Remove it from the caches.
566 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
567 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
569 assert(CI != Entry.end() && "Couldn't find entry to update?");
571 OverDefinedCache.erase(OI);
573 // If we removed anything, then we potentially need to update
574 // blocks successors too.
578 if (!changed) continue;
580 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
584 //===----------------------------------------------------------------------===//
585 // LazyValueInfo Impl
586 //===----------------------------------------------------------------------===//
588 bool LazyValueInfo::runOnFunction(Function &F) {
589 TD = getAnalysisIfAvailable<TargetData>();
594 /// getCache - This lazily constructs the LazyValueInfoCache.
595 static LazyValueInfoCache &getCache(void *&PImpl) {
597 PImpl = new LazyValueInfoCache();
598 return *static_cast<LazyValueInfoCache*>(PImpl);
601 void LazyValueInfo::releaseMemory() {
602 // If the cache was allocated, free it.
604 delete &getCache(PImpl);
609 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
610 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
612 if (Result.isConstant())
613 return Result.getConstant();
617 /// getConstantOnEdge - Determine whether the specified value is known to be a
618 /// constant on the specified edge. Return null if not.
619 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
621 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
623 if (Result.isConstant())
624 return Result.getConstant();
628 /// getPredicateOnEdge - Determine whether the specified value comparison
629 /// with a constant is known to be true or false on the specified CFG edge.
630 /// Pred is a CmpInst predicate.
631 LazyValueInfo::Tristate
632 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
633 BasicBlock *FromBB, BasicBlock *ToBB) {
634 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
636 // If we know the value is a constant, evaluate the conditional.
638 if (Result.isConstant()) {
639 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
640 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
641 return ResCI->isZero() ? False : True;
645 if (Result.isNotConstant()) {
646 // If this is an equality comparison, we can try to fold it knowing that
648 if (Pred == ICmpInst::ICMP_EQ) {
649 // !C1 == C -> false iff C1 == C.
650 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
651 Result.getNotConstant(), C, TD);
652 if (Res->isNullValue())
654 } else if (Pred == ICmpInst::ICMP_NE) {
655 // !C1 != C -> true iff C1 == C.
656 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
657 Result.getNotConstant(), C, TD);
658 if (Res->isNullValue())
667 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
668 BasicBlock* NewSucc) {
669 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);