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