1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interface for lazy computation of value constraint 11 // information. 12 // 13 //===----------------------------------------------------------------------===// 14 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/Intrinsics.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/PatternMatch.h" 32 #include "llvm/IR/ValueHandle.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <map> 36 #include <stack> 37 using namespace llvm; 38 using namespace PatternMatch; 39 40 #define DEBUG_TYPE "lazy-value-info" 41 42 char LazyValueInfoWrapperPass::ID = 0; 43 INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info", 44 "Lazy Value Information Analysis", false, true) 45 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 46 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 47 INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info", 48 "Lazy Value Information Analysis", false, true) 49 50 namespace llvm { 51 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); } 52 } 53 54 char LazyValueAnalysis::PassID; 55 56 //===----------------------------------------------------------------------===// 57 // LVILatticeVal 58 //===----------------------------------------------------------------------===// 59 60 /// This is the information tracked by LazyValueInfo for each value. 61 /// 62 /// FIXME: This is basically just for bringup, this can be made a lot more rich 63 /// in the future. 64 /// 65 namespace { 66 class LVILatticeVal { 67 enum LatticeValueTy { 68 /// This Value has no known value yet. As a result, this implies the 69 /// producing instruction is dead. Caution: We use this as the starting 70 /// state in our local meet rules. In this usage, it's taken to mean 71 /// "nothing known yet". 72 undefined, 73 74 /// This Value has a specific constant value. (For integers, constantrange 75 /// is used instead.) 76 constant, 77 78 /// This Value is known to not have the specified value. (For integers, 79 /// constantrange is used instead.) 80 notconstant, 81 82 /// The Value falls within this range. (Used only for integer typed values.) 83 constantrange, 84 85 /// We can not precisely model the dynamic values this value might take. 86 overdefined 87 }; 88 89 /// Val: This stores the current lattice value along with the Constant* for 90 /// the constant if this is a 'constant' or 'notconstant' value. 91 LatticeValueTy Tag; 92 Constant *Val; 93 ConstantRange Range; 94 95 public: 96 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {} 97 98 static LVILatticeVal get(Constant *C) { 99 LVILatticeVal Res; 100 if (!isa<UndefValue>(C)) 101 Res.markConstant(C); 102 return Res; 103 } 104 static LVILatticeVal getNot(Constant *C) { 105 LVILatticeVal Res; 106 if (!isa<UndefValue>(C)) 107 Res.markNotConstant(C); 108 return Res; 109 } 110 static LVILatticeVal getRange(ConstantRange CR) { 111 LVILatticeVal Res; 112 Res.markConstantRange(std::move(CR)); 113 return Res; 114 } 115 static LVILatticeVal getOverdefined() { 116 LVILatticeVal Res; 117 Res.markOverdefined(); 118 return Res; 119 } 120 121 bool isUndefined() const { return Tag == undefined; } 122 bool isConstant() const { return Tag == constant; } 123 bool isNotConstant() const { return Tag == notconstant; } 124 bool isConstantRange() const { return Tag == constantrange; } 125 bool isOverdefined() const { return Tag == overdefined; } 126 127 Constant *getConstant() const { 128 assert(isConstant() && "Cannot get the constant of a non-constant!"); 129 return Val; 130 } 131 132 Constant *getNotConstant() const { 133 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!"); 134 return Val; 135 } 136 137 ConstantRange getConstantRange() const { 138 assert(isConstantRange() && 139 "Cannot get the constant-range of a non-constant-range!"); 140 return Range; 141 } 142 143 /// Return true if this is a change in status. 144 bool markOverdefined() { 145 if (isOverdefined()) 146 return false; 147 Tag = overdefined; 148 return true; 149 } 150 151 /// Return true if this is a change in status. 152 bool markConstant(Constant *V) { 153 assert(V && "Marking constant with NULL"); 154 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 155 return markConstantRange(ConstantRange(CI->getValue())); 156 if (isa<UndefValue>(V)) 157 return false; 158 159 assert((!isConstant() || getConstant() == V) && 160 "Marking constant with different value"); 161 assert(isUndefined()); 162 Tag = constant; 163 Val = V; 164 return true; 165 } 166 167 /// Return true if this is a change in status. 168 bool markNotConstant(Constant *V) { 169 assert(V && "Marking constant with NULL"); 170 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 171 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue())); 172 if (isa<UndefValue>(V)) 173 return false; 174 175 assert((!isConstant() || getConstant() != V) && 176 "Marking constant !constant with same value"); 177 assert((!isNotConstant() || getNotConstant() == V) && 178 "Marking !constant with different value"); 179 assert(isUndefined() || isConstant()); 180 Tag = notconstant; 181 Val = V; 182 return true; 183 } 184 185 /// Return true if this is a change in status. 186 bool markConstantRange(ConstantRange NewR) { 187 if (isConstantRange()) { 188 if (NewR.isEmptySet()) 189 return markOverdefined(); 190 191 bool changed = Range != NewR; 192 Range = std::move(NewR); 193 return changed; 194 } 195 196 assert(isUndefined()); 197 if (NewR.isEmptySet()) 198 return markOverdefined(); 199 200 Tag = constantrange; 201 Range = std::move(NewR); 202 return true; 203 } 204 205 /// Merge the specified lattice value into this one, updating this 206 /// one and returning true if anything changed. 207 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) { 208 if (RHS.isUndefined() || isOverdefined()) return false; 209 if (RHS.isOverdefined()) return markOverdefined(); 210 211 if (isUndefined()) { 212 Tag = RHS.Tag; 213 Val = RHS.Val; 214 Range = RHS.Range; 215 return true; 216 } 217 218 if (isConstant()) { 219 if (RHS.isConstant()) { 220 if (Val == RHS.Val) 221 return false; 222 return markOverdefined(); 223 } 224 225 if (RHS.isNotConstant()) { 226 if (Val == RHS.Val) 227 return markOverdefined(); 228 229 // Unless we can prove that the two Constants are different, we must 230 // move to overdefined. 231 if (ConstantInt *Res = 232 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands( 233 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL))) 234 if (Res->isOne()) 235 return markNotConstant(RHS.getNotConstant()); 236 237 return markOverdefined(); 238 } 239 240 return markOverdefined(); 241 } 242 243 if (isNotConstant()) { 244 if (RHS.isConstant()) { 245 if (Val == RHS.Val) 246 return markOverdefined(); 247 248 // Unless we can prove that the two Constants are different, we must 249 // move to overdefined. 250 if (ConstantInt *Res = 251 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands( 252 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL))) 253 if (Res->isOne()) 254 return false; 255 256 return markOverdefined(); 257 } 258 259 if (RHS.isNotConstant()) { 260 if (Val == RHS.Val) 261 return false; 262 return markOverdefined(); 263 } 264 265 return markOverdefined(); 266 } 267 268 assert(isConstantRange() && "New LVILattice type?"); 269 if (!RHS.isConstantRange()) 270 return markOverdefined(); 271 272 ConstantRange NewR = Range.unionWith(RHS.getConstantRange()); 273 if (NewR.isFullSet()) 274 return markOverdefined(); 275 return markConstantRange(NewR); 276 } 277 }; 278 279 } // end anonymous namespace. 280 281 namespace llvm { 282 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) 283 LLVM_ATTRIBUTE_USED; 284 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) { 285 if (Val.isUndefined()) 286 return OS << "undefined"; 287 if (Val.isOverdefined()) 288 return OS << "overdefined"; 289 290 if (Val.isNotConstant()) 291 return OS << "notconstant<" << *Val.getNotConstant() << '>'; 292 if (Val.isConstantRange()) 293 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", " 294 << Val.getConstantRange().getUpper() << '>'; 295 return OS << "constant<" << *Val.getConstant() << '>'; 296 } 297 } 298 299 /// Returns true if this lattice value represents at most one possible value. 300 /// This is as precise as any lattice value can get while still representing 301 /// reachable code. 302 static bool hasSingleValue(const LVILatticeVal &Val) { 303 if (Val.isConstantRange() && 304 Val.getConstantRange().isSingleElement()) 305 // Integer constants are single element ranges 306 return true; 307 if (Val.isConstant()) 308 // Non integer constants 309 return true; 310 return false; 311 } 312 313 /// Combine two sets of facts about the same value into a single set of 314 /// facts. Note that this method is not suitable for merging facts along 315 /// different paths in a CFG; that's what the mergeIn function is for. This 316 /// is for merging facts gathered about the same value at the same location 317 /// through two independent means. 318 /// Notes: 319 /// * This method does not promise to return the most precise possible lattice 320 /// value implied by A and B. It is allowed to return any lattice element 321 /// which is at least as strong as *either* A or B (unless our facts 322 /// conflict, see below). 323 /// * Due to unreachable code, the intersection of two lattice values could be 324 /// contradictory. If this happens, we return some valid lattice value so as 325 /// not confuse the rest of LVI. Ideally, we'd always return Undefined, but 326 /// we do not make this guarantee. TODO: This would be a useful enhancement. 327 static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) { 328 // Undefined is the strongest state. It means the value is known to be along 329 // an unreachable path. 330 if (A.isUndefined()) 331 return A; 332 if (B.isUndefined()) 333 return B; 334 335 // If we gave up for one, but got a useable fact from the other, use it. 336 if (A.isOverdefined()) 337 return B; 338 if (B.isOverdefined()) 339 return A; 340 341 // Can't get any more precise than constants. 342 if (hasSingleValue(A)) 343 return A; 344 if (hasSingleValue(B)) 345 return B; 346 347 // Could be either constant range or not constant here. 348 if (!A.isConstantRange() || !B.isConstantRange()) { 349 // TODO: Arbitrary choice, could be improved 350 return A; 351 } 352 353 // Intersect two constant ranges 354 ConstantRange Range = 355 A.getConstantRange().intersectWith(B.getConstantRange()); 356 // Note: An empty range is implicitly converted to overdefined internally. 357 // TODO: We could instead use Undefined here since we've proven a conflict 358 // and thus know this path must be unreachable. 359 return LVILatticeVal::getRange(std::move(Range)); 360 } 361 362 //===----------------------------------------------------------------------===// 363 // LazyValueInfoCache Decl 364 //===----------------------------------------------------------------------===// 365 366 namespace { 367 /// A callback value handle updates the cache when values are erased. 368 class LazyValueInfoCache; 369 struct LVIValueHandle final : public CallbackVH { 370 // Needs to access getValPtr(), which is protected. 371 friend struct DenseMapInfo<LVIValueHandle>; 372 373 LazyValueInfoCache *Parent; 374 375 LVIValueHandle(Value *V, LazyValueInfoCache *P) 376 : CallbackVH(V), Parent(P) { } 377 378 void deleted() override; 379 void allUsesReplacedWith(Value *V) override { 380 deleted(); 381 } 382 }; 383 } // end anonymous namespace 384 385 namespace { 386 /// This is the cache kept by LazyValueInfo which 387 /// maintains information about queries across the clients' queries. 388 class LazyValueInfoCache { 389 /// This is all of the cached block information for exactly one Value*. 390 /// The entries are sorted by the BasicBlock* of the 391 /// entries, allowing us to do a lookup with a binary search. 392 /// Over-defined lattice values are recorded in OverDefinedCache to reduce 393 /// memory overhead. 394 struct ValueCacheEntryTy { 395 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {} 396 LVIValueHandle Handle; 397 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals; 398 }; 399 400 /// This is all of the cached information for all values, 401 /// mapped from Value* to key information. 402 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache; 403 404 /// This tracks, on a per-block basis, the set of values that are 405 /// over-defined at the end of that block. 406 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>> 407 OverDefinedCacheTy; 408 OverDefinedCacheTy OverDefinedCache; 409 410 /// Keep track of all blocks that we have ever seen, so we 411 /// don't spend time removing unused blocks from our caches. 412 DenseSet<AssertingVH<BasicBlock> > SeenBlocks; 413 414 public: 415 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) { 416 SeenBlocks.insert(BB); 417 418 // Insert over-defined values into their own cache to reduce memory 419 // overhead. 420 if (Result.isOverdefined()) 421 OverDefinedCache[BB].insert(Val); 422 else { 423 auto It = ValueCache.find_as(Val); 424 if (It == ValueCache.end()) { 425 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this); 426 It = ValueCache.find_as(Val); 427 assert(It != ValueCache.end() && "Val was just added to the map!"); 428 } 429 It->second->BlockVals[BB] = Result; 430 } 431 } 432 433 bool isOverdefined(Value *V, BasicBlock *BB) const { 434 auto ODI = OverDefinedCache.find(BB); 435 436 if (ODI == OverDefinedCache.end()) 437 return false; 438 439 return ODI->second.count(V); 440 } 441 442 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const { 443 if (isOverdefined(V, BB)) 444 return true; 445 446 auto I = ValueCache.find_as(V); 447 if (I == ValueCache.end()) 448 return false; 449 450 return I->second->BlockVals.count(BB); 451 } 452 453 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const { 454 if (isOverdefined(V, BB)) 455 return LVILatticeVal::getOverdefined(); 456 457 auto I = ValueCache.find_as(V); 458 if (I == ValueCache.end()) 459 return LVILatticeVal(); 460 auto BBI = I->second->BlockVals.find(BB); 461 if (BBI == I->second->BlockVals.end()) 462 return LVILatticeVal(); 463 return BBI->second; 464 } 465 466 /// clear - Empty the cache. 467 void clear() { 468 SeenBlocks.clear(); 469 ValueCache.clear(); 470 OverDefinedCache.clear(); 471 } 472 473 /// Inform the cache that a given value has been deleted. 474 void eraseValue(Value *V); 475 476 /// This is part of the update interface to inform the cache 477 /// that a block has been deleted. 478 void eraseBlock(BasicBlock *BB); 479 480 /// Updates the cache to remove any influence an overdefined value in 481 /// OldSucc might have (unless also overdefined in NewSucc). This just 482 /// flushes elements from the cache and does not add any. 483 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc); 484 485 friend struct LVIValueHandle; 486 }; 487 } 488 489 void LazyValueInfoCache::eraseValue(Value *V) { 490 SmallVector<AssertingVH<BasicBlock>, 4> ToErase; 491 for (auto &I : OverDefinedCache) { 492 SmallPtrSetImpl<Value *> &ValueSet = I.second; 493 if (ValueSet.count(V)) 494 ValueSet.erase(V); 495 if (ValueSet.empty()) 496 ToErase.push_back(I.first); 497 } 498 for (auto &BB : ToErase) 499 OverDefinedCache.erase(BB); 500 501 ValueCache.erase(V); 502 } 503 504 void LVIValueHandle::deleted() { 505 // This erasure deallocates *this, so it MUST happen after we're done 506 // using any and all members of *this. 507 Parent->eraseValue(*this); 508 } 509 510 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) { 511 // Shortcut if we have never seen this block. 512 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB); 513 if (I == SeenBlocks.end()) 514 return; 515 SeenBlocks.erase(I); 516 517 auto ODI = OverDefinedCache.find(BB); 518 if (ODI != OverDefinedCache.end()) 519 OverDefinedCache.erase(ODI); 520 521 for (auto &I : ValueCache) 522 I.second->BlockVals.erase(BB); 523 } 524 525 void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc, 526 BasicBlock *NewSucc) { 527 // When an edge in the graph has been threaded, values that we could not 528 // determine a value for before (i.e. were marked overdefined) may be 529 // possible to solve now. We do NOT try to proactively update these values. 530 // Instead, we clear their entries from the cache, and allow lazy updating to 531 // recompute them when needed. 532 533 // The updating process is fairly simple: we need to drop cached info 534 // for all values that were marked overdefined in OldSucc, and for those same 535 // values in any successor of OldSucc (except NewSucc) in which they were 536 // also marked overdefined. 537 std::vector<BasicBlock*> worklist; 538 worklist.push_back(OldSucc); 539 540 auto I = OverDefinedCache.find(OldSucc); 541 if (I == OverDefinedCache.end()) 542 return; // Nothing to process here. 543 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end()); 544 545 // Use a worklist to perform a depth-first search of OldSucc's successors. 546 // NOTE: We do not need a visited list since any blocks we have already 547 // visited will have had their overdefined markers cleared already, and we 548 // thus won't loop to their successors. 549 while (!worklist.empty()) { 550 BasicBlock *ToUpdate = worklist.back(); 551 worklist.pop_back(); 552 553 // Skip blocks only accessible through NewSucc. 554 if (ToUpdate == NewSucc) continue; 555 556 bool changed = false; 557 for (Value *V : ValsToClear) { 558 // If a value was marked overdefined in OldSucc, and is here too... 559 auto OI = OverDefinedCache.find(ToUpdate); 560 if (OI == OverDefinedCache.end()) 561 continue; 562 SmallPtrSetImpl<Value *> &ValueSet = OI->second; 563 if (!ValueSet.count(V)) 564 continue; 565 566 ValueSet.erase(V); 567 if (ValueSet.empty()) 568 OverDefinedCache.erase(OI); 569 570 // If we removed anything, then we potentially need to update 571 // blocks successors too. 572 changed = true; 573 } 574 575 if (!changed) continue; 576 577 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate)); 578 } 579 } 580 581 namespace { 582 // The actual implementation of the lazy analysis and update. Note that the 583 // inheritance from LazyValueInfoCache is intended to be temporary while 584 // splitting the code and then transitioning to a has-a relationship. 585 class LazyValueInfoImpl { 586 587 /// Cached results from previous queries 588 LazyValueInfoCache TheCache; 589 590 /// This stack holds the state of the value solver during a query. 591 /// It basically emulates the callstack of the naive 592 /// recursive value lookup process. 593 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack; 594 595 /// Keeps track of which block-value pairs are in BlockValueStack. 596 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet; 597 598 /// Push BV onto BlockValueStack unless it's already in there. 599 /// Returns true on success. 600 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) { 601 if (!BlockValueSet.insert(BV).second) 602 return false; // It's already in the stack. 603 604 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName() 605 << "\n"); 606 BlockValueStack.push(BV); 607 return true; 608 } 609 610 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls. 611 const DataLayout &DL; ///< A mandatory DataLayout 612 DominatorTree *DT; ///< An optional DT pointer. 613 614 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB); 615 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T, 616 LVILatticeVal &Result, Instruction *CxtI = nullptr); 617 bool hasBlockValue(Value *Val, BasicBlock *BB); 618 619 // These methods process one work item and may add more. A false value 620 // returned means that the work item was not completely processed and must 621 // be revisited after going through the new items. 622 bool solveBlockValue(Value *Val, BasicBlock *BB); 623 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB); 624 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB); 625 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S, 626 BasicBlock *BB); 627 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI, 628 BasicBlock *BB); 629 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI, 630 BasicBlock *BB); 631 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val, 632 LVILatticeVal &BBLV, 633 Instruction *BBI); 634 635 void solve(); 636 637 public: 638 /// This is the query interface to determine the lattice 639 /// value for the specified Value* at the end of the specified block. 640 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB, 641 Instruction *CxtI = nullptr); 642 643 /// This is the query interface to determine the lattice 644 /// value for the specified Value* at the specified instruction (generally 645 /// from an assume intrinsic). 646 LVILatticeVal getValueAt(Value *V, Instruction *CxtI); 647 648 /// This is the query interface to determine the lattice 649 /// value for the specified Value* that is true on the specified edge. 650 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB, 651 Instruction *CxtI = nullptr); 652 653 /// Complete flush all previously computed values 654 void clear() { 655 TheCache.clear(); 656 } 657 658 /// This is part of the update interface to inform the cache 659 /// that a block has been deleted. 660 void eraseBlock(BasicBlock *BB) { 661 TheCache.eraseBlock(BB); 662 } 663 664 /// This is the update interface to inform the cache that an edge from 665 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc. 666 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc); 667 668 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL, 669 DominatorTree *DT = nullptr) 670 : AC(AC), DL(DL), DT(DT) {} 671 }; 672 } // end anonymous namespace 673 674 void LazyValueInfoImpl::solve() { 675 while (!BlockValueStack.empty()) { 676 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top(); 677 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!"); 678 679 if (solveBlockValue(e.second, e.first)) { 680 // The work item was completely processed. 681 assert(BlockValueStack.top() == e && "Nothing should have been pushed!"); 682 assert(TheCache.hasCachedValueInfo(e.second, e.first) && 683 "Result should be in cache!"); 684 685 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName() 686 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n"); 687 688 BlockValueStack.pop(); 689 BlockValueSet.erase(e); 690 } else { 691 // More work needs to be done before revisiting. 692 assert(BlockValueStack.top() != e && "Stack should have been pushed!"); 693 } 694 } 695 } 696 697 bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) { 698 // If already a constant, there is nothing to compute. 699 if (isa<Constant>(Val)) 700 return true; 701 702 return TheCache.hasCachedValueInfo(Val, BB); 703 } 704 705 LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) { 706 // If already a constant, there is nothing to compute. 707 if (Constant *VC = dyn_cast<Constant>(Val)) 708 return LVILatticeVal::get(VC); 709 710 return TheCache.getCachedValueInfo(Val, BB); 711 } 712 713 static LVILatticeVal getFromRangeMetadata(Instruction *BBI) { 714 switch (BBI->getOpcode()) { 715 default: break; 716 case Instruction::Load: 717 case Instruction::Call: 718 case Instruction::Invoke: 719 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range)) 720 if (isa<IntegerType>(BBI->getType())) { 721 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges)); 722 } 723 break; 724 }; 725 // Nothing known - will be intersected with other facts 726 return LVILatticeVal::getOverdefined(); 727 } 728 729 bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) { 730 if (isa<Constant>(Val)) 731 return true; 732 733 if (TheCache.hasCachedValueInfo(Val, BB)) { 734 // If we have a cached value, use that. 735 DEBUG(dbgs() << " reuse BB '" << BB->getName() 736 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n'); 737 738 // Since we're reusing a cached value, we don't need to update the 739 // OverDefinedCache. The cache will have been properly updated whenever the 740 // cached value was inserted. 741 return true; 742 } 743 744 // Hold off inserting this value into the Cache in case we have to return 745 // false and come back later. 746 LVILatticeVal Res; 747 748 Instruction *BBI = dyn_cast<Instruction>(Val); 749 if (!BBI || BBI->getParent() != BB) { 750 if (!solveBlockValueNonLocal(Res, Val, BB)) 751 return false; 752 TheCache.insertResult(Val, BB, Res); 753 return true; 754 } 755 756 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 757 if (!solveBlockValuePHINode(Res, PN, BB)) 758 return false; 759 TheCache.insertResult(Val, BB, Res); 760 return true; 761 } 762 763 if (auto *SI = dyn_cast<SelectInst>(BBI)) { 764 if (!solveBlockValueSelect(Res, SI, BB)) 765 return false; 766 TheCache.insertResult(Val, BB, Res); 767 return true; 768 } 769 770 // If this value is a nonnull pointer, record it's range and bailout. Note 771 // that for all other pointer typed values, we terminate the search at the 772 // definition. We could easily extend this to look through geps, bitcasts, 773 // and the like to prove non-nullness, but it's not clear that's worth it 774 // compile time wise. The context-insensative value walk done inside 775 // isKnownNonNull gets most of the profitable cases at much less expense. 776 // This does mean that we have a sensativity to where the defining 777 // instruction is placed, even if it could legally be hoisted much higher. 778 // That is unfortunate. 779 PointerType *PT = dyn_cast<PointerType>(BBI->getType()); 780 if (PT && isKnownNonNull(BBI)) { 781 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT)); 782 TheCache.insertResult(Val, BB, Res); 783 return true; 784 } 785 if (BBI->getType()->isIntegerTy()) { 786 if (isa<CastInst>(BBI)) { 787 if (!solveBlockValueCast(Res, BBI, BB)) 788 return false; 789 TheCache.insertResult(Val, BB, Res); 790 return true; 791 } 792 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI); 793 if (BO && isa<ConstantInt>(BO->getOperand(1))) { 794 if (!solveBlockValueBinaryOp(Res, BBI, BB)) 795 return false; 796 TheCache.insertResult(Val, BB, Res); 797 return true; 798 } 799 } 800 801 DEBUG(dbgs() << " compute BB '" << BB->getName() 802 << "' - unknown inst def found.\n"); 803 Res = getFromRangeMetadata(BBI); 804 TheCache.insertResult(Val, BB, Res); 805 return true; 806 } 807 808 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) { 809 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 810 return L->getPointerAddressSpace() == 0 && 811 GetUnderlyingObject(L->getPointerOperand(), 812 L->getModule()->getDataLayout()) == Ptr; 813 } 814 if (StoreInst *S = dyn_cast<StoreInst>(I)) { 815 return S->getPointerAddressSpace() == 0 && 816 GetUnderlyingObject(S->getPointerOperand(), 817 S->getModule()->getDataLayout()) == Ptr; 818 } 819 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) { 820 if (MI->isVolatile()) return false; 821 822 // FIXME: check whether it has a valuerange that excludes zero? 823 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength()); 824 if (!Len || Len->isZero()) return false; 825 826 if (MI->getDestAddressSpace() == 0) 827 if (GetUnderlyingObject(MI->getRawDest(), 828 MI->getModule()->getDataLayout()) == Ptr) 829 return true; 830 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) 831 if (MTI->getSourceAddressSpace() == 0) 832 if (GetUnderlyingObject(MTI->getRawSource(), 833 MTI->getModule()->getDataLayout()) == Ptr) 834 return true; 835 } 836 return false; 837 } 838 839 /// Return true if the allocation associated with Val is ever dereferenced 840 /// within the given basic block. This establishes the fact Val is not null, 841 /// but does not imply that the memory at Val is dereferenceable. (Val may 842 /// point off the end of the dereferenceable part of the object.) 843 static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) { 844 assert(Val->getType()->isPointerTy()); 845 846 const DataLayout &DL = BB->getModule()->getDataLayout(); 847 Value *UnderlyingVal = GetUnderlyingObject(Val, DL); 848 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge 849 // inside InstructionDereferencesPointer either. 850 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) 851 for (Instruction &I : *BB) 852 if (InstructionDereferencesPointer(&I, UnderlyingVal)) 853 return true; 854 return false; 855 } 856 857 bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV, 858 Value *Val, BasicBlock *BB) { 859 LVILatticeVal Result; // Start Undefined. 860 861 // If this is the entry block, we must be asking about an argument. The 862 // value is overdefined. 863 if (BB == &BB->getParent()->getEntryBlock()) { 864 assert(isa<Argument>(Val) && "Unknown live-in to the entry block"); 865 // Bofore giving up, see if we can prove the pointer non-null local to 866 // this particular block. 867 if (Val->getType()->isPointerTy() && 868 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) { 869 PointerType *PTy = cast<PointerType>(Val->getType()); 870 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 871 } else { 872 Result.markOverdefined(); 873 } 874 BBLV = Result; 875 return true; 876 } 877 878 // Loop over all of our predecessors, merging what we know from them into 879 // result. 880 bool EdgesMissing = false; 881 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 882 LVILatticeVal EdgeResult; 883 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult); 884 if (EdgesMissing) 885 continue; 886 887 Result.mergeIn(EdgeResult, DL); 888 889 // If we hit overdefined, exit early. The BlockVals entry is already set 890 // to overdefined. 891 if (Result.isOverdefined()) { 892 DEBUG(dbgs() << " compute BB '" << BB->getName() 893 << "' - overdefined because of pred (non local).\n"); 894 // Before giving up, see if we can prove the pointer non-null local to 895 // this particular block. 896 if (Val->getType()->isPointerTy() && 897 isObjectDereferencedInBlock(Val, BB)) { 898 PointerType *PTy = cast<PointerType>(Val->getType()); 899 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 900 } 901 902 BBLV = Result; 903 return true; 904 } 905 } 906 if (EdgesMissing) 907 return false; 908 909 // Return the merged value, which is more precise than 'overdefined'. 910 assert(!Result.isOverdefined()); 911 BBLV = Result; 912 return true; 913 } 914 915 bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV, 916 PHINode *PN, BasicBlock *BB) { 917 LVILatticeVal Result; // Start Undefined. 918 919 // Loop over all of our predecessors, merging what we know from them into 920 // result. 921 bool EdgesMissing = false; 922 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 923 BasicBlock *PhiBB = PN->getIncomingBlock(i); 924 Value *PhiVal = PN->getIncomingValue(i); 925 LVILatticeVal EdgeResult; 926 // Note that we can provide PN as the context value to getEdgeValue, even 927 // though the results will be cached, because PN is the value being used as 928 // the cache key in the caller. 929 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN); 930 if (EdgesMissing) 931 continue; 932 933 Result.mergeIn(EdgeResult, DL); 934 935 // If we hit overdefined, exit early. The BlockVals entry is already set 936 // to overdefined. 937 if (Result.isOverdefined()) { 938 DEBUG(dbgs() << " compute BB '" << BB->getName() 939 << "' - overdefined because of pred (local).\n"); 940 941 BBLV = Result; 942 return true; 943 } 944 } 945 if (EdgesMissing) 946 return false; 947 948 // Return the merged value, which is more precise than 'overdefined'. 949 assert(!Result.isOverdefined() && "Possible PHI in entry block?"); 950 BBLV = Result; 951 return true; 952 } 953 954 static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, 955 bool isTrueDest = true); 956 957 // If we can determine a constraint on the value given conditions assumed by 958 // the program, intersect those constraints with BBLV 959 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange( 960 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) { 961 BBI = BBI ? BBI : dyn_cast<Instruction>(Val); 962 if (!BBI) 963 return; 964 965 for (auto &AssumeVH : AC->assumptions()) { 966 if (!AssumeVH) 967 continue; 968 auto *I = cast<CallInst>(AssumeVH); 969 if (!isValidAssumeForContext(I, BBI, DT)) 970 continue; 971 972 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0))); 973 } 974 975 // If guards are not used in the module, don't spend time looking for them 976 auto *GuardDecl = BBI->getModule()->getFunction( 977 Intrinsic::getName(Intrinsic::experimental_guard)); 978 if (!GuardDecl || GuardDecl->use_empty()) 979 return; 980 981 for (Instruction &I : make_range(BBI->getIterator().getReverse(), 982 BBI->getParent()->rend())) { 983 Value *Cond = nullptr; 984 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond)))) 985 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond)); 986 } 987 } 988 989 bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV, 990 SelectInst *SI, BasicBlock *BB) { 991 992 // Recurse on our inputs if needed 993 if (!hasBlockValue(SI->getTrueValue(), BB)) { 994 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue()))) 995 return false; 996 BBLV.markOverdefined(); 997 return true; 998 } 999 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB); 1000 // If we hit overdefined, don't ask more queries. We want to avoid poisoning 1001 // extra slots in the table if we can. 1002 if (TrueVal.isOverdefined()) { 1003 BBLV.markOverdefined(); 1004 return true; 1005 } 1006 1007 if (!hasBlockValue(SI->getFalseValue(), BB)) { 1008 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue()))) 1009 return false; 1010 BBLV.markOverdefined(); 1011 return true; 1012 } 1013 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB); 1014 // If we hit overdefined, don't ask more queries. We want to avoid poisoning 1015 // extra slots in the table if we can. 1016 if (FalseVal.isOverdefined()) { 1017 BBLV.markOverdefined(); 1018 return true; 1019 } 1020 1021 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) { 1022 ConstantRange TrueCR = TrueVal.getConstantRange(); 1023 ConstantRange FalseCR = FalseVal.getConstantRange(); 1024 Value *LHS = nullptr; 1025 Value *RHS = nullptr; 1026 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS); 1027 // Is this a min specifically of our two inputs? (Avoid the risk of 1028 // ValueTracking getting smarter looking back past our immediate inputs.) 1029 if (SelectPatternResult::isMinOrMax(SPR.Flavor) && 1030 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) { 1031 switch (SPR.Flavor) { 1032 default: 1033 llvm_unreachable("unexpected minmax type!"); 1034 case SPF_SMIN: /// Signed minimum 1035 BBLV.markConstantRange(TrueCR.smin(FalseCR)); 1036 return true; 1037 case SPF_UMIN: /// Unsigned minimum 1038 BBLV.markConstantRange(TrueCR.umin(FalseCR)); 1039 return true; 1040 case SPF_SMAX: /// Signed maximum 1041 BBLV.markConstantRange(TrueCR.smax(FalseCR)); 1042 return true; 1043 case SPF_UMAX: /// Unsigned maximum 1044 BBLV.markConstantRange(TrueCR.umax(FalseCR)); 1045 return true; 1046 }; 1047 } 1048 1049 // TODO: ABS, NABS from the SelectPatternResult 1050 } 1051 1052 // Can we constrain the facts about the true and false values by using the 1053 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5). 1054 // TODO: We could potentially refine an overdefined true value above. 1055 Value *Cond = SI->getCondition(); 1056 TrueVal = intersect(TrueVal, 1057 getValueFromCondition(SI->getTrueValue(), Cond, true)); 1058 FalseVal = intersect(FalseVal, 1059 getValueFromCondition(SI->getFalseValue(), Cond, false)); 1060 1061 // Handle clamp idioms such as: 1062 // %24 = constantrange<0, 17> 1063 // %39 = icmp eq i32 %24, 0 1064 // %40 = add i32 %24, -1 1065 // %siv.next = select i1 %39, i32 16, i32 %40 1066 // %siv.next = constantrange<0, 17> not <-1, 17> 1067 // In general, this can handle any clamp idiom which tests the edge 1068 // condition via an equality or inequality. 1069 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) { 1070 ICmpInst::Predicate Pred = ICI->getPredicate(); 1071 Value *A = ICI->getOperand(0); 1072 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) { 1073 auto addConstants = [](ConstantInt *A, ConstantInt *B) { 1074 assert(A->getType() == B->getType()); 1075 return ConstantInt::get(A->getType(), A->getValue() + B->getValue()); 1076 }; 1077 // See if either input is A + C2, subject to the constraint from the 1078 // condition that A != C when that input is used. We can assume that 1079 // that input doesn't include C + C2. 1080 ConstantInt *CIAdded; 1081 switch (Pred) { 1082 default: break; 1083 case ICmpInst::ICMP_EQ: 1084 if (match(SI->getFalseValue(), m_Add(m_Specific(A), 1085 m_ConstantInt(CIAdded)))) { 1086 auto ResNot = addConstants(CIBase, CIAdded); 1087 FalseVal = intersect(FalseVal, 1088 LVILatticeVal::getNot(ResNot)); 1089 } 1090 break; 1091 case ICmpInst::ICMP_NE: 1092 if (match(SI->getTrueValue(), m_Add(m_Specific(A), 1093 m_ConstantInt(CIAdded)))) { 1094 auto ResNot = addConstants(CIBase, CIAdded); 1095 TrueVal = intersect(TrueVal, 1096 LVILatticeVal::getNot(ResNot)); 1097 } 1098 break; 1099 }; 1100 } 1101 } 1102 1103 LVILatticeVal Result; // Start Undefined. 1104 Result.mergeIn(TrueVal, DL); 1105 Result.mergeIn(FalseVal, DL); 1106 BBLV = Result; 1107 return true; 1108 } 1109 1110 bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV, 1111 Instruction *BBI, 1112 BasicBlock *BB) { 1113 if (!BBI->getOperand(0)->getType()->isSized()) { 1114 // Without knowing how wide the input is, we can't analyze it in any useful 1115 // way. 1116 BBLV.markOverdefined(); 1117 return true; 1118 } 1119 1120 // Filter out casts we don't know how to reason about before attempting to 1121 // recurse on our operand. This can cut a long search short if we know we're 1122 // not going to be able to get any useful information anways. 1123 switch (BBI->getOpcode()) { 1124 case Instruction::Trunc: 1125 case Instruction::SExt: 1126 case Instruction::ZExt: 1127 case Instruction::BitCast: 1128 break; 1129 default: 1130 // Unhandled instructions are overdefined. 1131 DEBUG(dbgs() << " compute BB '" << BB->getName() 1132 << "' - overdefined (unknown cast).\n"); 1133 BBLV.markOverdefined(); 1134 return true; 1135 } 1136 1137 // Figure out the range of the LHS. If that fails, we still apply the 1138 // transfer rule on the full set since we may be able to locally infer 1139 // interesting facts. 1140 if (!hasBlockValue(BBI->getOperand(0), BB)) 1141 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0)))) 1142 // More work to do before applying this transfer rule. 1143 return false; 1144 1145 const unsigned OperandBitWidth = 1146 DL.getTypeSizeInBits(BBI->getOperand(0)->getType()); 1147 ConstantRange LHSRange = ConstantRange(OperandBitWidth); 1148 if (hasBlockValue(BBI->getOperand(0), BB)) { 1149 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB); 1150 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal, 1151 BBI); 1152 if (LHSVal.isConstantRange()) 1153 LHSRange = LHSVal.getConstantRange(); 1154 } 1155 1156 const unsigned ResultBitWidth = 1157 cast<IntegerType>(BBI->getType())->getBitWidth(); 1158 1159 // NOTE: We're currently limited by the set of operations that ConstantRange 1160 // can evaluate symbolically. Enhancing that set will allows us to analyze 1161 // more definitions. 1162 LVILatticeVal Result; 1163 switch (BBI->getOpcode()) { 1164 case Instruction::Trunc: 1165 Result.markConstantRange(LHSRange.truncate(ResultBitWidth)); 1166 break; 1167 case Instruction::SExt: 1168 Result.markConstantRange(LHSRange.signExtend(ResultBitWidth)); 1169 break; 1170 case Instruction::ZExt: 1171 Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth)); 1172 break; 1173 case Instruction::BitCast: 1174 Result.markConstantRange(LHSRange); 1175 break; 1176 default: 1177 // Should be dead if the code above is correct 1178 llvm_unreachable("inconsistent with above"); 1179 break; 1180 } 1181 1182 BBLV = Result; 1183 return true; 1184 } 1185 1186 bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV, 1187 Instruction *BBI, 1188 BasicBlock *BB) { 1189 1190 assert(BBI->getOperand(0)->getType()->isSized() && 1191 "all operands to binary operators are sized"); 1192 1193 // Filter out operators we don't know how to reason about before attempting to 1194 // recurse on our operand(s). This can cut a long search short if we know 1195 // we're not going to be able to get any useful information anways. 1196 switch (BBI->getOpcode()) { 1197 case Instruction::Add: 1198 case Instruction::Sub: 1199 case Instruction::Mul: 1200 case Instruction::UDiv: 1201 case Instruction::Shl: 1202 case Instruction::LShr: 1203 case Instruction::And: 1204 case Instruction::Or: 1205 // continue into the code below 1206 break; 1207 default: 1208 // Unhandled instructions are overdefined. 1209 DEBUG(dbgs() << " compute BB '" << BB->getName() 1210 << "' - overdefined (unknown binary operator).\n"); 1211 BBLV.markOverdefined(); 1212 return true; 1213 }; 1214 1215 // Figure out the range of the LHS. If that fails, use a conservative range, 1216 // but apply the transfer rule anyways. This lets us pick up facts from 1217 // expressions like "and i32 (call i32 @foo()), 32" 1218 if (!hasBlockValue(BBI->getOperand(0), BB)) 1219 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0)))) 1220 // More work to do before applying this transfer rule. 1221 return false; 1222 1223 const unsigned OperandBitWidth = 1224 DL.getTypeSizeInBits(BBI->getOperand(0)->getType()); 1225 ConstantRange LHSRange = ConstantRange(OperandBitWidth); 1226 if (hasBlockValue(BBI->getOperand(0), BB)) { 1227 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB); 1228 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal, 1229 BBI); 1230 if (LHSVal.isConstantRange()) 1231 LHSRange = LHSVal.getConstantRange(); 1232 } 1233 1234 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1)); 1235 ConstantRange RHSRange = ConstantRange(RHS->getValue()); 1236 1237 // NOTE: We're currently limited by the set of operations that ConstantRange 1238 // can evaluate symbolically. Enhancing that set will allows us to analyze 1239 // more definitions. 1240 LVILatticeVal Result; 1241 switch (BBI->getOpcode()) { 1242 case Instruction::Add: 1243 Result.markConstantRange(LHSRange.add(RHSRange)); 1244 break; 1245 case Instruction::Sub: 1246 Result.markConstantRange(LHSRange.sub(RHSRange)); 1247 break; 1248 case Instruction::Mul: 1249 Result.markConstantRange(LHSRange.multiply(RHSRange)); 1250 break; 1251 case Instruction::UDiv: 1252 Result.markConstantRange(LHSRange.udiv(RHSRange)); 1253 break; 1254 case Instruction::Shl: 1255 Result.markConstantRange(LHSRange.shl(RHSRange)); 1256 break; 1257 case Instruction::LShr: 1258 Result.markConstantRange(LHSRange.lshr(RHSRange)); 1259 break; 1260 case Instruction::And: 1261 Result.markConstantRange(LHSRange.binaryAnd(RHSRange)); 1262 break; 1263 case Instruction::Or: 1264 Result.markConstantRange(LHSRange.binaryOr(RHSRange)); 1265 break; 1266 default: 1267 // Should be dead if the code above is correct 1268 llvm_unreachable("inconsistent with above"); 1269 break; 1270 } 1271 1272 BBLV = Result; 1273 return true; 1274 } 1275 1276 static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI, 1277 bool isTrueDest) { 1278 Value *LHS = ICI->getOperand(0); 1279 Value *RHS = ICI->getOperand(1); 1280 CmpInst::Predicate Predicate = ICI->getPredicate(); 1281 1282 if (isa<Constant>(RHS)) { 1283 if (ICI->isEquality() && LHS == Val) { 1284 // We know that V has the RHS constant if this is a true SETEQ or 1285 // false SETNE. 1286 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ)) 1287 return LVILatticeVal::get(cast<Constant>(RHS)); 1288 else 1289 return LVILatticeVal::getNot(cast<Constant>(RHS)); 1290 } 1291 } 1292 1293 if (!Val->getType()->isIntegerTy()) 1294 return LVILatticeVal::getOverdefined(); 1295 1296 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible 1297 // range of Val guaranteed by the condition. Recognize comparisons in the from 1298 // of: 1299 // icmp <pred> Val, ... 1300 // icmp <pred> (add Val, Offset), ... 1301 // The latter is the range checking idiom that InstCombine produces. Subtract 1302 // the offset from the allowed range for RHS in this case. 1303 1304 // Val or (add Val, Offset) can be on either hand of the comparison 1305 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) { 1306 std::swap(LHS, RHS); 1307 Predicate = CmpInst::getSwappedPredicate(Predicate); 1308 } 1309 1310 ConstantInt *Offset = nullptr; 1311 if (LHS != Val) 1312 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset))); 1313 1314 if (LHS == Val || Offset) { 1315 // Calculate the range of values that are allowed by the comparison 1316 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(), 1317 /*isFullSet=*/true); 1318 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) 1319 RHSRange = ConstantRange(CI->getValue()); 1320 else if (Instruction *I = dyn_cast<Instruction>(RHS)) 1321 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range)) 1322 RHSRange = getConstantRangeFromMetadata(*Ranges); 1323 1324 // If we're interested in the false dest, invert the condition 1325 CmpInst::Predicate Pred = 1326 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate); 1327 ConstantRange TrueValues = 1328 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange); 1329 1330 if (Offset) // Apply the offset from above. 1331 TrueValues = TrueValues.subtract(Offset->getValue()); 1332 1333 return LVILatticeVal::getRange(std::move(TrueValues)); 1334 } 1335 1336 return LVILatticeVal::getOverdefined(); 1337 } 1338 1339 static LVILatticeVal 1340 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest, 1341 DenseMap<Value*, LVILatticeVal> &Visited); 1342 1343 static LVILatticeVal 1344 getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest, 1345 DenseMap<Value*, LVILatticeVal> &Visited) { 1346 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond)) 1347 return getValueFromICmpCondition(Val, ICI, isTrueDest); 1348 1349 // Handle conditions in the form of (cond1 && cond2), we know that on the 1350 // true dest path both of the conditions hold. 1351 if (!isTrueDest) 1352 return LVILatticeVal::getOverdefined(); 1353 1354 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond); 1355 if (!BO || BO->getOpcode() != BinaryOperator::And) 1356 return LVILatticeVal::getOverdefined(); 1357 1358 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited); 1359 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited); 1360 return intersect(RHS, LHS); 1361 } 1362 1363 static LVILatticeVal 1364 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest, 1365 DenseMap<Value*, LVILatticeVal> &Visited) { 1366 auto I = Visited.find(Cond); 1367 if (I != Visited.end()) 1368 return I->second; 1369 1370 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited); 1371 Visited[Cond] = Result; 1372 return Result; 1373 } 1374 1375 LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) { 1376 assert(Cond && "precondition"); 1377 DenseMap<Value*, LVILatticeVal> Visited; 1378 return getValueFromCondition(Val, Cond, isTrueDest, Visited); 1379 } 1380 1381 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if 1382 /// Val is not constrained on the edge. Result is unspecified if return value 1383 /// is false. 1384 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom, 1385 BasicBlock *BBTo, LVILatticeVal &Result) { 1386 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we 1387 // know that v != 0. 1388 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) { 1389 // If this is a conditional branch and only one successor goes to BBTo, then 1390 // we may be able to infer something from the condition. 1391 if (BI->isConditional() && 1392 BI->getSuccessor(0) != BI->getSuccessor(1)) { 1393 bool isTrueDest = BI->getSuccessor(0) == BBTo; 1394 assert(BI->getSuccessor(!isTrueDest) == BBTo && 1395 "BBTo isn't a successor of BBFrom"); 1396 1397 // If V is the condition of the branch itself, then we know exactly what 1398 // it is. 1399 if (BI->getCondition() == Val) { 1400 Result = LVILatticeVal::get(ConstantInt::get( 1401 Type::getInt1Ty(Val->getContext()), isTrueDest)); 1402 return true; 1403 } 1404 1405 // If the condition of the branch is an equality comparison, we may be 1406 // able to infer the value. 1407 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest); 1408 if (!Result.isOverdefined()) 1409 return true; 1410 } 1411 } 1412 1413 // If the edge was formed by a switch on the value, then we may know exactly 1414 // what it is. 1415 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) { 1416 if (SI->getCondition() != Val) 1417 return false; 1418 1419 bool DefaultCase = SI->getDefaultDest() == BBTo; 1420 unsigned BitWidth = Val->getType()->getIntegerBitWidth(); 1421 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/); 1422 1423 for (SwitchInst::CaseIt i : SI->cases()) { 1424 ConstantRange EdgeVal(i.getCaseValue()->getValue()); 1425 if (DefaultCase) { 1426 // It is possible that the default destination is the destination of 1427 // some cases. There is no need to perform difference for those cases. 1428 if (i.getCaseSuccessor() != BBTo) 1429 EdgesVals = EdgesVals.difference(EdgeVal); 1430 } else if (i.getCaseSuccessor() == BBTo) 1431 EdgesVals = EdgesVals.unionWith(EdgeVal); 1432 } 1433 Result = LVILatticeVal::getRange(std::move(EdgesVals)); 1434 return true; 1435 } 1436 return false; 1437 } 1438 1439 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at 1440 /// the basic block if the edge does not constrain Val. 1441 bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom, 1442 BasicBlock *BBTo, LVILatticeVal &Result, 1443 Instruction *CxtI) { 1444 // If already a constant, there is nothing to compute. 1445 if (Constant *VC = dyn_cast<Constant>(Val)) { 1446 Result = LVILatticeVal::get(VC); 1447 return true; 1448 } 1449 1450 LVILatticeVal LocalResult; 1451 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult)) 1452 // If we couldn't constrain the value on the edge, LocalResult doesn't 1453 // provide any information. 1454 LocalResult.markOverdefined(); 1455 1456 if (hasSingleValue(LocalResult)) { 1457 // Can't get any more precise here 1458 Result = LocalResult; 1459 return true; 1460 } 1461 1462 if (!hasBlockValue(Val, BBFrom)) { 1463 if (pushBlockValue(std::make_pair(BBFrom, Val))) 1464 return false; 1465 // No new information. 1466 Result = LocalResult; 1467 return true; 1468 } 1469 1470 // Try to intersect ranges of the BB and the constraint on the edge. 1471 LVILatticeVal InBlock = getBlockValue(Val, BBFrom); 1472 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, 1473 BBFrom->getTerminator()); 1474 // We can use the context instruction (generically the ultimate instruction 1475 // the calling pass is trying to simplify) here, even though the result of 1476 // this function is generally cached when called from the solve* functions 1477 // (and that cached result might be used with queries using a different 1478 // context instruction), because when this function is called from the solve* 1479 // functions, the context instruction is not provided. When called from 1480 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided, 1481 // but then the result is not cached. 1482 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI); 1483 1484 Result = intersect(LocalResult, InBlock); 1485 return true; 1486 } 1487 1488 LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB, 1489 Instruction *CxtI) { 1490 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '" 1491 << BB->getName() << "'\n"); 1492 1493 assert(BlockValueStack.empty() && BlockValueSet.empty()); 1494 if (!hasBlockValue(V, BB)) { 1495 pushBlockValue(std::make_pair(BB, V)); 1496 solve(); 1497 } 1498 LVILatticeVal Result = getBlockValue(V, BB); 1499 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI); 1500 1501 DEBUG(dbgs() << " Result = " << Result << "\n"); 1502 return Result; 1503 } 1504 1505 LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) { 1506 DEBUG(dbgs() << "LVI Getting value " << *V << " at '" 1507 << CxtI->getName() << "'\n"); 1508 1509 if (auto *C = dyn_cast<Constant>(V)) 1510 return LVILatticeVal::get(C); 1511 1512 LVILatticeVal Result = LVILatticeVal::getOverdefined(); 1513 if (auto *I = dyn_cast<Instruction>(V)) 1514 Result = getFromRangeMetadata(I); 1515 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI); 1516 1517 DEBUG(dbgs() << " Result = " << Result << "\n"); 1518 return Result; 1519 } 1520 1521 LVILatticeVal LazyValueInfoImpl:: 1522 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, 1523 Instruction *CxtI) { 1524 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '" 1525 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n"); 1526 1527 LVILatticeVal Result; 1528 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) { 1529 solve(); 1530 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI); 1531 (void)WasFastQuery; 1532 assert(WasFastQuery && "More work to do after problem solved?"); 1533 } 1534 1535 DEBUG(dbgs() << " Result = " << Result << "\n"); 1536 return Result; 1537 } 1538 1539 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 1540 BasicBlock *NewSucc) { 1541 TheCache.threadEdgeImpl(OldSucc, NewSucc); 1542 } 1543 1544 //===----------------------------------------------------------------------===// 1545 // LazyValueInfo Impl 1546 //===----------------------------------------------------------------------===// 1547 1548 /// This lazily constructs the LazyValueInfoImpl. 1549 static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC, 1550 const DataLayout *DL, 1551 DominatorTree *DT = nullptr) { 1552 if (!PImpl) { 1553 assert(DL && "getCache() called with a null DataLayout"); 1554 PImpl = new LazyValueInfoImpl(AC, *DL, DT); 1555 } 1556 return *static_cast<LazyValueInfoImpl*>(PImpl); 1557 } 1558 1559 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) { 1560 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1561 const DataLayout &DL = F.getParent()->getDataLayout(); 1562 1563 DominatorTreeWrapperPass *DTWP = 1564 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1565 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr; 1566 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1567 1568 if (Info.PImpl) 1569 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear(); 1570 1571 // Fully lazy. 1572 return false; 1573 } 1574 1575 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1576 AU.setPreservesAll(); 1577 AU.addRequired<AssumptionCacheTracker>(); 1578 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1579 } 1580 1581 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; } 1582 1583 LazyValueInfo::~LazyValueInfo() { releaseMemory(); } 1584 1585 void LazyValueInfo::releaseMemory() { 1586 // If the cache was allocated, free it. 1587 if (PImpl) { 1588 delete &getImpl(PImpl, AC, nullptr); 1589 PImpl = nullptr; 1590 } 1591 } 1592 1593 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); } 1594 1595 LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) { 1596 auto &AC = FAM.getResult<AssumptionAnalysis>(F); 1597 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F); 1598 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F); 1599 1600 return LazyValueInfo(&AC, &TLI, DT); 1601 } 1602 1603 /// Returns true if we can statically tell that this value will never be a 1604 /// "useful" constant. In practice, this means we've got something like an 1605 /// alloca or a malloc call for which a comparison against a constant can 1606 /// only be guarding dead code. Note that we are potentially giving up some 1607 /// precision in dead code (a constant result) in favour of avoiding a 1608 /// expensive search for a easily answered common query. 1609 static bool isKnownNonConstant(Value *V) { 1610 V = V->stripPointerCasts(); 1611 // The return val of alloc cannot be a Constant. 1612 if (isa<AllocaInst>(V)) 1613 return true; 1614 return false; 1615 } 1616 1617 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB, 1618 Instruction *CxtI) { 1619 // Bail out early if V is known not to be a Constant. 1620 if (isKnownNonConstant(V)) 1621 return nullptr; 1622 1623 const DataLayout &DL = BB->getModule()->getDataLayout(); 1624 LVILatticeVal Result = 1625 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI); 1626 1627 if (Result.isConstant()) 1628 return Result.getConstant(); 1629 if (Result.isConstantRange()) { 1630 ConstantRange CR = Result.getConstantRange(); 1631 if (const APInt *SingleVal = CR.getSingleElement()) 1632 return ConstantInt::get(V->getContext(), *SingleVal); 1633 } 1634 return nullptr; 1635 } 1636 1637 ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB, 1638 Instruction *CxtI) { 1639 assert(V->getType()->isIntegerTy()); 1640 unsigned Width = V->getType()->getIntegerBitWidth(); 1641 const DataLayout &DL = BB->getModule()->getDataLayout(); 1642 LVILatticeVal Result = 1643 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI); 1644 if (Result.isUndefined()) 1645 return ConstantRange(Width, /*isFullSet=*/false); 1646 if (Result.isConstantRange()) 1647 return Result.getConstantRange(); 1648 // We represent ConstantInt constants as constant ranges but other kinds 1649 // of integer constants, i.e. ConstantExpr will be tagged as constants 1650 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && 1651 "ConstantInt value must be represented as constantrange"); 1652 return ConstantRange(Width, /*isFullSet=*/true); 1653 } 1654 1655 /// Determine whether the specified value is known to be a 1656 /// constant on the specified edge. Return null if not. 1657 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB, 1658 BasicBlock *ToBB, 1659 Instruction *CxtI) { 1660 const DataLayout &DL = FromBB->getModule()->getDataLayout(); 1661 LVILatticeVal Result = 1662 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI); 1663 1664 if (Result.isConstant()) 1665 return Result.getConstant(); 1666 if (Result.isConstantRange()) { 1667 ConstantRange CR = Result.getConstantRange(); 1668 if (const APInt *SingleVal = CR.getSingleElement()) 1669 return ConstantInt::get(V->getContext(), *SingleVal); 1670 } 1671 return nullptr; 1672 } 1673 1674 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C, 1675 LVILatticeVal &Result, 1676 const DataLayout &DL, 1677 TargetLibraryInfo *TLI) { 1678 1679 // If we know the value is a constant, evaluate the conditional. 1680 Constant *Res = nullptr; 1681 if (Result.isConstant()) { 1682 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL, 1683 TLI); 1684 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res)) 1685 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True; 1686 return LazyValueInfo::Unknown; 1687 } 1688 1689 if (Result.isConstantRange()) { 1690 ConstantInt *CI = dyn_cast<ConstantInt>(C); 1691 if (!CI) return LazyValueInfo::Unknown; 1692 1693 ConstantRange CR = Result.getConstantRange(); 1694 if (Pred == ICmpInst::ICMP_EQ) { 1695 if (!CR.contains(CI->getValue())) 1696 return LazyValueInfo::False; 1697 1698 if (CR.isSingleElement() && CR.contains(CI->getValue())) 1699 return LazyValueInfo::True; 1700 } else if (Pred == ICmpInst::ICMP_NE) { 1701 if (!CR.contains(CI->getValue())) 1702 return LazyValueInfo::True; 1703 1704 if (CR.isSingleElement() && CR.contains(CI->getValue())) 1705 return LazyValueInfo::False; 1706 } 1707 1708 // Handle more complex predicates. 1709 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion( 1710 (ICmpInst::Predicate)Pred, CI->getValue()); 1711 if (TrueValues.contains(CR)) 1712 return LazyValueInfo::True; 1713 if (TrueValues.inverse().contains(CR)) 1714 return LazyValueInfo::False; 1715 return LazyValueInfo::Unknown; 1716 } 1717 1718 if (Result.isNotConstant()) { 1719 // If this is an equality comparison, we can try to fold it knowing that 1720 // "V != C1". 1721 if (Pred == ICmpInst::ICMP_EQ) { 1722 // !C1 == C -> false iff C1 == C. 1723 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 1724 Result.getNotConstant(), C, DL, 1725 TLI); 1726 if (Res->isNullValue()) 1727 return LazyValueInfo::False; 1728 } else if (Pred == ICmpInst::ICMP_NE) { 1729 // !C1 != C -> true iff C1 == C. 1730 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 1731 Result.getNotConstant(), C, DL, 1732 TLI); 1733 if (Res->isNullValue()) 1734 return LazyValueInfo::True; 1735 } 1736 return LazyValueInfo::Unknown; 1737 } 1738 1739 return LazyValueInfo::Unknown; 1740 } 1741 1742 /// Determine whether the specified value comparison with a constant is known to 1743 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate. 1744 LazyValueInfo::Tristate 1745 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, 1746 BasicBlock *FromBB, BasicBlock *ToBB, 1747 Instruction *CxtI) { 1748 const DataLayout &DL = FromBB->getModule()->getDataLayout(); 1749 LVILatticeVal Result = 1750 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI); 1751 1752 return getPredicateResult(Pred, C, Result, DL, TLI); 1753 } 1754 1755 LazyValueInfo::Tristate 1756 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C, 1757 Instruction *CxtI) { 1758 // Is or is not NonNull are common predicates being queried. If 1759 // isKnownNonNull can tell us the result of the predicate, we can 1760 // return it quickly. But this is only a fastpath, and falling 1761 // through would still be correct. 1762 if (V->getType()->isPointerTy() && C->isNullValue() && 1763 isKnownNonNull(V->stripPointerCasts())) { 1764 if (Pred == ICmpInst::ICMP_EQ) 1765 return LazyValueInfo::False; 1766 else if (Pred == ICmpInst::ICMP_NE) 1767 return LazyValueInfo::True; 1768 } 1769 const DataLayout &DL = CxtI->getModule()->getDataLayout(); 1770 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI); 1771 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI); 1772 if (Ret != Unknown) 1773 return Ret; 1774 1775 // Note: The following bit of code is somewhat distinct from the rest of LVI; 1776 // LVI as a whole tries to compute a lattice value which is conservatively 1777 // correct at a given location. In this case, we have a predicate which we 1778 // weren't able to prove about the merged result, and we're pushing that 1779 // predicate back along each incoming edge to see if we can prove it 1780 // separately for each input. As a motivating example, consider: 1781 // bb1: 1782 // %v1 = ... ; constantrange<1, 5> 1783 // br label %merge 1784 // bb2: 1785 // %v2 = ... ; constantrange<10, 20> 1786 // br label %merge 1787 // merge: 1788 // %phi = phi [%v1, %v2] ; constantrange<1,20> 1789 // %pred = icmp eq i32 %phi, 8 1790 // We can't tell from the lattice value for '%phi' that '%pred' is false 1791 // along each path, but by checking the predicate over each input separately, 1792 // we can. 1793 // We limit the search to one step backwards from the current BB and value. 1794 // We could consider extending this to search further backwards through the 1795 // CFG and/or value graph, but there are non-obvious compile time vs quality 1796 // tradeoffs. 1797 if (CxtI) { 1798 BasicBlock *BB = CxtI->getParent(); 1799 1800 // Function entry or an unreachable block. Bail to avoid confusing 1801 // analysis below. 1802 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1803 if (PI == PE) 1804 return Unknown; 1805 1806 // If V is a PHI node in the same block as the context, we need to ask 1807 // questions about the predicate as applied to the incoming value along 1808 // each edge. This is useful for eliminating cases where the predicate is 1809 // known along all incoming edges. 1810 if (auto *PHI = dyn_cast<PHINode>(V)) 1811 if (PHI->getParent() == BB) { 1812 Tristate Baseline = Unknown; 1813 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) { 1814 Value *Incoming = PHI->getIncomingValue(i); 1815 BasicBlock *PredBB = PHI->getIncomingBlock(i); 1816 // Note that PredBB may be BB itself. 1817 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, 1818 CxtI); 1819 1820 // Keep going as long as we've seen a consistent known result for 1821 // all inputs. 1822 Baseline = (i == 0) ? Result /* First iteration */ 1823 : (Baseline == Result ? Baseline : Unknown); /* All others */ 1824 if (Baseline == Unknown) 1825 break; 1826 } 1827 if (Baseline != Unknown) 1828 return Baseline; 1829 } 1830 1831 // For a comparison where the V is outside this block, it's possible 1832 // that we've branched on it before. Look to see if the value is known 1833 // on all incoming edges. 1834 if (!isa<Instruction>(V) || 1835 cast<Instruction>(V)->getParent() != BB) { 1836 // For predecessor edge, determine if the comparison is true or false 1837 // on that edge. If they're all true or all false, we can conclude 1838 // the value of the comparison in this block. 1839 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI); 1840 if (Baseline != Unknown) { 1841 // Check that all remaining incoming values match the first one. 1842 while (++PI != PE) { 1843 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI); 1844 if (Ret != Baseline) break; 1845 } 1846 // If we terminated early, then one of the values didn't match. 1847 if (PI == PE) { 1848 return Baseline; 1849 } 1850 } 1851 } 1852 } 1853 return Unknown; 1854 } 1855 1856 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 1857 BasicBlock *NewSucc) { 1858 if (PImpl) { 1859 const DataLayout &DL = PredBB->getModule()->getDataLayout(); 1860 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc); 1861 } 1862 } 1863 1864 void LazyValueInfo::eraseBlock(BasicBlock *BB) { 1865 if (PImpl) { 1866 const DataLayout &DL = BB->getModule()->getDataLayout(); 1867 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB); 1868 } 1869 } 1870