LLVM API Documentation
00001 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the interface for lazy computation of value constraint 00011 // information. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "lazy-value-info" 00016 #include "llvm/Analysis/LazyValueInfo.h" 00017 #include "llvm/ADT/DenseSet.h" 00018 #include "llvm/ADT/STLExtras.h" 00019 #include "llvm/Analysis/ConstantFolding.h" 00020 #include "llvm/Analysis/ValueTracking.h" 00021 #include "llvm/IR/Constants.h" 00022 #include "llvm/IR/DataLayout.h" 00023 #include "llvm/IR/Instructions.h" 00024 #include "llvm/IR/IntrinsicInst.h" 00025 #include "llvm/Support/CFG.h" 00026 #include "llvm/Support/ConstantRange.h" 00027 #include "llvm/Support/Debug.h" 00028 #include "llvm/Support/PatternMatch.h" 00029 #include "llvm/Support/ValueHandle.h" 00030 #include "llvm/Support/raw_ostream.h" 00031 #include "llvm/Target/TargetLibraryInfo.h" 00032 #include <map> 00033 #include <stack> 00034 using namespace llvm; 00035 using namespace PatternMatch; 00036 00037 char LazyValueInfo::ID = 0; 00038 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info", 00039 "Lazy Value Information Analysis", false, true) 00040 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 00041 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info", 00042 "Lazy Value Information Analysis", false, true) 00043 00044 namespace llvm { 00045 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); } 00046 } 00047 00048 00049 //===----------------------------------------------------------------------===// 00050 // LVILatticeVal 00051 //===----------------------------------------------------------------------===// 00052 00053 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each 00054 /// value. 00055 /// 00056 /// FIXME: This is basically just for bringup, this can be made a lot more rich 00057 /// in the future. 00058 /// 00059 namespace { 00060 class LVILatticeVal { 00061 enum LatticeValueTy { 00062 /// undefined - This Value has no known value yet. 00063 undefined, 00064 00065 /// constant - This Value has a specific constant value. 00066 constant, 00067 /// notconstant - This Value is known to not have the specified value. 00068 notconstant, 00069 00070 /// constantrange - The Value falls within this range. 00071 constantrange, 00072 00073 /// overdefined - This value is not known to be constant, and we know that 00074 /// it has a value. 00075 overdefined 00076 }; 00077 00078 /// Val: This stores the current lattice value along with the Constant* for 00079 /// the constant if this is a 'constant' or 'notconstant' value. 00080 LatticeValueTy Tag; 00081 Constant *Val; 00082 ConstantRange Range; 00083 00084 public: 00085 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {} 00086 00087 static LVILatticeVal get(Constant *C) { 00088 LVILatticeVal Res; 00089 if (!isa<UndefValue>(C)) 00090 Res.markConstant(C); 00091 return Res; 00092 } 00093 static LVILatticeVal getNot(Constant *C) { 00094 LVILatticeVal Res; 00095 if (!isa<UndefValue>(C)) 00096 Res.markNotConstant(C); 00097 return Res; 00098 } 00099 static LVILatticeVal getRange(ConstantRange CR) { 00100 LVILatticeVal Res; 00101 Res.markConstantRange(CR); 00102 return Res; 00103 } 00104 00105 bool isUndefined() const { return Tag == undefined; } 00106 bool isConstant() const { return Tag == constant; } 00107 bool isNotConstant() const { return Tag == notconstant; } 00108 bool isConstantRange() const { return Tag == constantrange; } 00109 bool isOverdefined() const { return Tag == overdefined; } 00110 00111 Constant *getConstant() const { 00112 assert(isConstant() && "Cannot get the constant of a non-constant!"); 00113 return Val; 00114 } 00115 00116 Constant *getNotConstant() const { 00117 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!"); 00118 return Val; 00119 } 00120 00121 ConstantRange getConstantRange() const { 00122 assert(isConstantRange() && 00123 "Cannot get the constant-range of a non-constant-range!"); 00124 return Range; 00125 } 00126 00127 /// markOverdefined - Return true if this is a change in status. 00128 bool markOverdefined() { 00129 if (isOverdefined()) 00130 return false; 00131 Tag = overdefined; 00132 return true; 00133 } 00134 00135 /// markConstant - Return true if this is a change in status. 00136 bool markConstant(Constant *V) { 00137 assert(V && "Marking constant with NULL"); 00138 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 00139 return markConstantRange(ConstantRange(CI->getValue())); 00140 if (isa<UndefValue>(V)) 00141 return false; 00142 00143 assert((!isConstant() || getConstant() == V) && 00144 "Marking constant with different value"); 00145 assert(isUndefined()); 00146 Tag = constant; 00147 Val = V; 00148 return true; 00149 } 00150 00151 /// markNotConstant - Return true if this is a change in status. 00152 bool markNotConstant(Constant *V) { 00153 assert(V && "Marking constant with NULL"); 00154 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 00155 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue())); 00156 if (isa<UndefValue>(V)) 00157 return false; 00158 00159 assert((!isConstant() || getConstant() != V) && 00160 "Marking constant !constant with same value"); 00161 assert((!isNotConstant() || getNotConstant() == V) && 00162 "Marking !constant with different value"); 00163 assert(isUndefined() || isConstant()); 00164 Tag = notconstant; 00165 Val = V; 00166 return true; 00167 } 00168 00169 /// markConstantRange - Return true if this is a change in status. 00170 bool markConstantRange(const ConstantRange NewR) { 00171 if (isConstantRange()) { 00172 if (NewR.isEmptySet()) 00173 return markOverdefined(); 00174 00175 bool changed = Range != NewR; 00176 Range = NewR; 00177 return changed; 00178 } 00179 00180 assert(isUndefined()); 00181 if (NewR.isEmptySet()) 00182 return markOverdefined(); 00183 00184 Tag = constantrange; 00185 Range = NewR; 00186 return true; 00187 } 00188 00189 /// mergeIn - Merge the specified lattice value into this one, updating this 00190 /// one and returning true if anything changed. 00191 bool mergeIn(const LVILatticeVal &RHS) { 00192 if (RHS.isUndefined() || isOverdefined()) return false; 00193 if (RHS.isOverdefined()) return markOverdefined(); 00194 00195 if (isUndefined()) { 00196 Tag = RHS.Tag; 00197 Val = RHS.Val; 00198 Range = RHS.Range; 00199 return true; 00200 } 00201 00202 if (isConstant()) { 00203 if (RHS.isConstant()) { 00204 if (Val == RHS.Val) 00205 return false; 00206 return markOverdefined(); 00207 } 00208 00209 if (RHS.isNotConstant()) { 00210 if (Val == RHS.Val) 00211 return markOverdefined(); 00212 00213 // Unless we can prove that the two Constants are different, we must 00214 // move to overdefined. 00215 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding. 00216 if (ConstantInt *Res = dyn_cast<ConstantInt>( 00217 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE, 00218 getConstant(), 00219 RHS.getNotConstant()))) 00220 if (Res->isOne()) 00221 return markNotConstant(RHS.getNotConstant()); 00222 00223 return markOverdefined(); 00224 } 00225 00226 // RHS is a ConstantRange, LHS is a non-integer Constant. 00227 00228 // FIXME: consider the case where RHS is a range [1, 0) and LHS is 00229 // a function. The correct result is to pick up RHS. 00230 00231 return markOverdefined(); 00232 } 00233 00234 if (isNotConstant()) { 00235 if (RHS.isConstant()) { 00236 if (Val == RHS.Val) 00237 return markOverdefined(); 00238 00239 // Unless we can prove that the two Constants are different, we must 00240 // move to overdefined. 00241 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding. 00242 if (ConstantInt *Res = dyn_cast<ConstantInt>( 00243 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE, 00244 getNotConstant(), 00245 RHS.getConstant()))) 00246 if (Res->isOne()) 00247 return false; 00248 00249 return markOverdefined(); 00250 } 00251 00252 if (RHS.isNotConstant()) { 00253 if (Val == RHS.Val) 00254 return false; 00255 return markOverdefined(); 00256 } 00257 00258 return markOverdefined(); 00259 } 00260 00261 assert(isConstantRange() && "New LVILattice type?"); 00262 if (!RHS.isConstantRange()) 00263 return markOverdefined(); 00264 00265 ConstantRange NewR = Range.unionWith(RHS.getConstantRange()); 00266 if (NewR.isFullSet()) 00267 return markOverdefined(); 00268 return markConstantRange(NewR); 00269 } 00270 }; 00271 00272 } // end anonymous namespace. 00273 00274 namespace llvm { 00275 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) 00276 LLVM_ATTRIBUTE_USED; 00277 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) { 00278 if (Val.isUndefined()) 00279 return OS << "undefined"; 00280 if (Val.isOverdefined()) 00281 return OS << "overdefined"; 00282 00283 if (Val.isNotConstant()) 00284 return OS << "notconstant<" << *Val.getNotConstant() << '>'; 00285 else if (Val.isConstantRange()) 00286 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", " 00287 << Val.getConstantRange().getUpper() << '>'; 00288 return OS << "constant<" << *Val.getConstant() << '>'; 00289 } 00290 } 00291 00292 //===----------------------------------------------------------------------===// 00293 // LazyValueInfoCache Decl 00294 //===----------------------------------------------------------------------===// 00295 00296 namespace { 00297 /// LVIValueHandle - A callback value handle updates the cache when 00298 /// values are erased. 00299 class LazyValueInfoCache; 00300 struct LVIValueHandle : public CallbackVH { 00301 LazyValueInfoCache *Parent; 00302 00303 LVIValueHandle(Value *V, LazyValueInfoCache *P) 00304 : CallbackVH(V), Parent(P) { } 00305 00306 void deleted(); 00307 void allUsesReplacedWith(Value *V) { 00308 deleted(); 00309 } 00310 }; 00311 } 00312 00313 namespace { 00314 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which 00315 /// maintains information about queries across the clients' queries. 00316 class LazyValueInfoCache { 00317 /// ValueCacheEntryTy - This is all of the cached block information for 00318 /// exactly one Value*. The entries are sorted by the BasicBlock* of the 00319 /// entries, allowing us to do a lookup with a binary search. 00320 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy; 00321 00322 /// ValueCache - This is all of the cached information for all values, 00323 /// mapped from Value* to key information. 00324 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache; 00325 00326 /// OverDefinedCache - This tracks, on a per-block basis, the set of 00327 /// values that are over-defined at the end of that block. This is required 00328 /// for cache updating. 00329 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy; 00330 DenseSet<OverDefinedPairTy> OverDefinedCache; 00331 00332 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we 00333 /// don't spend time removing unused blocks from our caches. 00334 DenseSet<AssertingVH<BasicBlock> > SeenBlocks; 00335 00336 /// BlockValueStack - This stack holds the state of the value solver 00337 /// during a query. It basically emulates the callstack of the naive 00338 /// recursive value lookup process. 00339 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack; 00340 00341 friend struct LVIValueHandle; 00342 00343 /// OverDefinedCacheUpdater - A helper object that ensures that the 00344 /// OverDefinedCache is updated whenever solveBlockValue returns. 00345 struct OverDefinedCacheUpdater { 00346 LazyValueInfoCache *Parent; 00347 Value *Val; 00348 BasicBlock *BB; 00349 LVILatticeVal &BBLV; 00350 00351 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV, 00352 LazyValueInfoCache *P) 00353 : Parent(P), Val(V), BB(B), BBLV(LV) { } 00354 00355 bool markResult(bool changed) { 00356 if (changed && BBLV.isOverdefined()) 00357 Parent->OverDefinedCache.insert(std::make_pair(BB, Val)); 00358 return changed; 00359 } 00360 }; 00361 00362 00363 00364 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB); 00365 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T, 00366 LVILatticeVal &Result); 00367 bool hasBlockValue(Value *Val, BasicBlock *BB); 00368 00369 // These methods process one work item and may add more. A false value 00370 // returned means that the work item was not completely processed and must 00371 // be revisited after going through the new items. 00372 bool solveBlockValue(Value *Val, BasicBlock *BB); 00373 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, 00374 Value *Val, BasicBlock *BB); 00375 bool solveBlockValuePHINode(LVILatticeVal &BBLV, 00376 PHINode *PN, BasicBlock *BB); 00377 bool solveBlockValueConstantRange(LVILatticeVal &BBLV, 00378 Instruction *BBI, BasicBlock *BB); 00379 00380 void solve(); 00381 00382 ValueCacheEntryTy &lookup(Value *V) { 00383 return ValueCache[LVIValueHandle(V, this)]; 00384 } 00385 00386 public: 00387 /// getValueInBlock - This is the query interface to determine the lattice 00388 /// value for the specified Value* at the end of the specified block. 00389 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB); 00390 00391 /// getValueOnEdge - This is the query interface to determine the lattice 00392 /// value for the specified Value* that is true on the specified edge. 00393 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB); 00394 00395 /// threadEdge - This is the update interface to inform the cache that an 00396 /// edge from PredBB to OldSucc has been threaded to be from PredBB to 00397 /// NewSucc. 00398 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc); 00399 00400 /// eraseBlock - This is part of the update interface to inform the cache 00401 /// that a block has been deleted. 00402 void eraseBlock(BasicBlock *BB); 00403 00404 /// clear - Empty the cache. 00405 void clear() { 00406 SeenBlocks.clear(); 00407 ValueCache.clear(); 00408 OverDefinedCache.clear(); 00409 } 00410 }; 00411 } // end anonymous namespace 00412 00413 void LVIValueHandle::deleted() { 00414 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy; 00415 00416 SmallVector<OverDefinedPairTy, 4> ToErase; 00417 for (DenseSet<OverDefinedPairTy>::iterator 00418 I = Parent->OverDefinedCache.begin(), 00419 E = Parent->OverDefinedCache.end(); 00420 I != E; ++I) { 00421 if (I->second == getValPtr()) 00422 ToErase.push_back(*I); 00423 } 00424 00425 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(), 00426 E = ToErase.end(); I != E; ++I) 00427 Parent->OverDefinedCache.erase(*I); 00428 00429 // This erasure deallocates *this, so it MUST happen after we're done 00430 // using any and all members of *this. 00431 Parent->ValueCache.erase(*this); 00432 } 00433 00434 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) { 00435 // Shortcut if we have never seen this block. 00436 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB); 00437 if (I == SeenBlocks.end()) 00438 return; 00439 SeenBlocks.erase(I); 00440 00441 SmallVector<OverDefinedPairTy, 4> ToErase; 00442 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(), 00443 E = OverDefinedCache.end(); I != E; ++I) { 00444 if (I->first == BB) 00445 ToErase.push_back(*I); 00446 } 00447 00448 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(), 00449 E = ToErase.end(); I != E; ++I) 00450 OverDefinedCache.erase(*I); 00451 00452 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator 00453 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I) 00454 I->second.erase(BB); 00455 } 00456 00457 void LazyValueInfoCache::solve() { 00458 while (!BlockValueStack.empty()) { 00459 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top(); 00460 if (solveBlockValue(e.second, e.first)) { 00461 assert(BlockValueStack.top() == e); 00462 BlockValueStack.pop(); 00463 } 00464 } 00465 } 00466 00467 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) { 00468 // If already a constant, there is nothing to compute. 00469 if (isa<Constant>(Val)) 00470 return true; 00471 00472 LVIValueHandle ValHandle(Val, this); 00473 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I = 00474 ValueCache.find(ValHandle); 00475 if (I == ValueCache.end()) return false; 00476 return I->second.count(BB); 00477 } 00478 00479 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) { 00480 // If already a constant, there is nothing to compute. 00481 if (Constant *VC = dyn_cast<Constant>(Val)) 00482 return LVILatticeVal::get(VC); 00483 00484 SeenBlocks.insert(BB); 00485 return lookup(Val)[BB]; 00486 } 00487 00488 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) { 00489 if (isa<Constant>(Val)) 00490 return true; 00491 00492 ValueCacheEntryTy &Cache = lookup(Val); 00493 SeenBlocks.insert(BB); 00494 LVILatticeVal &BBLV = Cache[BB]; 00495 00496 // OverDefinedCacheUpdater is a helper object that will update 00497 // the OverDefinedCache for us when this method exits. Make sure to 00498 // call markResult on it as we exist, passing a bool to indicate if the 00499 // cache needs updating, i.e. if we have solve a new value or not. 00500 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this); 00501 00502 // If we've already computed this block's value, return it. 00503 if (!BBLV.isUndefined()) { 00504 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n'); 00505 00506 // Since we're reusing a cached value here, we don't need to update the 00507 // OverDefinedCahce. The cache will have been properly updated 00508 // whenever the cached value was inserted. 00509 ODCacheUpdater.markResult(false); 00510 return true; 00511 } 00512 00513 // Otherwise, this is the first time we're seeing this block. Reset the 00514 // lattice value to overdefined, so that cycles will terminate and be 00515 // conservatively correct. 00516 BBLV.markOverdefined(); 00517 00518 Instruction *BBI = dyn_cast<Instruction>(Val); 00519 if (BBI == 0 || BBI->getParent() != BB) { 00520 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB)); 00521 } 00522 00523 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 00524 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB)); 00525 } 00526 00527 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) { 00528 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType())); 00529 return ODCacheUpdater.markResult(true); 00530 } 00531 00532 // We can only analyze the definitions of certain classes of instructions 00533 // (integral binops and casts at the moment), so bail if this isn't one. 00534 LVILatticeVal Result; 00535 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) || 00536 !BBI->getType()->isIntegerTy()) { 00537 DEBUG(dbgs() << " compute BB '" << BB->getName() 00538 << "' - overdefined because inst def found.\n"); 00539 BBLV.markOverdefined(); 00540 return ODCacheUpdater.markResult(true); 00541 } 00542 00543 // FIXME: We're currently limited to binops with a constant RHS. This should 00544 // be improved. 00545 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI); 00546 if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 00547 DEBUG(dbgs() << " compute BB '" << BB->getName() 00548 << "' - overdefined because inst def found.\n"); 00549 00550 BBLV.markOverdefined(); 00551 return ODCacheUpdater.markResult(true); 00552 } 00553 00554 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB)); 00555 } 00556 00557 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) { 00558 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 00559 return L->getPointerAddressSpace() == 0 && 00560 GetUnderlyingObject(L->getPointerOperand()) == Ptr; 00561 } 00562 if (StoreInst *S = dyn_cast<StoreInst>(I)) { 00563 return S->getPointerAddressSpace() == 0 && 00564 GetUnderlyingObject(S->getPointerOperand()) == Ptr; 00565 } 00566 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) { 00567 if (MI->isVolatile()) return false; 00568 00569 // FIXME: check whether it has a valuerange that excludes zero? 00570 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength()); 00571 if (!Len || Len->isZero()) return false; 00572 00573 if (MI->getDestAddressSpace() == 0) 00574 if (GetUnderlyingObject(MI->getRawDest()) == Ptr) 00575 return true; 00576 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) 00577 if (MTI->getSourceAddressSpace() == 0) 00578 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr) 00579 return true; 00580 } 00581 return false; 00582 } 00583 00584 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV, 00585 Value *Val, BasicBlock *BB) { 00586 LVILatticeVal Result; // Start Undefined. 00587 00588 // If this is a pointer, and there's a load from that pointer in this BB, 00589 // then we know that the pointer can't be NULL. 00590 bool NotNull = false; 00591 if (Val->getType()->isPointerTy()) { 00592 if (isKnownNonNull(Val)) { 00593 NotNull = true; 00594 } else { 00595 Value *UnderlyingVal = GetUnderlyingObject(Val); 00596 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge 00597 // inside InstructionDereferencesPointer either. 00598 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, NULL, 1)) { 00599 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 00600 BI != BE; ++BI) { 00601 if (InstructionDereferencesPointer(BI, UnderlyingVal)) { 00602 NotNull = true; 00603 break; 00604 } 00605 } 00606 } 00607 } 00608 } 00609 00610 // If this is the entry block, we must be asking about an argument. The 00611 // value is overdefined. 00612 if (BB == &BB->getParent()->getEntryBlock()) { 00613 assert(isa<Argument>(Val) && "Unknown live-in to the entry block"); 00614 if (NotNull) { 00615 PointerType *PTy = cast<PointerType>(Val->getType()); 00616 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 00617 } else { 00618 Result.markOverdefined(); 00619 } 00620 BBLV = Result; 00621 return true; 00622 } 00623 00624 // Loop over all of our predecessors, merging what we know from them into 00625 // result. 00626 bool EdgesMissing = false; 00627 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 00628 LVILatticeVal EdgeResult; 00629 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult); 00630 if (EdgesMissing) 00631 continue; 00632 00633 Result.mergeIn(EdgeResult); 00634 00635 // If we hit overdefined, exit early. The BlockVals entry is already set 00636 // to overdefined. 00637 if (Result.isOverdefined()) { 00638 DEBUG(dbgs() << " compute BB '" << BB->getName() 00639 << "' - overdefined because of pred.\n"); 00640 // If we previously determined that this is a pointer that can't be null 00641 // then return that rather than giving up entirely. 00642 if (NotNull) { 00643 PointerType *PTy = cast<PointerType>(Val->getType()); 00644 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 00645 } 00646 00647 BBLV = Result; 00648 return true; 00649 } 00650 } 00651 if (EdgesMissing) 00652 return false; 00653 00654 // Return the merged value, which is more precise than 'overdefined'. 00655 assert(!Result.isOverdefined()); 00656 BBLV = Result; 00657 return true; 00658 } 00659 00660 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV, 00661 PHINode *PN, BasicBlock *BB) { 00662 LVILatticeVal Result; // Start Undefined. 00663 00664 // Loop over all of our predecessors, merging what we know from them into 00665 // result. 00666 bool EdgesMissing = false; 00667 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 00668 BasicBlock *PhiBB = PN->getIncomingBlock(i); 00669 Value *PhiVal = PN->getIncomingValue(i); 00670 LVILatticeVal EdgeResult; 00671 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult); 00672 if (EdgesMissing) 00673 continue; 00674 00675 Result.mergeIn(EdgeResult); 00676 00677 // If we hit overdefined, exit early. The BlockVals entry is already set 00678 // to overdefined. 00679 if (Result.isOverdefined()) { 00680 DEBUG(dbgs() << " compute BB '" << BB->getName() 00681 << "' - overdefined because of pred.\n"); 00682 00683 BBLV = Result; 00684 return true; 00685 } 00686 } 00687 if (EdgesMissing) 00688 return false; 00689 00690 // Return the merged value, which is more precise than 'overdefined'. 00691 assert(!Result.isOverdefined() && "Possible PHI in entry block?"); 00692 BBLV = Result; 00693 return true; 00694 } 00695 00696 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV, 00697 Instruction *BBI, 00698 BasicBlock *BB) { 00699 // Figure out the range of the LHS. If that fails, bail. 00700 if (!hasBlockValue(BBI->getOperand(0), BB)) { 00701 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0))); 00702 return false; 00703 } 00704 00705 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB); 00706 if (!LHSVal.isConstantRange()) { 00707 BBLV.markOverdefined(); 00708 return true; 00709 } 00710 00711 ConstantRange LHSRange = LHSVal.getConstantRange(); 00712 ConstantRange RHSRange(1); 00713 IntegerType *ResultTy = cast<IntegerType>(BBI->getType()); 00714 if (isa<BinaryOperator>(BBI)) { 00715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) { 00716 RHSRange = ConstantRange(RHS->getValue()); 00717 } else { 00718 BBLV.markOverdefined(); 00719 return true; 00720 } 00721 } 00722 00723 // NOTE: We're currently limited by the set of operations that ConstantRange 00724 // can evaluate symbolically. Enhancing that set will allows us to analyze 00725 // more definitions. 00726 LVILatticeVal Result; 00727 switch (BBI->getOpcode()) { 00728 case Instruction::Add: 00729 Result.markConstantRange(LHSRange.add(RHSRange)); 00730 break; 00731 case Instruction::Sub: 00732 Result.markConstantRange(LHSRange.sub(RHSRange)); 00733 break; 00734 case Instruction::Mul: 00735 Result.markConstantRange(LHSRange.multiply(RHSRange)); 00736 break; 00737 case Instruction::UDiv: 00738 Result.markConstantRange(LHSRange.udiv(RHSRange)); 00739 break; 00740 case Instruction::Shl: 00741 Result.markConstantRange(LHSRange.shl(RHSRange)); 00742 break; 00743 case Instruction::LShr: 00744 Result.markConstantRange(LHSRange.lshr(RHSRange)); 00745 break; 00746 case Instruction::Trunc: 00747 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth())); 00748 break; 00749 case Instruction::SExt: 00750 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth())); 00751 break; 00752 case Instruction::ZExt: 00753 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth())); 00754 break; 00755 case Instruction::BitCast: 00756 Result.markConstantRange(LHSRange); 00757 break; 00758 case Instruction::And: 00759 Result.markConstantRange(LHSRange.binaryAnd(RHSRange)); 00760 break; 00761 case Instruction::Or: 00762 Result.markConstantRange(LHSRange.binaryOr(RHSRange)); 00763 break; 00764 00765 // Unhandled instructions are overdefined. 00766 default: 00767 DEBUG(dbgs() << " compute BB '" << BB->getName() 00768 << "' - overdefined because inst def found.\n"); 00769 Result.markOverdefined(); 00770 break; 00771 } 00772 00773 BBLV = Result; 00774 return true; 00775 } 00776 00777 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if 00778 /// Val is not constrained on the edge. 00779 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom, 00780 BasicBlock *BBTo, LVILatticeVal &Result) { 00781 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we 00782 // know that v != 0. 00783 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) { 00784 // If this is a conditional branch and only one successor goes to BBTo, then 00785 // we maybe able to infer something from the condition. 00786 if (BI->isConditional() && 00787 BI->getSuccessor(0) != BI->getSuccessor(1)) { 00788 bool isTrueDest = BI->getSuccessor(0) == BBTo; 00789 assert(BI->getSuccessor(!isTrueDest) == BBTo && 00790 "BBTo isn't a successor of BBFrom"); 00791 00792 // If V is the condition of the branch itself, then we know exactly what 00793 // it is. 00794 if (BI->getCondition() == Val) { 00795 Result = LVILatticeVal::get(ConstantInt::get( 00796 Type::getInt1Ty(Val->getContext()), isTrueDest)); 00797 return true; 00798 } 00799 00800 // If the condition of the branch is an equality comparison, we may be 00801 // able to infer the value. 00802 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()); 00803 if (ICI && isa<Constant>(ICI->getOperand(1))) { 00804 if (ICI->isEquality() && ICI->getOperand(0) == Val) { 00805 // We know that V has the RHS constant if this is a true SETEQ or 00806 // false SETNE. 00807 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ)) 00808 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1))); 00809 else 00810 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1))); 00811 return true; 00812 } 00813 00814 // Recognize the range checking idiom that InstCombine produces. 00815 // (X-C1) u< C2 --> [C1, C1+C2) 00816 ConstantInt *NegOffset = 0; 00817 if (ICI->getPredicate() == ICmpInst::ICMP_ULT) 00818 match(ICI->getOperand(0), m_Add(m_Specific(Val), 00819 m_ConstantInt(NegOffset))); 00820 00821 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1)); 00822 if (CI && (ICI->getOperand(0) == Val || NegOffset)) { 00823 // Calculate the range of values that would satisfy the comparison. 00824 ConstantRange CmpRange(CI->getValue()); 00825 ConstantRange TrueValues = 00826 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange); 00827 00828 if (NegOffset) // Apply the offset from above. 00829 TrueValues = TrueValues.subtract(NegOffset->getValue()); 00830 00831 // If we're interested in the false dest, invert the condition. 00832 if (!isTrueDest) TrueValues = TrueValues.inverse(); 00833 00834 Result = LVILatticeVal::getRange(TrueValues); 00835 return true; 00836 } 00837 } 00838 } 00839 } 00840 00841 // If the edge was formed by a switch on the value, then we may know exactly 00842 // what it is. 00843 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) { 00844 if (SI->getCondition() != Val) 00845 return false; 00846 00847 bool DefaultCase = SI->getDefaultDest() == BBTo; 00848 unsigned BitWidth = Val->getType()->getIntegerBitWidth(); 00849 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/); 00850 00851 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 00852 i != e; ++i) { 00853 ConstantRange EdgeVal(i.getCaseValue()->getValue()); 00854 if (DefaultCase) { 00855 // It is possible that the default destination is the destination of 00856 // some cases. There is no need to perform difference for those cases. 00857 if (i.getCaseSuccessor() != BBTo) 00858 EdgesVals = EdgesVals.difference(EdgeVal); 00859 } else if (i.getCaseSuccessor() == BBTo) 00860 EdgesVals = EdgesVals.unionWith(EdgeVal); 00861 } 00862 Result = LVILatticeVal::getRange(EdgesVals); 00863 return true; 00864 } 00865 return false; 00866 } 00867 00868 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at 00869 /// the basic block if the edge does not constraint Val. 00870 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom, 00871 BasicBlock *BBTo, LVILatticeVal &Result) { 00872 // If already a constant, there is nothing to compute. 00873 if (Constant *VC = dyn_cast<Constant>(Val)) { 00874 Result = LVILatticeVal::get(VC); 00875 return true; 00876 } 00877 00878 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) { 00879 if (!Result.isConstantRange() || 00880 Result.getConstantRange().getSingleElement()) 00881 return true; 00882 00883 // FIXME: this check should be moved to the beginning of the function when 00884 // LVI better supports recursive values. Even for the single value case, we 00885 // can intersect to detect dead code (an empty range). 00886 if (!hasBlockValue(Val, BBFrom)) { 00887 BlockValueStack.push(std::make_pair(BBFrom, Val)); 00888 return false; 00889 } 00890 00891 // Try to intersect ranges of the BB and the constraint on the edge. 00892 LVILatticeVal InBlock = getBlockValue(Val, BBFrom); 00893 if (!InBlock.isConstantRange()) 00894 return true; 00895 00896 ConstantRange Range = 00897 Result.getConstantRange().intersectWith(InBlock.getConstantRange()); 00898 Result = LVILatticeVal::getRange(Range); 00899 return true; 00900 } 00901 00902 if (!hasBlockValue(Val, BBFrom)) { 00903 BlockValueStack.push(std::make_pair(BBFrom, Val)); 00904 return false; 00905 } 00906 00907 // if we couldn't compute the value on the edge, use the value from the BB 00908 Result = getBlockValue(Val, BBFrom); 00909 return true; 00910 } 00911 00912 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) { 00913 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '" 00914 << BB->getName() << "'\n"); 00915 00916 BlockValueStack.push(std::make_pair(BB, V)); 00917 solve(); 00918 LVILatticeVal Result = getBlockValue(V, BB); 00919 00920 DEBUG(dbgs() << " Result = " << Result << "\n"); 00921 return Result; 00922 } 00923 00924 LVILatticeVal LazyValueInfoCache:: 00925 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) { 00926 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '" 00927 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n"); 00928 00929 LVILatticeVal Result; 00930 if (!getEdgeValue(V, FromBB, ToBB, Result)) { 00931 solve(); 00932 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result); 00933 (void)WasFastQuery; 00934 assert(WasFastQuery && "More work to do after problem solved?"); 00935 } 00936 00937 DEBUG(dbgs() << " Result = " << Result << "\n"); 00938 return Result; 00939 } 00940 00941 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 00942 BasicBlock *NewSucc) { 00943 // When an edge in the graph has been threaded, values that we could not 00944 // determine a value for before (i.e. were marked overdefined) may be possible 00945 // to solve now. We do NOT try to proactively update these values. Instead, 00946 // we clear their entries from the cache, and allow lazy updating to recompute 00947 // them when needed. 00948 00949 // The updating process is fairly simple: we need to dropped cached info 00950 // for all values that were marked overdefined in OldSucc, and for those same 00951 // values in any successor of OldSucc (except NewSucc) in which they were 00952 // also marked overdefined. 00953 std::vector<BasicBlock*> worklist; 00954 worklist.push_back(OldSucc); 00955 00956 DenseSet<Value*> ClearSet; 00957 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(), 00958 E = OverDefinedCache.end(); I != E; ++I) { 00959 if (I->first == OldSucc) 00960 ClearSet.insert(I->second); 00961 } 00962 00963 // Use a worklist to perform a depth-first search of OldSucc's successors. 00964 // NOTE: We do not need a visited list since any blocks we have already 00965 // visited will have had their overdefined markers cleared already, and we 00966 // thus won't loop to their successors. 00967 while (!worklist.empty()) { 00968 BasicBlock *ToUpdate = worklist.back(); 00969 worklist.pop_back(); 00970 00971 // Skip blocks only accessible through NewSucc. 00972 if (ToUpdate == NewSucc) continue; 00973 00974 bool changed = false; 00975 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end(); 00976 I != E; ++I) { 00977 // If a value was marked overdefined in OldSucc, and is here too... 00978 DenseSet<OverDefinedPairTy>::iterator OI = 00979 OverDefinedCache.find(std::make_pair(ToUpdate, *I)); 00980 if (OI == OverDefinedCache.end()) continue; 00981 00982 // Remove it from the caches. 00983 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)]; 00984 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate); 00985 00986 assert(CI != Entry.end() && "Couldn't find entry to update?"); 00987 Entry.erase(CI); 00988 OverDefinedCache.erase(OI); 00989 00990 // If we removed anything, then we potentially need to update 00991 // blocks successors too. 00992 changed = true; 00993 } 00994 00995 if (!changed) continue; 00996 00997 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate)); 00998 } 00999 } 01000 01001 //===----------------------------------------------------------------------===// 01002 // LazyValueInfo Impl 01003 //===----------------------------------------------------------------------===// 01004 01005 /// getCache - This lazily constructs the LazyValueInfoCache. 01006 static LazyValueInfoCache &getCache(void *&PImpl) { 01007 if (!PImpl) 01008 PImpl = new LazyValueInfoCache(); 01009 return *static_cast<LazyValueInfoCache*>(PImpl); 01010 } 01011 01012 bool LazyValueInfo::runOnFunction(Function &F) { 01013 if (PImpl) 01014 getCache(PImpl).clear(); 01015 01016 TD = getAnalysisIfAvailable<DataLayout>(); 01017 TLI = &getAnalysis<TargetLibraryInfo>(); 01018 01019 // Fully lazy. 01020 return false; 01021 } 01022 01023 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const { 01024 AU.setPreservesAll(); 01025 AU.addRequired<TargetLibraryInfo>(); 01026 } 01027 01028 void LazyValueInfo::releaseMemory() { 01029 // If the cache was allocated, free it. 01030 if (PImpl) { 01031 delete &getCache(PImpl); 01032 PImpl = 0; 01033 } 01034 } 01035 01036 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) { 01037 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB); 01038 01039 if (Result.isConstant()) 01040 return Result.getConstant(); 01041 if (Result.isConstantRange()) { 01042 ConstantRange CR = Result.getConstantRange(); 01043 if (const APInt *SingleVal = CR.getSingleElement()) 01044 return ConstantInt::get(V->getContext(), *SingleVal); 01045 } 01046 return 0; 01047 } 01048 01049 /// getConstantOnEdge - Determine whether the specified value is known to be a 01050 /// constant on the specified edge. Return null if not. 01051 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB, 01052 BasicBlock *ToBB) { 01053 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB); 01054 01055 if (Result.isConstant()) 01056 return Result.getConstant(); 01057 if (Result.isConstantRange()) { 01058 ConstantRange CR = Result.getConstantRange(); 01059 if (const APInt *SingleVal = CR.getSingleElement()) 01060 return ConstantInt::get(V->getContext(), *SingleVal); 01061 } 01062 return 0; 01063 } 01064 01065 /// getPredicateOnEdge - Determine whether the specified value comparison 01066 /// with a constant is known to be true or false on the specified CFG edge. 01067 /// Pred is a CmpInst predicate. 01068 LazyValueInfo::Tristate 01069 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, 01070 BasicBlock *FromBB, BasicBlock *ToBB) { 01071 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB); 01072 01073 // If we know the value is a constant, evaluate the conditional. 01074 Constant *Res = 0; 01075 if (Result.isConstant()) { 01076 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD, 01077 TLI); 01078 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res)) 01079 return ResCI->isZero() ? False : True; 01080 return Unknown; 01081 } 01082 01083 if (Result.isConstantRange()) { 01084 ConstantInt *CI = dyn_cast<ConstantInt>(C); 01085 if (!CI) return Unknown; 01086 01087 ConstantRange CR = Result.getConstantRange(); 01088 if (Pred == ICmpInst::ICMP_EQ) { 01089 if (!CR.contains(CI->getValue())) 01090 return False; 01091 01092 if (CR.isSingleElement() && CR.contains(CI->getValue())) 01093 return True; 01094 } else if (Pred == ICmpInst::ICMP_NE) { 01095 if (!CR.contains(CI->getValue())) 01096 return True; 01097 01098 if (CR.isSingleElement() && CR.contains(CI->getValue())) 01099 return False; 01100 } 01101 01102 // Handle more complex predicates. 01103 ConstantRange TrueValues = 01104 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue()); 01105 if (TrueValues.contains(CR)) 01106 return True; 01107 if (TrueValues.inverse().contains(CR)) 01108 return False; 01109 return Unknown; 01110 } 01111 01112 if (Result.isNotConstant()) { 01113 // If this is an equality comparison, we can try to fold it knowing that 01114 // "V != C1". 01115 if (Pred == ICmpInst::ICMP_EQ) { 01116 // !C1 == C -> false iff C1 == C. 01117 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 01118 Result.getNotConstant(), C, TD, 01119 TLI); 01120 if (Res->isNullValue()) 01121 return False; 01122 } else if (Pred == ICmpInst::ICMP_NE) { 01123 // !C1 != C -> true iff C1 == C. 01124 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 01125 Result.getNotConstant(), C, TD, 01126 TLI); 01127 if (Res->isNullValue()) 01128 return True; 01129 } 01130 return Unknown; 01131 } 01132 01133 return Unknown; 01134 } 01135 01136 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 01137 BasicBlock *NewSucc) { 01138 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc); 01139 } 01140 01141 void LazyValueInfo::eraseBlock(BasicBlock *BB) { 01142 if (PImpl) getCache(PImpl).eraseBlock(BB); 01143 }