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/ADT/DenseMap.h"
25 #include "llvm/ADT/PointerIntPair.h"
28 char LazyValueInfo::ID = 0;
29 static RegisterPass<LazyValueInfo>
30 X("lazy-value-info", "Lazy Value Information Analysis", false, true);
33 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
44 /// FIXME: This is basically just for bringup, this can be made a lot more rich
50 /// undefined - This LLVM Value has no known value yet.
52 /// constant - This LLVM Value has a specific constant value.
55 /// notconstant - This LLVM value is known to not have the specified value.
58 /// overdefined - This instruction is not known to be constant, and we know
63 /// Val: This stores the current lattice value along with the Constant* for
64 /// the constant if this is a 'constant' or 'notconstant' value.
65 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
68 LVILatticeVal() : Val(0, undefined) {}
70 static LVILatticeVal get(Constant *C) {
75 static LVILatticeVal getNot(Constant *C) {
77 Res.markNotConstant(C);
81 bool isUndefined() const { return Val.getInt() == undefined; }
82 bool isConstant() const { return Val.getInt() == constant; }
83 bool isNotConstant() const { return Val.getInt() == notconstant; }
84 bool isOverdefined() const { return Val.getInt() == overdefined; }
86 Constant *getConstant() const {
87 assert(isConstant() && "Cannot get the constant of a non-constant!");
88 return Val.getPointer();
91 Constant *getNotConstant() const {
92 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
93 return Val.getPointer();
96 /// markOverdefined - Return true if this is a change in status.
97 bool markOverdefined() {
100 Val.setInt(overdefined);
104 /// markConstant - Return true if this is a change in status.
105 bool markConstant(Constant *V) {
107 assert(getConstant() == V && "Marking constant with different value");
111 assert(isUndefined());
112 Val.setInt(constant);
113 assert(V && "Marking constant with NULL");
118 /// markNotConstant - Return true if this is a change in status.
119 bool markNotConstant(Constant *V) {
120 if (isNotConstant()) {
121 assert(getNotConstant() == V && "Marking !constant with different value");
126 assert(getConstant() != V && "Marking not constant with different value");
128 assert(isUndefined());
130 Val.setInt(notconstant);
131 assert(V && "Marking constant with NULL");
136 /// mergeIn - Merge the specified lattice value into this one, updating this
137 /// one and returning true if anything changed.
138 bool mergeIn(const LVILatticeVal &RHS) {
139 if (RHS.isUndefined() || isOverdefined()) return false;
140 if (RHS.isOverdefined()) return markOverdefined();
142 if (RHS.isNotConstant()) {
143 if (isNotConstant()) {
144 if (getNotConstant() != RHS.getNotConstant() ||
145 isa<ConstantExpr>(getNotConstant()) ||
146 isa<ConstantExpr>(RHS.getNotConstant()))
147 return markOverdefined();
151 if (getConstant() == RHS.getNotConstant() ||
152 isa<ConstantExpr>(RHS.getNotConstant()) ||
153 isa<ConstantExpr>(getConstant()))
154 return markOverdefined();
155 return markNotConstant(RHS.getNotConstant());
158 assert(isUndefined() && "Unexpected lattice");
159 return markNotConstant(RHS.getNotConstant());
162 // RHS must be a constant, we must be undef, constant, or notconstant.
164 return markConstant(RHS.getConstant());
167 if (getConstant() != RHS.getConstant())
168 return markOverdefined();
172 // If we are known "!=4" and RHS is "==5", stay at "!=4".
173 if (getNotConstant() == RHS.getConstant() ||
174 isa<ConstantExpr>(getNotConstant()) ||
175 isa<ConstantExpr>(RHS.getConstant()))
176 return markOverdefined();
182 } // end anonymous namespace.
185 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
186 if (Val.isUndefined())
187 return OS << "undefined";
188 if (Val.isOverdefined())
189 return OS << "overdefined";
191 if (Val.isNotConstant())
192 return OS << "notconstant<" << *Val.getNotConstant() << '>';
193 return OS << "constant<" << *Val.getConstant() << '>';
197 //===----------------------------------------------------------------------===//
198 // LazyValueInfoCache Decl
199 //===----------------------------------------------------------------------===//
202 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
203 /// maintains information about queries across the clients' queries.
204 class LazyValueInfoCache {
206 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
207 /// specified basic block for a Value* that depends on context.
208 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
210 /// ValueCacheEntryTy - This is all of the cached block information for
211 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
212 /// entries, allowing us to do a lookup with a binary search.
213 typedef std::vector<BlockCacheEntryTy> ValueCacheEntryTy;
216 /// ValueCache - This is all of the cached information for all values,
217 /// mapped from Value* to key information.
218 DenseMap<Value*, ValueCacheEntryTy> ValueCache;
221 /// getValueInBlock - This is the query interface to determine the lattice
222 /// value for the specified Value* at the end of the specified block.
223 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
225 /// getValueOnEdge - This is the query interface to determine the lattice
226 /// value for the specified Value* that is true on the specified edge.
227 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
229 } // end anonymous namespace
231 //===----------------------------------------------------------------------===//
233 //===----------------------------------------------------------------------===//
236 /// LVIQuery - This is a transient object that exists while a query is
239 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
240 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
242 /// This is the current value being queried.
245 /// This is all of the cached information about this value.
246 ValueCacheEntryTy &Cache;
248 /// BlockVals Temporary Cache used while processing a query.
249 DenseMap<BasicBlock*, LVILatticeVal> BlockVals;
253 LVIQuery(Value *V, ValueCacheEntryTy &VC) : Val(V), Cache(VC) {
256 LVILatticeVal getBlockValue(BasicBlock *BB);
258 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
260 } // end anonymous namespace
263 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
264 // See if we already have a value for this block.
265 LVILatticeVal &BBLV = BlockVals[BB];
267 // If we've already computed this block's value, return it.
268 if (!BBLV.isUndefined())
271 // Otherwise, this is the first time we're seeing this block. Reset the
272 // lattice value to overdefined, so that cycles will terminate and be
273 // conservatively correct.
274 BBLV.markOverdefined();
276 // If V is live into BB, see if our predecessors know anything about it.
277 Instruction *BBI = dyn_cast<Instruction>(Val);
278 if (BBI == 0 || BBI->getParent() != BB) {
279 LVILatticeVal Result; // Start Undefined.
280 unsigned NumPreds = 0;
282 // Loop over all of our predecessors, merging what we know from them into
284 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
285 Result.mergeIn(getEdgeValue(*PI, BB));
287 // If we hit overdefined, exit early. The BlockVals entry is already set
289 if (Result.isOverdefined())
294 // If this is the entry block, we must be asking about an argument. The
295 // value is overdefined.
296 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
297 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
298 Result.markOverdefined();
302 // Return the merged value, which is more precise than 'overdefined'.
303 assert(!Result.isOverdefined());
304 return BlockVals[BB] = Result;
307 // If this value is defined by an instruction in this block, we have to
308 // process it here somehow or return overdefined.
309 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
311 // TODO: PHI Translation in preds.
316 LVILatticeVal Result;
317 Result.markOverdefined();
318 return BlockVals[BB] = Result;
322 /// getEdgeValue - This method
323 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
324 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
325 // If this is a conditional branch and only one successor goes to BBTo, then
326 // we maybe able to infer something from the condition.
327 if (BI->isConditional() &&
328 BI->getSuccessor(0) != BI->getSuccessor(1)) {
329 bool isTrueDest = BI->getSuccessor(0) == BBTo;
330 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
331 "BBTo isn't a successor of BBFrom");
333 // If V is the condition of the branch itself, then we know exactly what
335 if (BI->getCondition() == Val)
336 return LVILatticeVal::get(ConstantInt::get(
337 Type::getInt1Ty(Val->getContext()), isTrueDest));
339 // If the condition of the branch is an equality comparison, we may be
340 // able to infer the value.
341 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
342 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
343 isa<Constant>(ICI->getOperand(1))) {
344 // We know that V has the RHS constant if this is a true SETEQ or
346 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
347 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
348 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
353 // TODO: Info from switch.
355 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
358 // Otherwise see if the value is known in the block.
359 return getBlockValue(BBFrom);
363 //===----------------------------------------------------------------------===//
364 // LazyValueInfoCache Impl
365 //===----------------------------------------------------------------------===//
367 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
368 // If already a constant, there is nothing to compute.
369 if (Constant *VC = dyn_cast<Constant>(V))
370 return LVILatticeVal::get(VC);
372 DEBUG(errs() << "Getting value " << *V << " at end of block '"
373 << BB->getName() << "'\n");
375 LVILatticeVal Result = LVIQuery(V, ValueCache[V]).getBlockValue(BB);
377 DEBUG(errs() << " Result = " << Result << "\n");
381 LVILatticeVal LazyValueInfoCache::
382 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
383 // If already a constant, there is nothing to compute.
384 if (Constant *VC = dyn_cast<Constant>(V))
385 return LVILatticeVal::get(VC);
387 DEBUG(errs() << "Getting value " << *V << " on edge from '"
388 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
389 LVILatticeVal Result =
390 LVIQuery(V, ValueCache[V]).getEdgeValue(FromBB, ToBB);
392 DEBUG(errs() << " Result = " << Result << "\n");
397 //===----------------------------------------------------------------------===//
398 // LazyValueInfo Impl
399 //===----------------------------------------------------------------------===//
401 bool LazyValueInfo::runOnFunction(Function &F) {
402 TD = getAnalysisIfAvailable<TargetData>();
407 /// getCache - This lazily constructs the LazyValueInfoCache.
408 static LazyValueInfoCache &getCache(void *&PImpl) {
410 PImpl = new LazyValueInfoCache();
411 return *static_cast<LazyValueInfoCache*>(PImpl);
414 void LazyValueInfo::releaseMemory() {
415 // If the cache was allocated, free it.
417 delete &getCache(PImpl);
422 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
423 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
425 if (Result.isConstant())
426 return Result.getConstant();
430 /// getConstantOnEdge - Determine whether the specified value is known to be a
431 /// constant on the specified edge. Return null if not.
432 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
434 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
436 if (Result.isConstant())
437 return Result.getConstant();
441 /// getPredicateOnEdge - Determine whether the specified value comparison
442 /// with a constant is known to be true or false on the specified CFG edge.
443 /// Pred is a CmpInst predicate.
444 LazyValueInfo::Tristate
445 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
446 BasicBlock *FromBB, BasicBlock *ToBB) {
447 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
449 // If we know the value is a constant, evaluate the conditional.
451 if (Result.isConstant()) {
452 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
453 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
454 return ResCI->isZero() ? False : True;
458 if (Result.isNotConstant()) {
459 // If this is an equality comparison, we can try to fold it knowing that
461 if (Pred == ICmpInst::ICMP_EQ) {
462 // !C1 == C -> false iff C1 == C.
463 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
464 Result.getNotConstant(), C, TD);
465 if (Res->isNullValue())
467 } else if (Pred == ICmpInst::ICMP_NE) {
468 // !C1 != C -> true iff C1 == C.
469 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_EQ,
470 Result.getNotConstant(), C, TD);
471 if (Res->isNullValue())