1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 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 contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/MathExtras.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include <algorithm> 96 using namespace llvm; 97 98 #define DEBUG_TYPE "scalar-evolution" 99 100 STATISTIC(NumArrayLenItCounts, 101 "Number of trip counts computed with array length"); 102 STATISTIC(NumTripCountsComputed, 103 "Number of loops with predictable loop counts"); 104 STATISTIC(NumTripCountsNotComputed, 105 "Number of loops without predictable loop counts"); 106 STATISTIC(NumBruteForceTripCountsComputed, 107 "Number of loops with trip counts computed by force"); 108 109 static cl::opt<unsigned> 110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 111 cl::desc("Maximum number of iterations SCEV will " 112 "symbolically execute a constant " 113 "derived loop"), 114 cl::init(100)); 115 116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 117 static cl::opt<bool> VerifySCEV( 118 "verify-scev", 119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"), 120 #ifdef EXPENSIVE_CHECKS 121 cl::init(true) 122 #else 123 cl::init(false) 124 #endif 125 ); 126 127 static cl::opt<bool> 128 VerifySCEVMap("verify-scev-maps", 129 cl::desc("Verify no dangling value in ScalarEvolution's " 130 "ExprValueMap (slow)")); 131 132 static cl::opt<unsigned> MulOpsInlineThreshold( 133 "scev-mulops-inline-threshold", cl::Hidden, 134 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 135 cl::init(1000)); 136 137 static cl::opt<unsigned> AddOpsInlineThreshold( 138 "scev-addops-inline-threshold", cl::Hidden, 139 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 140 cl::init(500)); 141 142 static cl::opt<unsigned> MaxSCEVCompareDepth( 143 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 144 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 145 cl::init(32)); 146 147 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 148 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 149 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 150 cl::init(2)); 151 152 static cl::opt<unsigned> MaxValueCompareDepth( 153 "scalar-evolution-max-value-compare-depth", cl::Hidden, 154 cl::desc("Maximum depth of recursive value complexity comparisons"), 155 cl::init(2)); 156 157 static cl::opt<unsigned> 158 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden, 159 cl::desc("Maximum depth of recursive AddExpr"), 160 cl::init(32)); 161 162 static cl::opt<unsigned> MaxConstantEvolvingDepth( 163 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 164 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 165 166 //===----------------------------------------------------------------------===// 167 // SCEV class definitions 168 //===----------------------------------------------------------------------===// 169 170 //===----------------------------------------------------------------------===// 171 // Implementation of the SCEV class. 172 // 173 174 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 175 LLVM_DUMP_METHOD void SCEV::dump() const { 176 print(dbgs()); 177 dbgs() << '\n'; 178 } 179 #endif 180 181 void SCEV::print(raw_ostream &OS) const { 182 switch (static_cast<SCEVTypes>(getSCEVType())) { 183 case scConstant: 184 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 185 return; 186 case scTruncate: { 187 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 188 const SCEV *Op = Trunc->getOperand(); 189 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 190 << *Trunc->getType() << ")"; 191 return; 192 } 193 case scZeroExtend: { 194 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 195 const SCEV *Op = ZExt->getOperand(); 196 OS << "(zext " << *Op->getType() << " " << *Op << " to " 197 << *ZExt->getType() << ")"; 198 return; 199 } 200 case scSignExtend: { 201 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 202 const SCEV *Op = SExt->getOperand(); 203 OS << "(sext " << *Op->getType() << " " << *Op << " to " 204 << *SExt->getType() << ")"; 205 return; 206 } 207 case scAddRecExpr: { 208 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 209 OS << "{" << *AR->getOperand(0); 210 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 211 OS << ",+," << *AR->getOperand(i); 212 OS << "}<"; 213 if (AR->hasNoUnsignedWrap()) 214 OS << "nuw><"; 215 if (AR->hasNoSignedWrap()) 216 OS << "nsw><"; 217 if (AR->hasNoSelfWrap() && 218 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 219 OS << "nw><"; 220 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 221 OS << ">"; 222 return; 223 } 224 case scAddExpr: 225 case scMulExpr: 226 case scUMaxExpr: 227 case scSMaxExpr: { 228 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 229 const char *OpStr = nullptr; 230 switch (NAry->getSCEVType()) { 231 case scAddExpr: OpStr = " + "; break; 232 case scMulExpr: OpStr = " * "; break; 233 case scUMaxExpr: OpStr = " umax "; break; 234 case scSMaxExpr: OpStr = " smax "; break; 235 } 236 OS << "("; 237 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 238 I != E; ++I) { 239 OS << **I; 240 if (std::next(I) != E) 241 OS << OpStr; 242 } 243 OS << ")"; 244 switch (NAry->getSCEVType()) { 245 case scAddExpr: 246 case scMulExpr: 247 if (NAry->hasNoUnsignedWrap()) 248 OS << "<nuw>"; 249 if (NAry->hasNoSignedWrap()) 250 OS << "<nsw>"; 251 } 252 return; 253 } 254 case scUDivExpr: { 255 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 256 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 257 return; 258 } 259 case scUnknown: { 260 const SCEVUnknown *U = cast<SCEVUnknown>(this); 261 Type *AllocTy; 262 if (U->isSizeOf(AllocTy)) { 263 OS << "sizeof(" << *AllocTy << ")"; 264 return; 265 } 266 if (U->isAlignOf(AllocTy)) { 267 OS << "alignof(" << *AllocTy << ")"; 268 return; 269 } 270 271 Type *CTy; 272 Constant *FieldNo; 273 if (U->isOffsetOf(CTy, FieldNo)) { 274 OS << "offsetof(" << *CTy << ", "; 275 FieldNo->printAsOperand(OS, false); 276 OS << ")"; 277 return; 278 } 279 280 // Otherwise just print it normally. 281 U->getValue()->printAsOperand(OS, false); 282 return; 283 } 284 case scCouldNotCompute: 285 OS << "***COULDNOTCOMPUTE***"; 286 return; 287 } 288 llvm_unreachable("Unknown SCEV kind!"); 289 } 290 291 Type *SCEV::getType() const { 292 switch (static_cast<SCEVTypes>(getSCEVType())) { 293 case scConstant: 294 return cast<SCEVConstant>(this)->getType(); 295 case scTruncate: 296 case scZeroExtend: 297 case scSignExtend: 298 return cast<SCEVCastExpr>(this)->getType(); 299 case scAddRecExpr: 300 case scMulExpr: 301 case scUMaxExpr: 302 case scSMaxExpr: 303 return cast<SCEVNAryExpr>(this)->getType(); 304 case scAddExpr: 305 return cast<SCEVAddExpr>(this)->getType(); 306 case scUDivExpr: 307 return cast<SCEVUDivExpr>(this)->getType(); 308 case scUnknown: 309 return cast<SCEVUnknown>(this)->getType(); 310 case scCouldNotCompute: 311 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 312 } 313 llvm_unreachable("Unknown SCEV kind!"); 314 } 315 316 bool SCEV::isZero() const { 317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 318 return SC->getValue()->isZero(); 319 return false; 320 } 321 322 bool SCEV::isOne() const { 323 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 324 return SC->getValue()->isOne(); 325 return false; 326 } 327 328 bool SCEV::isAllOnesValue() const { 329 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 330 return SC->getValue()->isAllOnesValue(); 331 return false; 332 } 333 334 bool SCEV::isNonConstantNegative() const { 335 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 336 if (!Mul) return false; 337 338 // If there is a constant factor, it will be first. 339 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 340 if (!SC) return false; 341 342 // Return true if the value is negative, this matches things like (-42 * V). 343 return SC->getAPInt().isNegative(); 344 } 345 346 SCEVCouldNotCompute::SCEVCouldNotCompute() : 347 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 348 349 bool SCEVCouldNotCompute::classof(const SCEV *S) { 350 return S->getSCEVType() == scCouldNotCompute; 351 } 352 353 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 354 FoldingSetNodeID ID; 355 ID.AddInteger(scConstant); 356 ID.AddPointer(V); 357 void *IP = nullptr; 358 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 359 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 360 UniqueSCEVs.InsertNode(S, IP); 361 return S; 362 } 363 364 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 365 return getConstant(ConstantInt::get(getContext(), Val)); 366 } 367 368 const SCEV * 369 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 370 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 371 return getConstant(ConstantInt::get(ITy, V, isSigned)); 372 } 373 374 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 375 unsigned SCEVTy, const SCEV *op, Type *ty) 376 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 377 378 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 379 const SCEV *op, Type *ty) 380 : SCEVCastExpr(ID, scTruncate, op, ty) { 381 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 382 (Ty->isIntegerTy() || Ty->isPointerTy()) && 383 "Cannot truncate non-integer value!"); 384 } 385 386 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 387 const SCEV *op, Type *ty) 388 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 389 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 390 (Ty->isIntegerTy() || Ty->isPointerTy()) && 391 "Cannot zero extend non-integer value!"); 392 } 393 394 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 395 const SCEV *op, Type *ty) 396 : SCEVCastExpr(ID, scSignExtend, op, ty) { 397 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 398 (Ty->isIntegerTy() || Ty->isPointerTy()) && 399 "Cannot sign extend non-integer value!"); 400 } 401 402 void SCEVUnknown::deleted() { 403 // Clear this SCEVUnknown from various maps. 404 SE->forgetMemoizedResults(this); 405 406 // Remove this SCEVUnknown from the uniquing map. 407 SE->UniqueSCEVs.RemoveNode(this); 408 409 // Release the value. 410 setValPtr(nullptr); 411 } 412 413 void SCEVUnknown::allUsesReplacedWith(Value *New) { 414 // Clear this SCEVUnknown from various maps. 415 SE->forgetMemoizedResults(this); 416 417 // Remove this SCEVUnknown from the uniquing map. 418 SE->UniqueSCEVs.RemoveNode(this); 419 420 // Update this SCEVUnknown to point to the new value. This is needed 421 // because there may still be outstanding SCEVs which still point to 422 // this SCEVUnknown. 423 setValPtr(New); 424 } 425 426 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 428 if (VCE->getOpcode() == Instruction::PtrToInt) 429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 430 if (CE->getOpcode() == Instruction::GetElementPtr && 431 CE->getOperand(0)->isNullValue() && 432 CE->getNumOperands() == 2) 433 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 434 if (CI->isOne()) { 435 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 436 ->getElementType(); 437 return true; 438 } 439 440 return false; 441 } 442 443 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 444 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 445 if (VCE->getOpcode() == Instruction::PtrToInt) 446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 447 if (CE->getOpcode() == Instruction::GetElementPtr && 448 CE->getOperand(0)->isNullValue()) { 449 Type *Ty = 450 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 451 if (StructType *STy = dyn_cast<StructType>(Ty)) 452 if (!STy->isPacked() && 453 CE->getNumOperands() == 3 && 454 CE->getOperand(1)->isNullValue()) { 455 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 456 if (CI->isOne() && 457 STy->getNumElements() == 2 && 458 STy->getElementType(0)->isIntegerTy(1)) { 459 AllocTy = STy->getElementType(1); 460 return true; 461 } 462 } 463 } 464 465 return false; 466 } 467 468 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 469 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 470 if (VCE->getOpcode() == Instruction::PtrToInt) 471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 472 if (CE->getOpcode() == Instruction::GetElementPtr && 473 CE->getNumOperands() == 3 && 474 CE->getOperand(0)->isNullValue() && 475 CE->getOperand(1)->isNullValue()) { 476 Type *Ty = 477 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 478 // Ignore vector types here so that ScalarEvolutionExpander doesn't 479 // emit getelementptrs that index into vectors. 480 if (Ty->isStructTy() || Ty->isArrayTy()) { 481 CTy = Ty; 482 FieldNo = CE->getOperand(2); 483 return true; 484 } 485 } 486 487 return false; 488 } 489 490 //===----------------------------------------------------------------------===// 491 // SCEV Utilities 492 //===----------------------------------------------------------------------===// 493 494 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 495 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 496 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 497 /// have been previously deemed to be "equally complex" by this routine. It is 498 /// intended to avoid exponential time complexity in cases like: 499 /// 500 /// %a = f(%x, %y) 501 /// %b = f(%a, %a) 502 /// %c = f(%b, %b) 503 /// 504 /// %d = f(%x, %y) 505 /// %e = f(%d, %d) 506 /// %f = f(%e, %e) 507 /// 508 /// CompareValueComplexity(%f, %c) 509 /// 510 /// Since we do not continue running this routine on expression trees once we 511 /// have seen unequal values, there is no need to track them in the cache. 512 static int 513 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 514 const LoopInfo *const LI, Value *LV, Value *RV, 515 unsigned Depth) { 516 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV})) 517 return 0; 518 519 // Order pointer values after integer values. This helps SCEVExpander form 520 // GEPs. 521 bool LIsPointer = LV->getType()->isPointerTy(), 522 RIsPointer = RV->getType()->isPointerTy(); 523 if (LIsPointer != RIsPointer) 524 return (int)LIsPointer - (int)RIsPointer; 525 526 // Compare getValueID values. 527 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 528 if (LID != RID) 529 return (int)LID - (int)RID; 530 531 // Sort arguments by their position. 532 if (const auto *LA = dyn_cast<Argument>(LV)) { 533 const auto *RA = cast<Argument>(RV); 534 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 535 return (int)LArgNo - (int)RArgNo; 536 } 537 538 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 539 const auto *RGV = cast<GlobalValue>(RV); 540 541 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 542 auto LT = GV->getLinkage(); 543 return !(GlobalValue::isPrivateLinkage(LT) || 544 GlobalValue::isInternalLinkage(LT)); 545 }; 546 547 // Use the names to distinguish the two values, but only if the 548 // names are semantically important. 549 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 550 return LGV->getName().compare(RGV->getName()); 551 } 552 553 // For instructions, compare their loop depth, and their operand count. This 554 // is pretty loose. 555 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 556 const auto *RInst = cast<Instruction>(RV); 557 558 // Compare loop depths. 559 const BasicBlock *LParent = LInst->getParent(), 560 *RParent = RInst->getParent(); 561 if (LParent != RParent) { 562 unsigned LDepth = LI->getLoopDepth(LParent), 563 RDepth = LI->getLoopDepth(RParent); 564 if (LDepth != RDepth) 565 return (int)LDepth - (int)RDepth; 566 } 567 568 // Compare the number of operands. 569 unsigned LNumOps = LInst->getNumOperands(), 570 RNumOps = RInst->getNumOperands(); 571 if (LNumOps != RNumOps) 572 return (int)LNumOps - (int)RNumOps; 573 574 for (unsigned Idx : seq(0u, LNumOps)) { 575 int Result = 576 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 577 RInst->getOperand(Idx), Depth + 1); 578 if (Result != 0) 579 return Result; 580 } 581 } 582 583 EqCache.insert({LV, RV}); 584 return 0; 585 } 586 587 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 588 // than RHS, respectively. A three-way result allows recursive comparisons to be 589 // more efficient. 590 static int CompareSCEVComplexity( 591 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 592 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 593 unsigned Depth = 0) { 594 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 595 if (LHS == RHS) 596 return 0; 597 598 // Primarily, sort the SCEVs by their getSCEVType(). 599 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 600 if (LType != RType) 601 return (int)LType - (int)RType; 602 603 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS})) 604 return 0; 605 // Aside from the getSCEVType() ordering, the particular ordering 606 // isn't very important except that it's beneficial to be consistent, 607 // so that (a + b) and (b + a) don't end up as different expressions. 608 switch (static_cast<SCEVTypes>(LType)) { 609 case scUnknown: { 610 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 611 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 612 613 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 614 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 615 Depth + 1); 616 if (X == 0) 617 EqCacheSCEV.insert({LHS, RHS}); 618 return X; 619 } 620 621 case scConstant: { 622 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 623 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 624 625 // Compare constant values. 626 const APInt &LA = LC->getAPInt(); 627 const APInt &RA = RC->getAPInt(); 628 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 629 if (LBitWidth != RBitWidth) 630 return (int)LBitWidth - (int)RBitWidth; 631 return LA.ult(RA) ? -1 : 1; 632 } 633 634 case scAddRecExpr: { 635 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 636 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 637 638 // Compare addrec loop depths. 639 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 640 if (LLoop != RLoop) { 641 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 642 if (LDepth != RDepth) 643 return (int)LDepth - (int)RDepth; 644 } 645 646 // Addrec complexity grows with operand count. 647 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 648 if (LNumOps != RNumOps) 649 return (int)LNumOps - (int)RNumOps; 650 651 // Lexicographically compare. 652 for (unsigned i = 0; i != LNumOps; ++i) { 653 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 654 RA->getOperand(i), Depth + 1); 655 if (X != 0) 656 return X; 657 } 658 EqCacheSCEV.insert({LHS, RHS}); 659 return 0; 660 } 661 662 case scAddExpr: 663 case scMulExpr: 664 case scSMaxExpr: 665 case scUMaxExpr: { 666 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 667 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 668 669 // Lexicographically compare n-ary expressions. 670 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 671 if (LNumOps != RNumOps) 672 return (int)LNumOps - (int)RNumOps; 673 674 for (unsigned i = 0; i != LNumOps; ++i) { 675 if (i >= RNumOps) 676 return 1; 677 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 678 RC->getOperand(i), Depth + 1); 679 if (X != 0) 680 return X; 681 } 682 EqCacheSCEV.insert({LHS, RHS}); 683 return 0; 684 } 685 686 case scUDivExpr: { 687 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 688 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 689 690 // Lexicographically compare udiv expressions. 691 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 692 Depth + 1); 693 if (X != 0) 694 return X; 695 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), 696 Depth + 1); 697 if (X == 0) 698 EqCacheSCEV.insert({LHS, RHS}); 699 return X; 700 } 701 702 case scTruncate: 703 case scZeroExtend: 704 case scSignExtend: { 705 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 706 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 707 708 // Compare cast expressions by operand. 709 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 710 RC->getOperand(), Depth + 1); 711 if (X == 0) 712 EqCacheSCEV.insert({LHS, RHS}); 713 return X; 714 } 715 716 case scCouldNotCompute: 717 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 718 } 719 llvm_unreachable("Unknown SCEV kind!"); 720 } 721 722 /// Given a list of SCEV objects, order them by their complexity, and group 723 /// objects of the same complexity together by value. When this routine is 724 /// finished, we know that any duplicates in the vector are consecutive and that 725 /// complexity is monotonically increasing. 726 /// 727 /// Note that we go take special precautions to ensure that we get deterministic 728 /// results from this routine. In other words, we don't want the results of 729 /// this to depend on where the addresses of various SCEV objects happened to 730 /// land in memory. 731 /// 732 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 733 LoopInfo *LI) { 734 if (Ops.size() < 2) return; // Noop 735 736 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 737 if (Ops.size() == 2) { 738 // This is the common case, which also happens to be trivially simple. 739 // Special case it. 740 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 741 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) 742 std::swap(LHS, RHS); 743 return; 744 } 745 746 // Do the rough sort by complexity. 747 std::stable_sort(Ops.begin(), Ops.end(), 748 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { 749 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; 750 }); 751 752 // Now that we are sorted by complexity, group elements of the same 753 // complexity. Note that this is, at worst, N^2, but the vector is likely to 754 // be extremely short in practice. Note that we take this approach because we 755 // do not want to depend on the addresses of the objects we are grouping. 756 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 757 const SCEV *S = Ops[i]; 758 unsigned Complexity = S->getSCEVType(); 759 760 // If there are any objects of the same complexity and same value as this 761 // one, group them. 762 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 763 if (Ops[j] == S) { // Found a duplicate. 764 // Move it to immediately after i'th element. 765 std::swap(Ops[i+1], Ops[j]); 766 ++i; // no need to rescan it. 767 if (i == e-2) return; // Done! 768 } 769 } 770 } 771 } 772 773 // Returns the size of the SCEV S. 774 static inline int sizeOfSCEV(const SCEV *S) { 775 struct FindSCEVSize { 776 int Size; 777 FindSCEVSize() : Size(0) {} 778 779 bool follow(const SCEV *S) { 780 ++Size; 781 // Keep looking at all operands of S. 782 return true; 783 } 784 bool isDone() const { 785 return false; 786 } 787 }; 788 789 FindSCEVSize F; 790 SCEVTraversal<FindSCEVSize> ST(F); 791 ST.visitAll(S); 792 return F.Size; 793 } 794 795 namespace { 796 797 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 798 public: 799 // Computes the Quotient and Remainder of the division of Numerator by 800 // Denominator. 801 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 802 const SCEV *Denominator, const SCEV **Quotient, 803 const SCEV **Remainder) { 804 assert(Numerator && Denominator && "Uninitialized SCEV"); 805 806 SCEVDivision D(SE, Numerator, Denominator); 807 808 // Check for the trivial case here to avoid having to check for it in the 809 // rest of the code. 810 if (Numerator == Denominator) { 811 *Quotient = D.One; 812 *Remainder = D.Zero; 813 return; 814 } 815 816 if (Numerator->isZero()) { 817 *Quotient = D.Zero; 818 *Remainder = D.Zero; 819 return; 820 } 821 822 // A simple case when N/1. The quotient is N. 823 if (Denominator->isOne()) { 824 *Quotient = Numerator; 825 *Remainder = D.Zero; 826 return; 827 } 828 829 // Split the Denominator when it is a product. 830 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 831 const SCEV *Q, *R; 832 *Quotient = Numerator; 833 for (const SCEV *Op : T->operands()) { 834 divide(SE, *Quotient, Op, &Q, &R); 835 *Quotient = Q; 836 837 // Bail out when the Numerator is not divisible by one of the terms of 838 // the Denominator. 839 if (!R->isZero()) { 840 *Quotient = D.Zero; 841 *Remainder = Numerator; 842 return; 843 } 844 } 845 *Remainder = D.Zero; 846 return; 847 } 848 849 D.visit(Numerator); 850 *Quotient = D.Quotient; 851 *Remainder = D.Remainder; 852 } 853 854 // Except in the trivial case described above, we do not know how to divide 855 // Expr by Denominator for the following functions with empty implementation. 856 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 857 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 858 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 859 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 860 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 861 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 862 void visitUnknown(const SCEVUnknown *Numerator) {} 863 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 864 865 void visitConstant(const SCEVConstant *Numerator) { 866 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 867 APInt NumeratorVal = Numerator->getAPInt(); 868 APInt DenominatorVal = D->getAPInt(); 869 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 870 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 871 872 if (NumeratorBW > DenominatorBW) 873 DenominatorVal = DenominatorVal.sext(NumeratorBW); 874 else if (NumeratorBW < DenominatorBW) 875 NumeratorVal = NumeratorVal.sext(DenominatorBW); 876 877 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 878 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 879 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 880 Quotient = SE.getConstant(QuotientVal); 881 Remainder = SE.getConstant(RemainderVal); 882 return; 883 } 884 } 885 886 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 887 const SCEV *StartQ, *StartR, *StepQ, *StepR; 888 if (!Numerator->isAffine()) 889 return cannotDivide(Numerator); 890 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 891 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 892 // Bail out if the types do not match. 893 Type *Ty = Denominator->getType(); 894 if (Ty != StartQ->getType() || Ty != StartR->getType() || 895 Ty != StepQ->getType() || Ty != StepR->getType()) 896 return cannotDivide(Numerator); 897 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 898 Numerator->getNoWrapFlags()); 899 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 900 Numerator->getNoWrapFlags()); 901 } 902 903 void visitAddExpr(const SCEVAddExpr *Numerator) { 904 SmallVector<const SCEV *, 2> Qs, Rs; 905 Type *Ty = Denominator->getType(); 906 907 for (const SCEV *Op : Numerator->operands()) { 908 const SCEV *Q, *R; 909 divide(SE, Op, Denominator, &Q, &R); 910 911 // Bail out if types do not match. 912 if (Ty != Q->getType() || Ty != R->getType()) 913 return cannotDivide(Numerator); 914 915 Qs.push_back(Q); 916 Rs.push_back(R); 917 } 918 919 if (Qs.size() == 1) { 920 Quotient = Qs[0]; 921 Remainder = Rs[0]; 922 return; 923 } 924 925 Quotient = SE.getAddExpr(Qs); 926 Remainder = SE.getAddExpr(Rs); 927 } 928 929 void visitMulExpr(const SCEVMulExpr *Numerator) { 930 SmallVector<const SCEV *, 2> Qs; 931 Type *Ty = Denominator->getType(); 932 933 bool FoundDenominatorTerm = false; 934 for (const SCEV *Op : Numerator->operands()) { 935 // Bail out if types do not match. 936 if (Ty != Op->getType()) 937 return cannotDivide(Numerator); 938 939 if (FoundDenominatorTerm) { 940 Qs.push_back(Op); 941 continue; 942 } 943 944 // Check whether Denominator divides one of the product operands. 945 const SCEV *Q, *R; 946 divide(SE, Op, Denominator, &Q, &R); 947 if (!R->isZero()) { 948 Qs.push_back(Op); 949 continue; 950 } 951 952 // Bail out if types do not match. 953 if (Ty != Q->getType()) 954 return cannotDivide(Numerator); 955 956 FoundDenominatorTerm = true; 957 Qs.push_back(Q); 958 } 959 960 if (FoundDenominatorTerm) { 961 Remainder = Zero; 962 if (Qs.size() == 1) 963 Quotient = Qs[0]; 964 else 965 Quotient = SE.getMulExpr(Qs); 966 return; 967 } 968 969 if (!isa<SCEVUnknown>(Denominator)) 970 return cannotDivide(Numerator); 971 972 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 973 ValueToValueMap RewriteMap; 974 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 975 cast<SCEVConstant>(Zero)->getValue(); 976 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 977 978 if (Remainder->isZero()) { 979 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 980 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 981 cast<SCEVConstant>(One)->getValue(); 982 Quotient = 983 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 984 return; 985 } 986 987 // Quotient is (Numerator - Remainder) divided by Denominator. 988 const SCEV *Q, *R; 989 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 990 // This SCEV does not seem to simplify: fail the division here. 991 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 992 return cannotDivide(Numerator); 993 divide(SE, Diff, Denominator, &Q, &R); 994 if (R != Zero) 995 return cannotDivide(Numerator); 996 Quotient = Q; 997 } 998 999 private: 1000 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1001 const SCEV *Denominator) 1002 : SE(S), Denominator(Denominator) { 1003 Zero = SE.getZero(Denominator->getType()); 1004 One = SE.getOne(Denominator->getType()); 1005 1006 // We generally do not know how to divide Expr by Denominator. We 1007 // initialize the division to a "cannot divide" state to simplify the rest 1008 // of the code. 1009 cannotDivide(Numerator); 1010 } 1011 1012 // Convenience function for giving up on the division. We set the quotient to 1013 // be equal to zero and the remainder to be equal to the numerator. 1014 void cannotDivide(const SCEV *Numerator) { 1015 Quotient = Zero; 1016 Remainder = Numerator; 1017 } 1018 1019 ScalarEvolution &SE; 1020 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1021 }; 1022 1023 } 1024 1025 //===----------------------------------------------------------------------===// 1026 // Simple SCEV method implementations 1027 //===----------------------------------------------------------------------===// 1028 1029 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1030 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1031 ScalarEvolution &SE, 1032 Type *ResultTy) { 1033 // Handle the simplest case efficiently. 1034 if (K == 1) 1035 return SE.getTruncateOrZeroExtend(It, ResultTy); 1036 1037 // We are using the following formula for BC(It, K): 1038 // 1039 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1040 // 1041 // Suppose, W is the bitwidth of the return value. We must be prepared for 1042 // overflow. Hence, we must assure that the result of our computation is 1043 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1044 // safe in modular arithmetic. 1045 // 1046 // However, this code doesn't use exactly that formula; the formula it uses 1047 // is something like the following, where T is the number of factors of 2 in 1048 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1049 // exponentiation: 1050 // 1051 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1052 // 1053 // This formula is trivially equivalent to the previous formula. However, 1054 // this formula can be implemented much more efficiently. The trick is that 1055 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1056 // arithmetic. To do exact division in modular arithmetic, all we have 1057 // to do is multiply by the inverse. Therefore, this step can be done at 1058 // width W. 1059 // 1060 // The next issue is how to safely do the division by 2^T. The way this 1061 // is done is by doing the multiplication step at a width of at least W + T 1062 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1063 // when we perform the division by 2^T (which is equivalent to a right shift 1064 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1065 // truncated out after the division by 2^T. 1066 // 1067 // In comparison to just directly using the first formula, this technique 1068 // is much more efficient; using the first formula requires W * K bits, 1069 // but this formula less than W + K bits. Also, the first formula requires 1070 // a division step, whereas this formula only requires multiplies and shifts. 1071 // 1072 // It doesn't matter whether the subtraction step is done in the calculation 1073 // width or the input iteration count's width; if the subtraction overflows, 1074 // the result must be zero anyway. We prefer here to do it in the width of 1075 // the induction variable because it helps a lot for certain cases; CodeGen 1076 // isn't smart enough to ignore the overflow, which leads to much less 1077 // efficient code if the width of the subtraction is wider than the native 1078 // register width. 1079 // 1080 // (It's possible to not widen at all by pulling out factors of 2 before 1081 // the multiplication; for example, K=2 can be calculated as 1082 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1083 // extra arithmetic, so it's not an obvious win, and it gets 1084 // much more complicated for K > 3.) 1085 1086 // Protection from insane SCEVs; this bound is conservative, 1087 // but it probably doesn't matter. 1088 if (K > 1000) 1089 return SE.getCouldNotCompute(); 1090 1091 unsigned W = SE.getTypeSizeInBits(ResultTy); 1092 1093 // Calculate K! / 2^T and T; we divide out the factors of two before 1094 // multiplying for calculating K! / 2^T to avoid overflow. 1095 // Other overflow doesn't matter because we only care about the bottom 1096 // W bits of the result. 1097 APInt OddFactorial(W, 1); 1098 unsigned T = 1; 1099 for (unsigned i = 3; i <= K; ++i) { 1100 APInt Mult(W, i); 1101 unsigned TwoFactors = Mult.countTrailingZeros(); 1102 T += TwoFactors; 1103 Mult.lshrInPlace(TwoFactors); 1104 OddFactorial *= Mult; 1105 } 1106 1107 // We need at least W + T bits for the multiplication step 1108 unsigned CalculationBits = W + T; 1109 1110 // Calculate 2^T, at width T+W. 1111 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1112 1113 // Calculate the multiplicative inverse of K! / 2^T; 1114 // this multiplication factor will perform the exact division by 1115 // K! / 2^T. 1116 APInt Mod = APInt::getSignedMinValue(W+1); 1117 APInt MultiplyFactor = OddFactorial.zext(W+1); 1118 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1119 MultiplyFactor = MultiplyFactor.trunc(W); 1120 1121 // Calculate the product, at width T+W 1122 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1123 CalculationBits); 1124 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1125 for (unsigned i = 1; i != K; ++i) { 1126 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1127 Dividend = SE.getMulExpr(Dividend, 1128 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1129 } 1130 1131 // Divide by 2^T 1132 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1133 1134 // Truncate the result, and divide by K! / 2^T. 1135 1136 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1137 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1138 } 1139 1140 /// Return the value of this chain of recurrences at the specified iteration 1141 /// number. We can evaluate this recurrence by multiplying each element in the 1142 /// chain by the binomial coefficient corresponding to it. In other words, we 1143 /// can evaluate {A,+,B,+,C,+,D} as: 1144 /// 1145 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1146 /// 1147 /// where BC(It, k) stands for binomial coefficient. 1148 /// 1149 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1150 ScalarEvolution &SE) const { 1151 const SCEV *Result = getStart(); 1152 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1153 // The computation is correct in the face of overflow provided that the 1154 // multiplication is performed _after_ the evaluation of the binomial 1155 // coefficient. 1156 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1157 if (isa<SCEVCouldNotCompute>(Coeff)) 1158 return Coeff; 1159 1160 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1161 } 1162 return Result; 1163 } 1164 1165 //===----------------------------------------------------------------------===// 1166 // SCEV Expression folder implementations 1167 //===----------------------------------------------------------------------===// 1168 1169 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1170 Type *Ty) { 1171 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1172 "This is not a truncating conversion!"); 1173 assert(isSCEVable(Ty) && 1174 "This is not a conversion to a SCEVable type!"); 1175 Ty = getEffectiveSCEVType(Ty); 1176 1177 FoldingSetNodeID ID; 1178 ID.AddInteger(scTruncate); 1179 ID.AddPointer(Op); 1180 ID.AddPointer(Ty); 1181 void *IP = nullptr; 1182 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1183 1184 // Fold if the operand is constant. 1185 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1186 return getConstant( 1187 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1188 1189 // trunc(trunc(x)) --> trunc(x) 1190 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1191 return getTruncateExpr(ST->getOperand(), Ty); 1192 1193 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1194 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1195 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1196 1197 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1198 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1199 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1200 1201 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1202 // eliminate all the truncates, or we replace other casts with truncates. 1203 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1204 SmallVector<const SCEV *, 4> Operands; 1205 bool hasTrunc = false; 1206 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1207 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1208 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1209 hasTrunc = isa<SCEVTruncateExpr>(S); 1210 Operands.push_back(S); 1211 } 1212 if (!hasTrunc) 1213 return getAddExpr(Operands); 1214 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1215 } 1216 1217 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1218 // eliminate all the truncates, or we replace other casts with truncates. 1219 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1220 SmallVector<const SCEV *, 4> Operands; 1221 bool hasTrunc = false; 1222 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1223 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1224 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1225 hasTrunc = isa<SCEVTruncateExpr>(S); 1226 Operands.push_back(S); 1227 } 1228 if (!hasTrunc) 1229 return getMulExpr(Operands); 1230 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1231 } 1232 1233 // If the input value is a chrec scev, truncate the chrec's operands. 1234 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1235 SmallVector<const SCEV *, 4> Operands; 1236 for (const SCEV *Op : AddRec->operands()) 1237 Operands.push_back(getTruncateExpr(Op, Ty)); 1238 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1239 } 1240 1241 // The cast wasn't folded; create an explicit cast node. We can reuse 1242 // the existing insert position since if we get here, we won't have 1243 // made any changes which would invalidate it. 1244 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1245 Op, Ty); 1246 UniqueSCEVs.InsertNode(S, IP); 1247 return S; 1248 } 1249 1250 // Get the limit of a recurrence such that incrementing by Step cannot cause 1251 // signed overflow as long as the value of the recurrence within the 1252 // loop does not exceed this limit before incrementing. 1253 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1254 ICmpInst::Predicate *Pred, 1255 ScalarEvolution *SE) { 1256 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1257 if (SE->isKnownPositive(Step)) { 1258 *Pred = ICmpInst::ICMP_SLT; 1259 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1260 SE->getSignedRange(Step).getSignedMax()); 1261 } 1262 if (SE->isKnownNegative(Step)) { 1263 *Pred = ICmpInst::ICMP_SGT; 1264 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1265 SE->getSignedRange(Step).getSignedMin()); 1266 } 1267 return nullptr; 1268 } 1269 1270 // Get the limit of a recurrence such that incrementing by Step cannot cause 1271 // unsigned overflow as long as the value of the recurrence within the loop does 1272 // not exceed this limit before incrementing. 1273 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1274 ICmpInst::Predicate *Pred, 1275 ScalarEvolution *SE) { 1276 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1277 *Pred = ICmpInst::ICMP_ULT; 1278 1279 return SE->getConstant(APInt::getMinValue(BitWidth) - 1280 SE->getUnsignedRange(Step).getUnsignedMax()); 1281 } 1282 1283 namespace { 1284 1285 struct ExtendOpTraitsBase { 1286 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)( 1287 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache); 1288 }; 1289 1290 // Used to make code generic over signed and unsigned overflow. 1291 template <typename ExtendOp> struct ExtendOpTraits { 1292 // Members present: 1293 // 1294 // static const SCEV::NoWrapFlags WrapType; 1295 // 1296 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1297 // 1298 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1299 // ICmpInst::Predicate *Pred, 1300 // ScalarEvolution *SE); 1301 }; 1302 1303 template <> 1304 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1306 1307 static const GetExtendExprTy GetExtendExpr; 1308 1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1310 ICmpInst::Predicate *Pred, 1311 ScalarEvolution *SE) { 1312 return getSignedOverflowLimitForStep(Step, Pred, SE); 1313 } 1314 }; 1315 1316 const ExtendOpTraitsBase::GetExtendExprTy 1317 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr = 1318 &ScalarEvolution::getSignExtendExprCached; 1319 1320 template <> 1321 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1322 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1323 1324 static const GetExtendExprTy GetExtendExpr; 1325 1326 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1327 ICmpInst::Predicate *Pred, 1328 ScalarEvolution *SE) { 1329 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1330 } 1331 }; 1332 1333 const ExtendOpTraitsBase::GetExtendExprTy 1334 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr = 1335 &ScalarEvolution::getZeroExtendExprCached; 1336 } 1337 1338 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1339 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1340 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1341 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1342 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1343 // expression "Step + sext/zext(PreIncAR)" is congruent with 1344 // "sext/zext(PostIncAR)" 1345 template <typename ExtendOpTy> 1346 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1347 ScalarEvolution *SE, 1348 ScalarEvolution::ExtendCacheTy &Cache) { 1349 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1350 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1351 1352 const Loop *L = AR->getLoop(); 1353 const SCEV *Start = AR->getStart(); 1354 const SCEV *Step = AR->getStepRecurrence(*SE); 1355 1356 // Check for a simple looking step prior to loop entry. 1357 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1358 if (!SA) 1359 return nullptr; 1360 1361 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1362 // subtraction is expensive. For this purpose, perform a quick and dirty 1363 // difference, by checking for Step in the operand list. 1364 SmallVector<const SCEV *, 4> DiffOps; 1365 for (const SCEV *Op : SA->operands()) 1366 if (Op != Step) 1367 DiffOps.push_back(Op); 1368 1369 if (DiffOps.size() == SA->getNumOperands()) 1370 return nullptr; 1371 1372 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1373 // `Step`: 1374 1375 // 1. NSW/NUW flags on the step increment. 1376 auto PreStartFlags = 1377 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1378 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1379 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1380 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1381 1382 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1383 // "S+X does not sign/unsign-overflow". 1384 // 1385 1386 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1387 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1388 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1389 return PreStart; 1390 1391 // 2. Direct overflow check on the step operation's expression. 1392 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1393 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1394 const SCEV *OperandExtendedStart = 1395 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache), 1396 (SE->*GetExtendExpr)(Step, WideTy, Cache)); 1397 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) { 1398 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1399 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1400 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1401 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1402 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1403 } 1404 return PreStart; 1405 } 1406 1407 // 3. Loop precondition. 1408 ICmpInst::Predicate Pred; 1409 const SCEV *OverflowLimit = 1410 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1411 1412 if (OverflowLimit && 1413 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1414 return PreStart; 1415 1416 return nullptr; 1417 } 1418 1419 // Get the normalized zero or sign extended expression for this AddRec's Start. 1420 template <typename ExtendOpTy> 1421 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1422 ScalarEvolution *SE, 1423 ScalarEvolution::ExtendCacheTy &Cache) { 1424 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1425 1426 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache); 1427 if (!PreStart) 1428 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache); 1429 1430 return SE->getAddExpr( 1431 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache), 1432 (SE->*GetExtendExpr)(PreStart, Ty, Cache)); 1433 } 1434 1435 // Try to prove away overflow by looking at "nearby" add recurrences. A 1436 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1437 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1438 // 1439 // Formally: 1440 // 1441 // {S,+,X} == {S-T,+,X} + T 1442 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1443 // 1444 // If ({S-T,+,X} + T) does not overflow ... (1) 1445 // 1446 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1447 // 1448 // If {S-T,+,X} does not overflow ... (2) 1449 // 1450 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1451 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1452 // 1453 // If (S-T)+T does not overflow ... (3) 1454 // 1455 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1456 // == {Ext(S),+,Ext(X)} == LHS 1457 // 1458 // Thus, if (1), (2) and (3) are true for some T, then 1459 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1460 // 1461 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1462 // does not overflow" restricted to the 0th iteration. Therefore we only need 1463 // to check for (1) and (2). 1464 // 1465 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1466 // is `Delta` (defined below). 1467 // 1468 template <typename ExtendOpTy> 1469 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1470 const SCEV *Step, 1471 const Loop *L) { 1472 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1473 1474 // We restrict `Start` to a constant to prevent SCEV from spending too much 1475 // time here. It is correct (but more expensive) to continue with a 1476 // non-constant `Start` and do a general SCEV subtraction to compute 1477 // `PreStart` below. 1478 // 1479 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1480 if (!StartC) 1481 return false; 1482 1483 APInt StartAI = StartC->getAPInt(); 1484 1485 for (unsigned Delta : {-2, -1, 1, 2}) { 1486 const SCEV *PreStart = getConstant(StartAI - Delta); 1487 1488 FoldingSetNodeID ID; 1489 ID.AddInteger(scAddRecExpr); 1490 ID.AddPointer(PreStart); 1491 ID.AddPointer(Step); 1492 ID.AddPointer(L); 1493 void *IP = nullptr; 1494 const auto *PreAR = 1495 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1496 1497 // Give up if we don't already have the add recurrence we need because 1498 // actually constructing an add recurrence is relatively expensive. 1499 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1500 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1501 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1502 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1503 DeltaS, &Pred, this); 1504 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1505 return true; 1506 } 1507 } 1508 1509 return false; 1510 } 1511 1512 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) { 1513 // Use the local cache to prevent exponential behavior of 1514 // getZeroExtendExprImpl. 1515 ExtendCacheTy Cache; 1516 return getZeroExtendExprCached(Op, Ty, Cache); 1517 } 1518 1519 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no 1520 /// related entry in the \p Cache, call getZeroExtendExprImpl and save 1521 /// the result in the \p Cache. 1522 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty, 1523 ExtendCacheTy &Cache) { 1524 auto It = Cache.find({Op, Ty}); 1525 if (It != Cache.end()) 1526 return It->second; 1527 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache); 1528 auto InsertResult = Cache.insert({{Op, Ty}, ZExt}); 1529 assert(InsertResult.second && "Expect the key was not in the cache"); 1530 (void)InsertResult; 1531 return ZExt; 1532 } 1533 1534 /// The real implementation of getZeroExtendExpr. 1535 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty, 1536 ExtendCacheTy &Cache) { 1537 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1538 "This is not an extending conversion!"); 1539 assert(isSCEVable(Ty) && 1540 "This is not a conversion to a SCEVable type!"); 1541 Ty = getEffectiveSCEVType(Ty); 1542 1543 // Fold if the operand is constant. 1544 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1545 return getConstant( 1546 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1547 1548 // zext(zext(x)) --> zext(x) 1549 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1550 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache); 1551 1552 // Before doing any expensive analysis, check to see if we've already 1553 // computed a SCEV for this Op and Ty. 1554 FoldingSetNodeID ID; 1555 ID.AddInteger(scZeroExtend); 1556 ID.AddPointer(Op); 1557 ID.AddPointer(Ty); 1558 void *IP = nullptr; 1559 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1560 1561 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1562 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1563 // It's possible the bits taken off by the truncate were all zero bits. If 1564 // so, we should be able to simplify this further. 1565 const SCEV *X = ST->getOperand(); 1566 ConstantRange CR = getUnsignedRange(X); 1567 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1568 unsigned NewBits = getTypeSizeInBits(Ty); 1569 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1570 CR.zextOrTrunc(NewBits))) 1571 return getTruncateOrZeroExtend(X, Ty); 1572 } 1573 1574 // If the input value is a chrec scev, and we can prove that the value 1575 // did not overflow the old, smaller, value, we can zero extend all of the 1576 // operands (often constants). This allows analysis of something like 1577 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1578 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1579 if (AR->isAffine()) { 1580 const SCEV *Start = AR->getStart(); 1581 const SCEV *Step = AR->getStepRecurrence(*this); 1582 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1583 const Loop *L = AR->getLoop(); 1584 1585 if (!AR->hasNoUnsignedWrap()) { 1586 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1587 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1588 } 1589 1590 // If we have special knowledge that this addrec won't overflow, 1591 // we don't need to do any further analysis. 1592 if (AR->hasNoUnsignedWrap()) 1593 return getAddRecExpr( 1594 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1595 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1596 1597 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1598 // Note that this serves two purposes: It filters out loops that are 1599 // simply not analyzable, and it covers the case where this code is 1600 // being called from within backedge-taken count analysis, such that 1601 // attempting to ask for the backedge-taken count would likely result 1602 // in infinite recursion. In the later case, the analysis code will 1603 // cope with a conservative value, and it will take care to purge 1604 // that value once it has finished. 1605 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1606 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1607 // Manually compute the final value for AR, checking for 1608 // overflow. 1609 1610 // Check whether the backedge-taken count can be losslessly casted to 1611 // the addrec's type. The count is always unsigned. 1612 const SCEV *CastedMaxBECount = 1613 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1614 const SCEV *RecastedMaxBECount = 1615 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1616 if (MaxBECount == RecastedMaxBECount) { 1617 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1618 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1619 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1620 const SCEV *ZAdd = 1621 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache); 1622 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache); 1623 const SCEV *WideMaxBECount = 1624 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache); 1625 const SCEV *OperandExtendedAdd = getAddExpr( 1626 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached( 1627 Step, WideTy, Cache))); 1628 if (ZAdd == OperandExtendedAdd) { 1629 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1630 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1631 // Return the expression with the addrec on the outside. 1632 return getAddRecExpr( 1633 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1634 getZeroExtendExprCached(Step, Ty, Cache), L, 1635 AR->getNoWrapFlags()); 1636 } 1637 // Similar to above, only this time treat the step value as signed. 1638 // This covers loops that count down. 1639 OperandExtendedAdd = 1640 getAddExpr(WideStart, 1641 getMulExpr(WideMaxBECount, 1642 getSignExtendExpr(Step, WideTy))); 1643 if (ZAdd == OperandExtendedAdd) { 1644 // Cache knowledge of AR NW, which is propagated to this AddRec. 1645 // Negative step causes unsigned wrap, but it still can't self-wrap. 1646 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1647 // Return the expression with the addrec on the outside. 1648 return getAddRecExpr( 1649 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1650 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1651 } 1652 } 1653 } 1654 1655 // Normally, in the cases we can prove no-overflow via a 1656 // backedge guarding condition, we can also compute a backedge 1657 // taken count for the loop. The exceptions are assumptions and 1658 // guards present in the loop -- SCEV is not great at exploiting 1659 // these to compute max backedge taken counts, but can still use 1660 // these to prove lack of overflow. Use this fact to avoid 1661 // doing extra work that may not pay off. 1662 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1663 !AC.assumptions().empty()) { 1664 // If the backedge is guarded by a comparison with the pre-inc 1665 // value the addrec is safe. Also, if the entry is guarded by 1666 // a comparison with the start value and the backedge is 1667 // guarded by a comparison with the post-inc value, the addrec 1668 // is safe. 1669 if (isKnownPositive(Step)) { 1670 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1671 getUnsignedRange(Step).getUnsignedMax()); 1672 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1673 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1674 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1675 AR->getPostIncExpr(*this), N))) { 1676 // Cache knowledge of AR NUW, which is propagated to this 1677 // AddRec. 1678 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1679 // Return the expression with the addrec on the outside. 1680 return getAddRecExpr( 1681 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1682 getZeroExtendExprCached(Step, Ty, Cache), L, 1683 AR->getNoWrapFlags()); 1684 } 1685 } else if (isKnownNegative(Step)) { 1686 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1687 getSignedRange(Step).getSignedMin()); 1688 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1689 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1690 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1691 AR->getPostIncExpr(*this), N))) { 1692 // Cache knowledge of AR NW, which is propagated to this 1693 // AddRec. Negative step causes unsigned wrap, but it 1694 // still can't self-wrap. 1695 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1696 // Return the expression with the addrec on the outside. 1697 return getAddRecExpr( 1698 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1699 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1700 } 1701 } 1702 } 1703 1704 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1705 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1706 return getAddRecExpr( 1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1708 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1709 } 1710 } 1711 1712 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1713 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1714 if (SA->hasNoUnsignedWrap()) { 1715 // If the addition does not unsign overflow then we can, by definition, 1716 // commute the zero extension with the addition operation. 1717 SmallVector<const SCEV *, 4> Ops; 1718 for (const auto *Op : SA->operands()) 1719 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache)); 1720 return getAddExpr(Ops, SCEV::FlagNUW); 1721 } 1722 } 1723 1724 // The cast wasn't folded; create an explicit cast node. 1725 // Recompute the insert position, as it may have been invalidated. 1726 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1727 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1728 Op, Ty); 1729 UniqueSCEVs.InsertNode(S, IP); 1730 return S; 1731 } 1732 1733 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) { 1734 // Use the local cache to prevent exponential behavior of 1735 // getSignExtendExprImpl. 1736 ExtendCacheTy Cache; 1737 return getSignExtendExprCached(Op, Ty, Cache); 1738 } 1739 1740 /// Query \p Cache before calling getSignExtendExprImpl. If there is no 1741 /// related entry in the \p Cache, call getSignExtendExprImpl and save 1742 /// the result in the \p Cache. 1743 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty, 1744 ExtendCacheTy &Cache) { 1745 auto It = Cache.find({Op, Ty}); 1746 if (It != Cache.end()) 1747 return It->second; 1748 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache); 1749 auto InsertResult = Cache.insert({{Op, Ty}, SExt}); 1750 assert(InsertResult.second && "Expect the key was not in the cache"); 1751 (void)InsertResult; 1752 return SExt; 1753 } 1754 1755 /// The real implementation of getSignExtendExpr. 1756 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty, 1757 ExtendCacheTy &Cache) { 1758 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1759 "This is not an extending conversion!"); 1760 assert(isSCEVable(Ty) && 1761 "This is not a conversion to a SCEVable type!"); 1762 Ty = getEffectiveSCEVType(Ty); 1763 1764 // Fold if the operand is constant. 1765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1766 return getConstant( 1767 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1768 1769 // sext(sext(x)) --> sext(x) 1770 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1771 return getSignExtendExprCached(SS->getOperand(), Ty, Cache); 1772 1773 // sext(zext(x)) --> zext(x) 1774 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1775 return getZeroExtendExpr(SZ->getOperand(), Ty); 1776 1777 // Before doing any expensive analysis, check to see if we've already 1778 // computed a SCEV for this Op and Ty. 1779 FoldingSetNodeID ID; 1780 ID.AddInteger(scSignExtend); 1781 ID.AddPointer(Op); 1782 ID.AddPointer(Ty); 1783 void *IP = nullptr; 1784 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1785 1786 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1787 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1788 // It's possible the bits taken off by the truncate were all sign bits. If 1789 // so, we should be able to simplify this further. 1790 const SCEV *X = ST->getOperand(); 1791 ConstantRange CR = getSignedRange(X); 1792 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1793 unsigned NewBits = getTypeSizeInBits(Ty); 1794 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1795 CR.sextOrTrunc(NewBits))) 1796 return getTruncateOrSignExtend(X, Ty); 1797 } 1798 1799 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1800 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1801 if (SA->getNumOperands() == 2) { 1802 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1803 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1804 if (SMul && SC1) { 1805 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1806 const APInt &C1 = SC1->getAPInt(); 1807 const APInt &C2 = SC2->getAPInt(); 1808 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1809 C2.ugt(C1) && C2.isPowerOf2()) 1810 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache), 1811 getSignExtendExprCached(SMul, Ty, Cache)); 1812 } 1813 } 1814 } 1815 1816 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1817 if (SA->hasNoSignedWrap()) { 1818 // If the addition does not sign overflow then we can, by definition, 1819 // commute the sign extension with the addition operation. 1820 SmallVector<const SCEV *, 4> Ops; 1821 for (const auto *Op : SA->operands()) 1822 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache)); 1823 return getAddExpr(Ops, SCEV::FlagNSW); 1824 } 1825 } 1826 // If the input value is a chrec scev, and we can prove that the value 1827 // did not overflow the old, smaller, value, we can sign extend all of the 1828 // operands (often constants). This allows analysis of something like 1829 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1830 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1831 if (AR->isAffine()) { 1832 const SCEV *Start = AR->getStart(); 1833 const SCEV *Step = AR->getStepRecurrence(*this); 1834 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1835 const Loop *L = AR->getLoop(); 1836 1837 if (!AR->hasNoSignedWrap()) { 1838 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1839 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1840 } 1841 1842 // If we have special knowledge that this addrec won't overflow, 1843 // we don't need to do any further analysis. 1844 if (AR->hasNoSignedWrap()) 1845 return getAddRecExpr( 1846 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1847 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW); 1848 1849 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1850 // Note that this serves two purposes: It filters out loops that are 1851 // simply not analyzable, and it covers the case where this code is 1852 // being called from within backedge-taken count analysis, such that 1853 // attempting to ask for the backedge-taken count would likely result 1854 // in infinite recursion. In the later case, the analysis code will 1855 // cope with a conservative value, and it will take care to purge 1856 // that value once it has finished. 1857 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1858 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1859 // Manually compute the final value for AR, checking for 1860 // overflow. 1861 1862 // Check whether the backedge-taken count can be losslessly casted to 1863 // the addrec's type. The count is always unsigned. 1864 const SCEV *CastedMaxBECount = 1865 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1866 const SCEV *RecastedMaxBECount = 1867 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1868 if (MaxBECount == RecastedMaxBECount) { 1869 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1870 // Check whether Start+Step*MaxBECount has no signed overflow. 1871 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1872 const SCEV *SAdd = 1873 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache); 1874 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache); 1875 const SCEV *WideMaxBECount = 1876 getZeroExtendExpr(CastedMaxBECount, WideTy); 1877 const SCEV *OperandExtendedAdd = getAddExpr( 1878 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached( 1879 Step, WideTy, Cache))); 1880 if (SAdd == OperandExtendedAdd) { 1881 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1882 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1883 // Return the expression with the addrec on the outside. 1884 return getAddRecExpr( 1885 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1886 getSignExtendExprCached(Step, Ty, Cache), L, 1887 AR->getNoWrapFlags()); 1888 } 1889 // Similar to above, only this time treat the step value as unsigned. 1890 // This covers loops that count up with an unsigned step. 1891 OperandExtendedAdd = 1892 getAddExpr(WideStart, 1893 getMulExpr(WideMaxBECount, 1894 getZeroExtendExpr(Step, WideTy))); 1895 if (SAdd == OperandExtendedAdd) { 1896 // If AR wraps around then 1897 // 1898 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1899 // => SAdd != OperandExtendedAdd 1900 // 1901 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1902 // (SAdd == OperandExtendedAdd => AR is NW) 1903 1904 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1905 1906 // Return the expression with the addrec on the outside. 1907 return getAddRecExpr( 1908 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1909 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1910 } 1911 } 1912 } 1913 1914 // Normally, in the cases we can prove no-overflow via a 1915 // backedge guarding condition, we can also compute a backedge 1916 // taken count for the loop. The exceptions are assumptions and 1917 // guards present in the loop -- SCEV is not great at exploiting 1918 // these to compute max backedge taken counts, but can still use 1919 // these to prove lack of overflow. Use this fact to avoid 1920 // doing extra work that may not pay off. 1921 1922 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1923 !AC.assumptions().empty()) { 1924 // If the backedge is guarded by a comparison with the pre-inc 1925 // value the addrec is safe. Also, if the entry is guarded by 1926 // a comparison with the start value and the backedge is 1927 // guarded by a comparison with the post-inc value, the addrec 1928 // is safe. 1929 ICmpInst::Predicate Pred; 1930 const SCEV *OverflowLimit = 1931 getSignedOverflowLimitForStep(Step, &Pred, this); 1932 if (OverflowLimit && 1933 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1934 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1935 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1936 OverflowLimit)))) { 1937 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1938 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1939 return getAddRecExpr( 1940 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1941 getSignExtendExprCached(Step, Ty, Cache), L, 1942 AR->getNoWrapFlags()); 1943 } 1944 } 1945 1946 // If Start and Step are constants, check if we can apply this 1947 // transformation: 1948 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1949 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1950 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1951 if (SC1 && SC2) { 1952 const APInt &C1 = SC1->getAPInt(); 1953 const APInt &C2 = SC2->getAPInt(); 1954 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1955 C2.isPowerOf2()) { 1956 Start = getSignExtendExprCached(Start, Ty, Cache); 1957 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1958 AR->getNoWrapFlags()); 1959 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache)); 1960 } 1961 } 1962 1963 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1964 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1965 return getAddRecExpr( 1966 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1967 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1968 } 1969 } 1970 1971 // If the input value is provably positive and we could not simplify 1972 // away the sext build a zext instead. 1973 if (isKnownNonNegative(Op)) 1974 return getZeroExtendExpr(Op, Ty); 1975 1976 // The cast wasn't folded; create an explicit cast node. 1977 // Recompute the insert position, as it may have been invalidated. 1978 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1979 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1980 Op, Ty); 1981 UniqueSCEVs.InsertNode(S, IP); 1982 return S; 1983 } 1984 1985 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1986 /// unspecified bits out to the given type. 1987 /// 1988 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1989 Type *Ty) { 1990 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1991 "This is not an extending conversion!"); 1992 assert(isSCEVable(Ty) && 1993 "This is not a conversion to a SCEVable type!"); 1994 Ty = getEffectiveSCEVType(Ty); 1995 1996 // Sign-extend negative constants. 1997 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1998 if (SC->getAPInt().isNegative()) 1999 return getSignExtendExpr(Op, Ty); 2000 2001 // Peel off a truncate cast. 2002 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2003 const SCEV *NewOp = T->getOperand(); 2004 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2005 return getAnyExtendExpr(NewOp, Ty); 2006 return getTruncateOrNoop(NewOp, Ty); 2007 } 2008 2009 // Next try a zext cast. If the cast is folded, use it. 2010 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2011 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2012 return ZExt; 2013 2014 // Next try a sext cast. If the cast is folded, use it. 2015 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2016 if (!isa<SCEVSignExtendExpr>(SExt)) 2017 return SExt; 2018 2019 // Force the cast to be folded into the operands of an addrec. 2020 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2021 SmallVector<const SCEV *, 4> Ops; 2022 for (const SCEV *Op : AR->operands()) 2023 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2024 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2025 } 2026 2027 // If the expression is obviously signed, use the sext cast value. 2028 if (isa<SCEVSMaxExpr>(Op)) 2029 return SExt; 2030 2031 // Absent any other information, use the zext cast value. 2032 return ZExt; 2033 } 2034 2035 /// Process the given Ops list, which is a list of operands to be added under 2036 /// the given scale, update the given map. This is a helper function for 2037 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2038 /// that would form an add expression like this: 2039 /// 2040 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2041 /// 2042 /// where A and B are constants, update the map with these values: 2043 /// 2044 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2045 /// 2046 /// and add 13 + A*B*29 to AccumulatedConstant. 2047 /// This will allow getAddRecExpr to produce this: 2048 /// 2049 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2050 /// 2051 /// This form often exposes folding opportunities that are hidden in 2052 /// the original operand list. 2053 /// 2054 /// Return true iff it appears that any interesting folding opportunities 2055 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2056 /// the common case where no interesting opportunities are present, and 2057 /// is also used as a check to avoid infinite recursion. 2058 /// 2059 static bool 2060 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2061 SmallVectorImpl<const SCEV *> &NewOps, 2062 APInt &AccumulatedConstant, 2063 const SCEV *const *Ops, size_t NumOperands, 2064 const APInt &Scale, 2065 ScalarEvolution &SE) { 2066 bool Interesting = false; 2067 2068 // Iterate over the add operands. They are sorted, with constants first. 2069 unsigned i = 0; 2070 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2071 ++i; 2072 // Pull a buried constant out to the outside. 2073 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2074 Interesting = true; 2075 AccumulatedConstant += Scale * C->getAPInt(); 2076 } 2077 2078 // Next comes everything else. We're especially interested in multiplies 2079 // here, but they're in the middle, so just visit the rest with one loop. 2080 for (; i != NumOperands; ++i) { 2081 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2082 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2083 APInt NewScale = 2084 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2085 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2086 // A multiplication of a constant with another add; recurse. 2087 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2088 Interesting |= 2089 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2090 Add->op_begin(), Add->getNumOperands(), 2091 NewScale, SE); 2092 } else { 2093 // A multiplication of a constant with some other value. Update 2094 // the map. 2095 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2096 const SCEV *Key = SE.getMulExpr(MulOps); 2097 auto Pair = M.insert({Key, NewScale}); 2098 if (Pair.second) { 2099 NewOps.push_back(Pair.first->first); 2100 } else { 2101 Pair.first->second += NewScale; 2102 // The map already had an entry for this value, which may indicate 2103 // a folding opportunity. 2104 Interesting = true; 2105 } 2106 } 2107 } else { 2108 // An ordinary operand. Update the map. 2109 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2110 M.insert({Ops[i], Scale}); 2111 if (Pair.second) { 2112 NewOps.push_back(Pair.first->first); 2113 } else { 2114 Pair.first->second += Scale; 2115 // The map already had an entry for this value, which may indicate 2116 // a folding opportunity. 2117 Interesting = true; 2118 } 2119 } 2120 } 2121 2122 return Interesting; 2123 } 2124 2125 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2126 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2127 // can't-overflow flags for the operation if possible. 2128 static SCEV::NoWrapFlags 2129 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2130 const SmallVectorImpl<const SCEV *> &Ops, 2131 SCEV::NoWrapFlags Flags) { 2132 using namespace std::placeholders; 2133 typedef OverflowingBinaryOperator OBO; 2134 2135 bool CanAnalyze = 2136 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2137 (void)CanAnalyze; 2138 assert(CanAnalyze && "don't call from other places!"); 2139 2140 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2141 SCEV::NoWrapFlags SignOrUnsignWrap = 2142 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2143 2144 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2145 auto IsKnownNonNegative = [&](const SCEV *S) { 2146 return SE->isKnownNonNegative(S); 2147 }; 2148 2149 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2150 Flags = 2151 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2152 2153 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2154 2155 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2156 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2157 2158 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2159 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2160 2161 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2162 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2163 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2164 Instruction::Add, C, OBO::NoSignedWrap); 2165 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2167 } 2168 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2169 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2170 Instruction::Add, C, OBO::NoUnsignedWrap); 2171 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2172 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2173 } 2174 } 2175 2176 return Flags; 2177 } 2178 2179 /// Get a canonical add expression, or something simpler if possible. 2180 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2181 SCEV::NoWrapFlags Flags, 2182 unsigned Depth) { 2183 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2184 "only nuw or nsw allowed"); 2185 assert(!Ops.empty() && "Cannot get empty add!"); 2186 if (Ops.size() == 1) return Ops[0]; 2187 #ifndef NDEBUG 2188 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2189 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2190 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2191 "SCEVAddExpr operand types don't match!"); 2192 #endif 2193 2194 // Sort by complexity, this groups all similar expression types together. 2195 GroupByComplexity(Ops, &LI); 2196 2197 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2198 2199 // If there are any constants, fold them together. 2200 unsigned Idx = 0; 2201 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2202 ++Idx; 2203 assert(Idx < Ops.size()); 2204 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2205 // We found two constants, fold them together! 2206 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2207 if (Ops.size() == 2) return Ops[0]; 2208 Ops.erase(Ops.begin()+1); // Erase the folded element 2209 LHSC = cast<SCEVConstant>(Ops[0]); 2210 } 2211 2212 // If we are left with a constant zero being added, strip it off. 2213 if (LHSC->getValue()->isZero()) { 2214 Ops.erase(Ops.begin()); 2215 --Idx; 2216 } 2217 2218 if (Ops.size() == 1) return Ops[0]; 2219 } 2220 2221 // Limit recursion calls depth 2222 if (Depth > MaxAddExprDepth) 2223 return getOrCreateAddExpr(Ops, Flags); 2224 2225 // Okay, check to see if the same value occurs in the operand list more than 2226 // once. If so, merge them together into an multiply expression. Since we 2227 // sorted the list, these values are required to be adjacent. 2228 Type *Ty = Ops[0]->getType(); 2229 bool FoundMatch = false; 2230 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2231 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2232 // Scan ahead to count how many equal operands there are. 2233 unsigned Count = 2; 2234 while (i+Count != e && Ops[i+Count] == Ops[i]) 2235 ++Count; 2236 // Merge the values into a multiply. 2237 const SCEV *Scale = getConstant(Ty, Count); 2238 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2239 if (Ops.size() == Count) 2240 return Mul; 2241 Ops[i] = Mul; 2242 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2243 --i; e -= Count - 1; 2244 FoundMatch = true; 2245 } 2246 if (FoundMatch) 2247 return getAddExpr(Ops, Flags); 2248 2249 // Check for truncates. If all the operands are truncated from the same 2250 // type, see if factoring out the truncate would permit the result to be 2251 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2252 // if the contents of the resulting outer trunc fold to something simple. 2253 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2254 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2255 Type *DstType = Trunc->getType(); 2256 Type *SrcType = Trunc->getOperand()->getType(); 2257 SmallVector<const SCEV *, 8> LargeOps; 2258 bool Ok = true; 2259 // Check all the operands to see if they can be represented in the 2260 // source type of the truncate. 2261 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2262 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2263 if (T->getOperand()->getType() != SrcType) { 2264 Ok = false; 2265 break; 2266 } 2267 LargeOps.push_back(T->getOperand()); 2268 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2269 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2270 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2271 SmallVector<const SCEV *, 8> LargeMulOps; 2272 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2273 if (const SCEVTruncateExpr *T = 2274 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2275 if (T->getOperand()->getType() != SrcType) { 2276 Ok = false; 2277 break; 2278 } 2279 LargeMulOps.push_back(T->getOperand()); 2280 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2281 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2282 } else { 2283 Ok = false; 2284 break; 2285 } 2286 } 2287 if (Ok) 2288 LargeOps.push_back(getMulExpr(LargeMulOps)); 2289 } else { 2290 Ok = false; 2291 break; 2292 } 2293 } 2294 if (Ok) { 2295 // Evaluate the expression in the larger type. 2296 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2297 // If it folds to something simple, use it. Otherwise, don't. 2298 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2299 return getTruncateExpr(Fold, DstType); 2300 } 2301 } 2302 2303 // Skip past any other cast SCEVs. 2304 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2305 ++Idx; 2306 2307 // If there are add operands they would be next. 2308 if (Idx < Ops.size()) { 2309 bool DeletedAdd = false; 2310 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2311 if (Ops.size() > AddOpsInlineThreshold || 2312 Add->getNumOperands() > AddOpsInlineThreshold) 2313 break; 2314 // If we have an add, expand the add operands onto the end of the operands 2315 // list. 2316 Ops.erase(Ops.begin()+Idx); 2317 Ops.append(Add->op_begin(), Add->op_end()); 2318 DeletedAdd = true; 2319 } 2320 2321 // If we deleted at least one add, we added operands to the end of the list, 2322 // and they are not necessarily sorted. Recurse to resort and resimplify 2323 // any operands we just acquired. 2324 if (DeletedAdd) 2325 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2326 } 2327 2328 // Skip over the add expression until we get to a multiply. 2329 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2330 ++Idx; 2331 2332 // Check to see if there are any folding opportunities present with 2333 // operands multiplied by constant values. 2334 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2335 uint64_t BitWidth = getTypeSizeInBits(Ty); 2336 DenseMap<const SCEV *, APInt> M; 2337 SmallVector<const SCEV *, 8> NewOps; 2338 APInt AccumulatedConstant(BitWidth, 0); 2339 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2340 Ops.data(), Ops.size(), 2341 APInt(BitWidth, 1), *this)) { 2342 struct APIntCompare { 2343 bool operator()(const APInt &LHS, const APInt &RHS) const { 2344 return LHS.ult(RHS); 2345 } 2346 }; 2347 2348 // Some interesting folding opportunity is present, so its worthwhile to 2349 // re-generate the operands list. Group the operands by constant scale, 2350 // to avoid multiplying by the same constant scale multiple times. 2351 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2352 for (const SCEV *NewOp : NewOps) 2353 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2354 // Re-generate the operands list. 2355 Ops.clear(); 2356 if (AccumulatedConstant != 0) 2357 Ops.push_back(getConstant(AccumulatedConstant)); 2358 for (auto &MulOp : MulOpLists) 2359 if (MulOp.first != 0) 2360 Ops.push_back(getMulExpr( 2361 getConstant(MulOp.first), 2362 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1))); 2363 if (Ops.empty()) 2364 return getZero(Ty); 2365 if (Ops.size() == 1) 2366 return Ops[0]; 2367 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2368 } 2369 } 2370 2371 // If we are adding something to a multiply expression, make sure the 2372 // something is not already an operand of the multiply. If so, merge it into 2373 // the multiply. 2374 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2375 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2376 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2377 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2378 if (isa<SCEVConstant>(MulOpSCEV)) 2379 continue; 2380 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2381 if (MulOpSCEV == Ops[AddOp]) { 2382 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2383 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2384 if (Mul->getNumOperands() != 2) { 2385 // If the multiply has more than two operands, we must get the 2386 // Y*Z term. 2387 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2388 Mul->op_begin()+MulOp); 2389 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2390 InnerMul = getMulExpr(MulOps); 2391 } 2392 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2393 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2394 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2395 if (Ops.size() == 2) return OuterMul; 2396 if (AddOp < Idx) { 2397 Ops.erase(Ops.begin()+AddOp); 2398 Ops.erase(Ops.begin()+Idx-1); 2399 } else { 2400 Ops.erase(Ops.begin()+Idx); 2401 Ops.erase(Ops.begin()+AddOp-1); 2402 } 2403 Ops.push_back(OuterMul); 2404 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2405 } 2406 2407 // Check this multiply against other multiplies being added together. 2408 for (unsigned OtherMulIdx = Idx+1; 2409 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2410 ++OtherMulIdx) { 2411 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2412 // If MulOp occurs in OtherMul, we can fold the two multiplies 2413 // together. 2414 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2415 OMulOp != e; ++OMulOp) 2416 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2417 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2418 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2419 if (Mul->getNumOperands() != 2) { 2420 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2421 Mul->op_begin()+MulOp); 2422 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2423 InnerMul1 = getMulExpr(MulOps); 2424 } 2425 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2426 if (OtherMul->getNumOperands() != 2) { 2427 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2428 OtherMul->op_begin()+OMulOp); 2429 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2430 InnerMul2 = getMulExpr(MulOps); 2431 } 2432 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2433 const SCEV *InnerMulSum = 2434 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2435 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2436 if (Ops.size() == 2) return OuterMul; 2437 Ops.erase(Ops.begin()+Idx); 2438 Ops.erase(Ops.begin()+OtherMulIdx-1); 2439 Ops.push_back(OuterMul); 2440 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2441 } 2442 } 2443 } 2444 } 2445 2446 // If there are any add recurrences in the operands list, see if any other 2447 // added values are loop invariant. If so, we can fold them into the 2448 // recurrence. 2449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2450 ++Idx; 2451 2452 // Scan over all recurrences, trying to fold loop invariants into them. 2453 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2454 // Scan all of the other operands to this add and add them to the vector if 2455 // they are loop invariant w.r.t. the recurrence. 2456 SmallVector<const SCEV *, 8> LIOps; 2457 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2458 const Loop *AddRecLoop = AddRec->getLoop(); 2459 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2460 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2461 LIOps.push_back(Ops[i]); 2462 Ops.erase(Ops.begin()+i); 2463 --i; --e; 2464 } 2465 2466 // If we found some loop invariants, fold them into the recurrence. 2467 if (!LIOps.empty()) { 2468 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2469 LIOps.push_back(AddRec->getStart()); 2470 2471 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2472 AddRec->op_end()); 2473 // This follows from the fact that the no-wrap flags on the outer add 2474 // expression are applicable on the 0th iteration, when the add recurrence 2475 // will be equal to its start value. 2476 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2477 2478 // Build the new addrec. Propagate the NUW and NSW flags if both the 2479 // outer add and the inner addrec are guaranteed to have no overflow. 2480 // Always propagate NW. 2481 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2482 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2483 2484 // If all of the other operands were loop invariant, we are done. 2485 if (Ops.size() == 1) return NewRec; 2486 2487 // Otherwise, add the folded AddRec by the non-invariant parts. 2488 for (unsigned i = 0;; ++i) 2489 if (Ops[i] == AddRec) { 2490 Ops[i] = NewRec; 2491 break; 2492 } 2493 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2494 } 2495 2496 // Okay, if there weren't any loop invariants to be folded, check to see if 2497 // there are multiple AddRec's with the same loop induction variable being 2498 // added together. If so, we can fold them. 2499 for (unsigned OtherIdx = Idx+1; 2500 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2501 ++OtherIdx) 2502 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2503 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2504 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2505 AddRec->op_end()); 2506 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2507 ++OtherIdx) 2508 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2509 if (OtherAddRec->getLoop() == AddRecLoop) { 2510 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2511 i != e; ++i) { 2512 if (i >= AddRecOps.size()) { 2513 AddRecOps.append(OtherAddRec->op_begin()+i, 2514 OtherAddRec->op_end()); 2515 break; 2516 } 2517 SmallVector<const SCEV *, 2> TwoOps = { 2518 AddRecOps[i], OtherAddRec->getOperand(i)}; 2519 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2520 } 2521 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2522 } 2523 // Step size has changed, so we cannot guarantee no self-wraparound. 2524 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2525 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2526 } 2527 2528 // Otherwise couldn't fold anything into this recurrence. Move onto the 2529 // next one. 2530 } 2531 2532 // Okay, it looks like we really DO need an add expr. Check to see if we 2533 // already have one, otherwise create a new one. 2534 return getOrCreateAddExpr(Ops, Flags); 2535 } 2536 2537 const SCEV * 2538 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2539 SCEV::NoWrapFlags Flags) { 2540 FoldingSetNodeID ID; 2541 ID.AddInteger(scAddExpr); 2542 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2543 ID.AddPointer(Ops[i]); 2544 void *IP = nullptr; 2545 SCEVAddExpr *S = 2546 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2547 if (!S) { 2548 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2549 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2550 S = new (SCEVAllocator) 2551 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2552 UniqueSCEVs.InsertNode(S, IP); 2553 } 2554 S->setNoWrapFlags(Flags); 2555 return S; 2556 } 2557 2558 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2559 uint64_t k = i*j; 2560 if (j > 1 && k / j != i) Overflow = true; 2561 return k; 2562 } 2563 2564 /// Compute the result of "n choose k", the binomial coefficient. If an 2565 /// intermediate computation overflows, Overflow will be set and the return will 2566 /// be garbage. Overflow is not cleared on absence of overflow. 2567 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2568 // We use the multiplicative formula: 2569 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2570 // At each iteration, we take the n-th term of the numeral and divide by the 2571 // (k-n)th term of the denominator. This division will always produce an 2572 // integral result, and helps reduce the chance of overflow in the 2573 // intermediate computations. However, we can still overflow even when the 2574 // final result would fit. 2575 2576 if (n == 0 || n == k) return 1; 2577 if (k > n) return 0; 2578 2579 if (k > n/2) 2580 k = n-k; 2581 2582 uint64_t r = 1; 2583 for (uint64_t i = 1; i <= k; ++i) { 2584 r = umul_ov(r, n-(i-1), Overflow); 2585 r /= i; 2586 } 2587 return r; 2588 } 2589 2590 /// Determine if any of the operands in this SCEV are a constant or if 2591 /// any of the add or multiply expressions in this SCEV contain a constant. 2592 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2593 SmallVector<const SCEV *, 4> Ops; 2594 Ops.push_back(StartExpr); 2595 while (!Ops.empty()) { 2596 const SCEV *CurrentExpr = Ops.pop_back_val(); 2597 if (isa<SCEVConstant>(*CurrentExpr)) 2598 return true; 2599 2600 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2601 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2602 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2603 } 2604 } 2605 return false; 2606 } 2607 2608 /// Get a canonical multiply expression, or something simpler if possible. 2609 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2610 SCEV::NoWrapFlags Flags) { 2611 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2612 "only nuw or nsw allowed"); 2613 assert(!Ops.empty() && "Cannot get empty mul!"); 2614 if (Ops.size() == 1) return Ops[0]; 2615 #ifndef NDEBUG 2616 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2617 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2618 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2619 "SCEVMulExpr operand types don't match!"); 2620 #endif 2621 2622 // Sort by complexity, this groups all similar expression types together. 2623 GroupByComplexity(Ops, &LI); 2624 2625 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2626 2627 // If there are any constants, fold them together. 2628 unsigned Idx = 0; 2629 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2630 2631 // C1*(C2+V) -> C1*C2 + C1*V 2632 if (Ops.size() == 2) 2633 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2634 // If any of Add's ops are Adds or Muls with a constant, 2635 // apply this transformation as well. 2636 if (Add->getNumOperands() == 2) 2637 if (containsConstantSomewhere(Add)) 2638 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2639 getMulExpr(LHSC, Add->getOperand(1))); 2640 2641 ++Idx; 2642 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2643 // We found two constants, fold them together! 2644 ConstantInt *Fold = 2645 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2646 Ops[0] = getConstant(Fold); 2647 Ops.erase(Ops.begin()+1); // Erase the folded element 2648 if (Ops.size() == 1) return Ops[0]; 2649 LHSC = cast<SCEVConstant>(Ops[0]); 2650 } 2651 2652 // If we are left with a constant one being multiplied, strip it off. 2653 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2654 Ops.erase(Ops.begin()); 2655 --Idx; 2656 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2657 // If we have a multiply of zero, it will always be zero. 2658 return Ops[0]; 2659 } else if (Ops[0]->isAllOnesValue()) { 2660 // If we have a mul by -1 of an add, try distributing the -1 among the 2661 // add operands. 2662 if (Ops.size() == 2) { 2663 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2664 SmallVector<const SCEV *, 4> NewOps; 2665 bool AnyFolded = false; 2666 for (const SCEV *AddOp : Add->operands()) { 2667 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2668 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2669 NewOps.push_back(Mul); 2670 } 2671 if (AnyFolded) 2672 return getAddExpr(NewOps); 2673 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2674 // Negation preserves a recurrence's no self-wrap property. 2675 SmallVector<const SCEV *, 4> Operands; 2676 for (const SCEV *AddRecOp : AddRec->operands()) 2677 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2678 2679 return getAddRecExpr(Operands, AddRec->getLoop(), 2680 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2681 } 2682 } 2683 } 2684 2685 if (Ops.size() == 1) 2686 return Ops[0]; 2687 } 2688 2689 // Skip over the add expression until we get to a multiply. 2690 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2691 ++Idx; 2692 2693 // If there are mul operands inline them all into this expression. 2694 if (Idx < Ops.size()) { 2695 bool DeletedMul = false; 2696 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2697 if (Ops.size() > MulOpsInlineThreshold) 2698 break; 2699 // If we have an mul, expand the mul operands onto the end of the operands 2700 // list. 2701 Ops.erase(Ops.begin()+Idx); 2702 Ops.append(Mul->op_begin(), Mul->op_end()); 2703 DeletedMul = true; 2704 } 2705 2706 // If we deleted at least one mul, we added operands to the end of the list, 2707 // and they are not necessarily sorted. Recurse to resort and resimplify 2708 // any operands we just acquired. 2709 if (DeletedMul) 2710 return getMulExpr(Ops); 2711 } 2712 2713 // If there are any add recurrences in the operands list, see if any other 2714 // added values are loop invariant. If so, we can fold them into the 2715 // recurrence. 2716 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2717 ++Idx; 2718 2719 // Scan over all recurrences, trying to fold loop invariants into them. 2720 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2721 // Scan all of the other operands to this mul and add them to the vector if 2722 // they are loop invariant w.r.t. the recurrence. 2723 SmallVector<const SCEV *, 8> LIOps; 2724 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2725 const Loop *AddRecLoop = AddRec->getLoop(); 2726 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2727 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2728 LIOps.push_back(Ops[i]); 2729 Ops.erase(Ops.begin()+i); 2730 --i; --e; 2731 } 2732 2733 // If we found some loop invariants, fold them into the recurrence. 2734 if (!LIOps.empty()) { 2735 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2736 SmallVector<const SCEV *, 4> NewOps; 2737 NewOps.reserve(AddRec->getNumOperands()); 2738 const SCEV *Scale = getMulExpr(LIOps); 2739 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2740 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2741 2742 // Build the new addrec. Propagate the NUW and NSW flags if both the 2743 // outer mul and the inner addrec are guaranteed to have no overflow. 2744 // 2745 // No self-wrap cannot be guaranteed after changing the step size, but 2746 // will be inferred if either NUW or NSW is true. 2747 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2748 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2749 2750 // If all of the other operands were loop invariant, we are done. 2751 if (Ops.size() == 1) return NewRec; 2752 2753 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2754 for (unsigned i = 0;; ++i) 2755 if (Ops[i] == AddRec) { 2756 Ops[i] = NewRec; 2757 break; 2758 } 2759 return getMulExpr(Ops); 2760 } 2761 2762 // Okay, if there weren't any loop invariants to be folded, check to see if 2763 // there are multiple AddRec's with the same loop induction variable being 2764 // multiplied together. If so, we can fold them. 2765 2766 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2767 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2768 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2769 // ]]],+,...up to x=2n}. 2770 // Note that the arguments to choose() are always integers with values 2771 // known at compile time, never SCEV objects. 2772 // 2773 // The implementation avoids pointless extra computations when the two 2774 // addrec's are of different length (mathematically, it's equivalent to 2775 // an infinite stream of zeros on the right). 2776 bool OpsModified = false; 2777 for (unsigned OtherIdx = Idx+1; 2778 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2779 ++OtherIdx) { 2780 const SCEVAddRecExpr *OtherAddRec = 2781 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2782 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2783 continue; 2784 2785 bool Overflow = false; 2786 Type *Ty = AddRec->getType(); 2787 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2788 SmallVector<const SCEV*, 7> AddRecOps; 2789 for (int x = 0, xe = AddRec->getNumOperands() + 2790 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2791 const SCEV *Term = getZero(Ty); 2792 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2793 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2794 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2795 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2796 z < ze && !Overflow; ++z) { 2797 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2798 uint64_t Coeff; 2799 if (LargerThan64Bits) 2800 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2801 else 2802 Coeff = Coeff1*Coeff2; 2803 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2804 const SCEV *Term1 = AddRec->getOperand(y-z); 2805 const SCEV *Term2 = OtherAddRec->getOperand(z); 2806 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2807 } 2808 } 2809 AddRecOps.push_back(Term); 2810 } 2811 if (!Overflow) { 2812 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2813 SCEV::FlagAnyWrap); 2814 if (Ops.size() == 2) return NewAddRec; 2815 Ops[Idx] = NewAddRec; 2816 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2817 OpsModified = true; 2818 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2819 if (!AddRec) 2820 break; 2821 } 2822 } 2823 if (OpsModified) 2824 return getMulExpr(Ops); 2825 2826 // Otherwise couldn't fold anything into this recurrence. Move onto the 2827 // next one. 2828 } 2829 2830 // Okay, it looks like we really DO need an mul expr. Check to see if we 2831 // already have one, otherwise create a new one. 2832 FoldingSetNodeID ID; 2833 ID.AddInteger(scMulExpr); 2834 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2835 ID.AddPointer(Ops[i]); 2836 void *IP = nullptr; 2837 SCEVMulExpr *S = 2838 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2839 if (!S) { 2840 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2841 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2842 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2843 O, Ops.size()); 2844 UniqueSCEVs.InsertNode(S, IP); 2845 } 2846 S->setNoWrapFlags(Flags); 2847 return S; 2848 } 2849 2850 /// Get a canonical unsigned division expression, or something simpler if 2851 /// possible. 2852 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2853 const SCEV *RHS) { 2854 assert(getEffectiveSCEVType(LHS->getType()) == 2855 getEffectiveSCEVType(RHS->getType()) && 2856 "SCEVUDivExpr operand types don't match!"); 2857 2858 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2859 if (RHSC->getValue()->equalsInt(1)) 2860 return LHS; // X udiv 1 --> x 2861 // If the denominator is zero, the result of the udiv is undefined. Don't 2862 // try to analyze it, because the resolution chosen here may differ from 2863 // the resolution chosen in other parts of the compiler. 2864 if (!RHSC->getValue()->isZero()) { 2865 // Determine if the division can be folded into the operands of 2866 // its operands. 2867 // TODO: Generalize this to non-constants by using known-bits information. 2868 Type *Ty = LHS->getType(); 2869 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2870 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2871 // For non-power-of-two values, effectively round the value up to the 2872 // nearest power of two. 2873 if (!RHSC->getAPInt().isPowerOf2()) 2874 ++MaxShiftAmt; 2875 IntegerType *ExtTy = 2876 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2877 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2878 if (const SCEVConstant *Step = 2879 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2880 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2881 const APInt &StepInt = Step->getAPInt(); 2882 const APInt &DivInt = RHSC->getAPInt(); 2883 if (!StepInt.urem(DivInt) && 2884 getZeroExtendExpr(AR, ExtTy) == 2885 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2886 getZeroExtendExpr(Step, ExtTy), 2887 AR->getLoop(), SCEV::FlagAnyWrap)) { 2888 SmallVector<const SCEV *, 4> Operands; 2889 for (const SCEV *Op : AR->operands()) 2890 Operands.push_back(getUDivExpr(Op, RHS)); 2891 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2892 } 2893 /// Get a canonical UDivExpr for a recurrence. 2894 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2895 // We can currently only fold X%N if X is constant. 2896 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2897 if (StartC && !DivInt.urem(StepInt) && 2898 getZeroExtendExpr(AR, ExtTy) == 2899 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2900 getZeroExtendExpr(Step, ExtTy), 2901 AR->getLoop(), SCEV::FlagAnyWrap)) { 2902 const APInt &StartInt = StartC->getAPInt(); 2903 const APInt &StartRem = StartInt.urem(StepInt); 2904 if (StartRem != 0) 2905 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2906 AR->getLoop(), SCEV::FlagNW); 2907 } 2908 } 2909 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2910 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2911 SmallVector<const SCEV *, 4> Operands; 2912 for (const SCEV *Op : M->operands()) 2913 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2914 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2915 // Find an operand that's safely divisible. 2916 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2917 const SCEV *Op = M->getOperand(i); 2918 const SCEV *Div = getUDivExpr(Op, RHSC); 2919 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2920 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2921 M->op_end()); 2922 Operands[i] = Div; 2923 return getMulExpr(Operands); 2924 } 2925 } 2926 } 2927 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2928 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2929 SmallVector<const SCEV *, 4> Operands; 2930 for (const SCEV *Op : A->operands()) 2931 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2932 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2933 Operands.clear(); 2934 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2935 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2936 if (isa<SCEVUDivExpr>(Op) || 2937 getMulExpr(Op, RHS) != A->getOperand(i)) 2938 break; 2939 Operands.push_back(Op); 2940 } 2941 if (Operands.size() == A->getNumOperands()) 2942 return getAddExpr(Operands); 2943 } 2944 } 2945 2946 // Fold if both operands are constant. 2947 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2948 Constant *LHSCV = LHSC->getValue(); 2949 Constant *RHSCV = RHSC->getValue(); 2950 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2951 RHSCV))); 2952 } 2953 } 2954 } 2955 2956 FoldingSetNodeID ID; 2957 ID.AddInteger(scUDivExpr); 2958 ID.AddPointer(LHS); 2959 ID.AddPointer(RHS); 2960 void *IP = nullptr; 2961 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2962 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2963 LHS, RHS); 2964 UniqueSCEVs.InsertNode(S, IP); 2965 return S; 2966 } 2967 2968 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2969 APInt A = C1->getAPInt().abs(); 2970 APInt B = C2->getAPInt().abs(); 2971 uint32_t ABW = A.getBitWidth(); 2972 uint32_t BBW = B.getBitWidth(); 2973 2974 if (ABW > BBW) 2975 B = B.zext(ABW); 2976 else if (ABW < BBW) 2977 A = A.zext(BBW); 2978 2979 return APIntOps::GreatestCommonDivisor(A, B); 2980 } 2981 2982 /// Get a canonical unsigned division expression, or something simpler if 2983 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2984 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2985 /// it's not exact because the udiv may be clearing bits. 2986 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2987 const SCEV *RHS) { 2988 // TODO: we could try to find factors in all sorts of things, but for now we 2989 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2990 // end of this file for inspiration. 2991 2992 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2993 if (!Mul || !Mul->hasNoUnsignedWrap()) 2994 return getUDivExpr(LHS, RHS); 2995 2996 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2997 // If the mulexpr multiplies by a constant, then that constant must be the 2998 // first element of the mulexpr. 2999 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3000 if (LHSCst == RHSCst) { 3001 SmallVector<const SCEV *, 2> Operands; 3002 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3003 return getMulExpr(Operands); 3004 } 3005 3006 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3007 // that there's a factor provided by one of the other terms. We need to 3008 // check. 3009 APInt Factor = gcd(LHSCst, RHSCst); 3010 if (!Factor.isIntN(1)) { 3011 LHSCst = 3012 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3013 RHSCst = 3014 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3015 SmallVector<const SCEV *, 2> Operands; 3016 Operands.push_back(LHSCst); 3017 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3018 LHS = getMulExpr(Operands); 3019 RHS = RHSCst; 3020 Mul = dyn_cast<SCEVMulExpr>(LHS); 3021 if (!Mul) 3022 return getUDivExactExpr(LHS, RHS); 3023 } 3024 } 3025 } 3026 3027 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3028 if (Mul->getOperand(i) == RHS) { 3029 SmallVector<const SCEV *, 2> Operands; 3030 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3031 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3032 return getMulExpr(Operands); 3033 } 3034 } 3035 3036 return getUDivExpr(LHS, RHS); 3037 } 3038 3039 /// Get an add recurrence expression for the specified loop. Simplify the 3040 /// expression as much as possible. 3041 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3042 const Loop *L, 3043 SCEV::NoWrapFlags Flags) { 3044 SmallVector<const SCEV *, 4> Operands; 3045 Operands.push_back(Start); 3046 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3047 if (StepChrec->getLoop() == L) { 3048 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3049 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3050 } 3051 3052 Operands.push_back(Step); 3053 return getAddRecExpr(Operands, L, Flags); 3054 } 3055 3056 /// Get an add recurrence expression for the specified loop. Simplify the 3057 /// expression as much as possible. 3058 const SCEV * 3059 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3060 const Loop *L, SCEV::NoWrapFlags Flags) { 3061 if (Operands.size() == 1) return Operands[0]; 3062 #ifndef NDEBUG 3063 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3064 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3065 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3066 "SCEVAddRecExpr operand types don't match!"); 3067 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3068 assert(isLoopInvariant(Operands[i], L) && 3069 "SCEVAddRecExpr operand is not loop-invariant!"); 3070 #endif 3071 3072 if (Operands.back()->isZero()) { 3073 Operands.pop_back(); 3074 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3075 } 3076 3077 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3078 // use that information to infer NUW and NSW flags. However, computing a 3079 // BE count requires calling getAddRecExpr, so we may not yet have a 3080 // meaningful BE count at this point (and if we don't, we'd be stuck 3081 // with a SCEVCouldNotCompute as the cached BE count). 3082 3083 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3084 3085 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3086 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3087 const Loop *NestedLoop = NestedAR->getLoop(); 3088 if (L->contains(NestedLoop) 3089 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3090 : (!NestedLoop->contains(L) && 3091 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3092 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3093 NestedAR->op_end()); 3094 Operands[0] = NestedAR->getStart(); 3095 // AddRecs require their operands be loop-invariant with respect to their 3096 // loops. Don't perform this transformation if it would break this 3097 // requirement. 3098 bool AllInvariant = all_of( 3099 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3100 3101 if (AllInvariant) { 3102 // Create a recurrence for the outer loop with the same step size. 3103 // 3104 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3105 // inner recurrence has the same property. 3106 SCEV::NoWrapFlags OuterFlags = 3107 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3108 3109 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3110 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3111 return isLoopInvariant(Op, NestedLoop); 3112 }); 3113 3114 if (AllInvariant) { 3115 // Ok, both add recurrences are valid after the transformation. 3116 // 3117 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3118 // the outer recurrence has the same property. 3119 SCEV::NoWrapFlags InnerFlags = 3120 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3121 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3122 } 3123 } 3124 // Reset Operands to its original state. 3125 Operands[0] = NestedAR; 3126 } 3127 } 3128 3129 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3130 // already have one, otherwise create a new one. 3131 FoldingSetNodeID ID; 3132 ID.AddInteger(scAddRecExpr); 3133 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3134 ID.AddPointer(Operands[i]); 3135 ID.AddPointer(L); 3136 void *IP = nullptr; 3137 SCEVAddRecExpr *S = 3138 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3139 if (!S) { 3140 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3141 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3142 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3143 O, Operands.size(), L); 3144 UniqueSCEVs.InsertNode(S, IP); 3145 } 3146 S->setNoWrapFlags(Flags); 3147 return S; 3148 } 3149 3150 const SCEV * 3151 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3152 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3153 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3154 // getSCEV(Base)->getType() has the same address space as Base->getType() 3155 // because SCEV::getType() preserves the address space. 3156 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3157 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3158 // instruction to its SCEV, because the Instruction may be guarded by control 3159 // flow and the no-overflow bits may not be valid for the expression in any 3160 // context. This can be fixed similarly to how these flags are handled for 3161 // adds. 3162 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3163 : SCEV::FlagAnyWrap; 3164 3165 const SCEV *TotalOffset = getZero(IntPtrTy); 3166 // The array size is unimportant. The first thing we do on CurTy is getting 3167 // its element type. 3168 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3169 for (const SCEV *IndexExpr : IndexExprs) { 3170 // Compute the (potentially symbolic) offset in bytes for this index. 3171 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3172 // For a struct, add the member offset. 3173 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3174 unsigned FieldNo = Index->getZExtValue(); 3175 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3176 3177 // Add the field offset to the running total offset. 3178 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3179 3180 // Update CurTy to the type of the field at Index. 3181 CurTy = STy->getTypeAtIndex(Index); 3182 } else { 3183 // Update CurTy to its element type. 3184 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3185 // For an array, add the element offset, explicitly scaled. 3186 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3187 // Getelementptr indices are signed. 3188 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3189 3190 // Multiply the index by the element size to compute the element offset. 3191 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3192 3193 // Add the element offset to the running total offset. 3194 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3195 } 3196 } 3197 3198 // Add the total offset from all the GEP indices to the base. 3199 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3200 } 3201 3202 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3203 const SCEV *RHS) { 3204 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3205 return getSMaxExpr(Ops); 3206 } 3207 3208 const SCEV * 3209 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3210 assert(!Ops.empty() && "Cannot get empty smax!"); 3211 if (Ops.size() == 1) return Ops[0]; 3212 #ifndef NDEBUG 3213 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3214 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3215 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3216 "SCEVSMaxExpr operand types don't match!"); 3217 #endif 3218 3219 // Sort by complexity, this groups all similar expression types together. 3220 GroupByComplexity(Ops, &LI); 3221 3222 // If there are any constants, fold them together. 3223 unsigned Idx = 0; 3224 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3225 ++Idx; 3226 assert(Idx < Ops.size()); 3227 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3228 // We found two constants, fold them together! 3229 ConstantInt *Fold = ConstantInt::get( 3230 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3231 Ops[0] = getConstant(Fold); 3232 Ops.erase(Ops.begin()+1); // Erase the folded element 3233 if (Ops.size() == 1) return Ops[0]; 3234 LHSC = cast<SCEVConstant>(Ops[0]); 3235 } 3236 3237 // If we are left with a constant minimum-int, strip it off. 3238 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3239 Ops.erase(Ops.begin()); 3240 --Idx; 3241 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3242 // If we have an smax with a constant maximum-int, it will always be 3243 // maximum-int. 3244 return Ops[0]; 3245 } 3246 3247 if (Ops.size() == 1) return Ops[0]; 3248 } 3249 3250 // Find the first SMax 3251 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3252 ++Idx; 3253 3254 // Check to see if one of the operands is an SMax. If so, expand its operands 3255 // onto our operand list, and recurse to simplify. 3256 if (Idx < Ops.size()) { 3257 bool DeletedSMax = false; 3258 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3259 Ops.erase(Ops.begin()+Idx); 3260 Ops.append(SMax->op_begin(), SMax->op_end()); 3261 DeletedSMax = true; 3262 } 3263 3264 if (DeletedSMax) 3265 return getSMaxExpr(Ops); 3266 } 3267 3268 // Okay, check to see if the same value occurs in the operand list twice. If 3269 // so, delete one. Since we sorted the list, these values are required to 3270 // be adjacent. 3271 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3272 // X smax Y smax Y --> X smax Y 3273 // X smax Y --> X, if X is always greater than Y 3274 if (Ops[i] == Ops[i+1] || 3275 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3276 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3277 --i; --e; 3278 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3279 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3280 --i; --e; 3281 } 3282 3283 if (Ops.size() == 1) return Ops[0]; 3284 3285 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3286 3287 // Okay, it looks like we really DO need an smax expr. Check to see if we 3288 // already have one, otherwise create a new one. 3289 FoldingSetNodeID ID; 3290 ID.AddInteger(scSMaxExpr); 3291 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3292 ID.AddPointer(Ops[i]); 3293 void *IP = nullptr; 3294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3295 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3296 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3297 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3298 O, Ops.size()); 3299 UniqueSCEVs.InsertNode(S, IP); 3300 return S; 3301 } 3302 3303 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3304 const SCEV *RHS) { 3305 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3306 return getUMaxExpr(Ops); 3307 } 3308 3309 const SCEV * 3310 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3311 assert(!Ops.empty() && "Cannot get empty umax!"); 3312 if (Ops.size() == 1) return Ops[0]; 3313 #ifndef NDEBUG 3314 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3315 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3316 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3317 "SCEVUMaxExpr operand types don't match!"); 3318 #endif 3319 3320 // Sort by complexity, this groups all similar expression types together. 3321 GroupByComplexity(Ops, &LI); 3322 3323 // If there are any constants, fold them together. 3324 unsigned Idx = 0; 3325 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3326 ++Idx; 3327 assert(Idx < Ops.size()); 3328 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3329 // We found two constants, fold them together! 3330 ConstantInt *Fold = ConstantInt::get( 3331 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3332 Ops[0] = getConstant(Fold); 3333 Ops.erase(Ops.begin()+1); // Erase the folded element 3334 if (Ops.size() == 1) return Ops[0]; 3335 LHSC = cast<SCEVConstant>(Ops[0]); 3336 } 3337 3338 // If we are left with a constant minimum-int, strip it off. 3339 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3340 Ops.erase(Ops.begin()); 3341 --Idx; 3342 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3343 // If we have an umax with a constant maximum-int, it will always be 3344 // maximum-int. 3345 return Ops[0]; 3346 } 3347 3348 if (Ops.size() == 1) return Ops[0]; 3349 } 3350 3351 // Find the first UMax 3352 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3353 ++Idx; 3354 3355 // Check to see if one of the operands is a UMax. If so, expand its operands 3356 // onto our operand list, and recurse to simplify. 3357 if (Idx < Ops.size()) { 3358 bool DeletedUMax = false; 3359 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3360 Ops.erase(Ops.begin()+Idx); 3361 Ops.append(UMax->op_begin(), UMax->op_end()); 3362 DeletedUMax = true; 3363 } 3364 3365 if (DeletedUMax) 3366 return getUMaxExpr(Ops); 3367 } 3368 3369 // Okay, check to see if the same value occurs in the operand list twice. If 3370 // so, delete one. Since we sorted the list, these values are required to 3371 // be adjacent. 3372 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3373 // X umax Y umax Y --> X umax Y 3374 // X umax Y --> X, if X is always greater than Y 3375 if (Ops[i] == Ops[i+1] || 3376 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3377 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3378 --i; --e; 3379 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3380 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3381 --i; --e; 3382 } 3383 3384 if (Ops.size() == 1) return Ops[0]; 3385 3386 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3387 3388 // Okay, it looks like we really DO need a umax expr. Check to see if we 3389 // already have one, otherwise create a new one. 3390 FoldingSetNodeID ID; 3391 ID.AddInteger(scUMaxExpr); 3392 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3393 ID.AddPointer(Ops[i]); 3394 void *IP = nullptr; 3395 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3396 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3397 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3398 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3399 O, Ops.size()); 3400 UniqueSCEVs.InsertNode(S, IP); 3401 return S; 3402 } 3403 3404 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3405 const SCEV *RHS) { 3406 // ~smax(~x, ~y) == smin(x, y). 3407 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3408 } 3409 3410 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3411 const SCEV *RHS) { 3412 // ~umax(~x, ~y) == umin(x, y) 3413 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3414 } 3415 3416 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3417 // We can bypass creating a target-independent 3418 // constant expression and then folding it back into a ConstantInt. 3419 // This is just a compile-time optimization. 3420 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3421 } 3422 3423 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3424 StructType *STy, 3425 unsigned FieldNo) { 3426 // We can bypass creating a target-independent 3427 // constant expression and then folding it back into a ConstantInt. 3428 // This is just a compile-time optimization. 3429 return getConstant( 3430 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3431 } 3432 3433 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3434 // Don't attempt to do anything other than create a SCEVUnknown object 3435 // here. createSCEV only calls getUnknown after checking for all other 3436 // interesting possibilities, and any other code that calls getUnknown 3437 // is doing so in order to hide a value from SCEV canonicalization. 3438 3439 FoldingSetNodeID ID; 3440 ID.AddInteger(scUnknown); 3441 ID.AddPointer(V); 3442 void *IP = nullptr; 3443 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3444 assert(cast<SCEVUnknown>(S)->getValue() == V && 3445 "Stale SCEVUnknown in uniquing map!"); 3446 return S; 3447 } 3448 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3449 FirstUnknown); 3450 FirstUnknown = cast<SCEVUnknown>(S); 3451 UniqueSCEVs.InsertNode(S, IP); 3452 return S; 3453 } 3454 3455 //===----------------------------------------------------------------------===// 3456 // Basic SCEV Analysis and PHI Idiom Recognition Code 3457 // 3458 3459 /// Test if values of the given type are analyzable within the SCEV 3460 /// framework. This primarily includes integer types, and it can optionally 3461 /// include pointer types if the ScalarEvolution class has access to 3462 /// target-specific information. 3463 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3464 // Integers and pointers are always SCEVable. 3465 return Ty->isIntegerTy() || Ty->isPointerTy(); 3466 } 3467 3468 /// Return the size in bits of the specified type, for which isSCEVable must 3469 /// return true. 3470 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3471 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3472 return getDataLayout().getTypeSizeInBits(Ty); 3473 } 3474 3475 /// Return a type with the same bitwidth as the given type and which represents 3476 /// how SCEV will treat the given type, for which isSCEVable must return 3477 /// true. For pointer types, this is the pointer-sized integer type. 3478 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3479 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3480 3481 if (Ty->isIntegerTy()) 3482 return Ty; 3483 3484 // The only other support type is pointer. 3485 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3486 return getDataLayout().getIntPtrType(Ty); 3487 } 3488 3489 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3490 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3491 } 3492 3493 const SCEV *ScalarEvolution::getCouldNotCompute() { 3494 return CouldNotCompute.get(); 3495 } 3496 3497 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3498 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3499 auto *SU = dyn_cast<SCEVUnknown>(S); 3500 return SU && SU->getValue() == nullptr; 3501 }); 3502 3503 return !ContainsNulls; 3504 } 3505 3506 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3507 HasRecMapType::iterator I = HasRecMap.find(S); 3508 if (I != HasRecMap.end()) 3509 return I->second; 3510 3511 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3512 HasRecMap.insert({S, FoundAddRec}); 3513 return FoundAddRec; 3514 } 3515 3516 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3517 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3518 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3519 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3520 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3521 if (!Add) 3522 return {S, nullptr}; 3523 3524 if (Add->getNumOperands() != 2) 3525 return {S, nullptr}; 3526 3527 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3528 if (!ConstOp) 3529 return {S, nullptr}; 3530 3531 return {Add->getOperand(1), ConstOp->getValue()}; 3532 } 3533 3534 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3535 /// by the value and offset from any ValueOffsetPair in the set. 3536 SetVector<ScalarEvolution::ValueOffsetPair> * 3537 ScalarEvolution::getSCEVValues(const SCEV *S) { 3538 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3539 if (SI == ExprValueMap.end()) 3540 return nullptr; 3541 #ifndef NDEBUG 3542 if (VerifySCEVMap) { 3543 // Check there is no dangling Value in the set returned. 3544 for (const auto &VE : SI->second) 3545 assert(ValueExprMap.count(VE.first)); 3546 } 3547 #endif 3548 return &SI->second; 3549 } 3550 3551 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3552 /// cannot be used separately. eraseValueFromMap should be used to remove 3553 /// V from ValueExprMap and ExprValueMap at the same time. 3554 void ScalarEvolution::eraseValueFromMap(Value *V) { 3555 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3556 if (I != ValueExprMap.end()) { 3557 const SCEV *S = I->second; 3558 // Remove {V, 0} from the set of ExprValueMap[S] 3559 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3560 SV->remove({V, nullptr}); 3561 3562 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3563 const SCEV *Stripped; 3564 ConstantInt *Offset; 3565 std::tie(Stripped, Offset) = splitAddExpr(S); 3566 if (Offset != nullptr) { 3567 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3568 SV->remove({V, Offset}); 3569 } 3570 ValueExprMap.erase(V); 3571 } 3572 } 3573 3574 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3575 /// create a new one. 3576 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3577 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3578 3579 const SCEV *S = getExistingSCEV(V); 3580 if (S == nullptr) { 3581 S = createSCEV(V); 3582 // During PHI resolution, it is possible to create two SCEVs for the same 3583 // V, so it is needed to double check whether V->S is inserted into 3584 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3585 std::pair<ValueExprMapType::iterator, bool> Pair = 3586 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3587 if (Pair.second) { 3588 ExprValueMap[S].insert({V, nullptr}); 3589 3590 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3591 // ExprValueMap. 3592 const SCEV *Stripped = S; 3593 ConstantInt *Offset = nullptr; 3594 std::tie(Stripped, Offset) = splitAddExpr(S); 3595 // If stripped is SCEVUnknown, don't bother to save 3596 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3597 // increase the complexity of the expansion code. 3598 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3599 // because it may generate add/sub instead of GEP in SCEV expansion. 3600 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3601 !isa<GetElementPtrInst>(V)) 3602 ExprValueMap[Stripped].insert({V, Offset}); 3603 } 3604 } 3605 return S; 3606 } 3607 3608 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3609 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3610 3611 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3612 if (I != ValueExprMap.end()) { 3613 const SCEV *S = I->second; 3614 if (checkValidity(S)) 3615 return S; 3616 eraseValueFromMap(V); 3617 forgetMemoizedResults(S); 3618 } 3619 return nullptr; 3620 } 3621 3622 /// Return a SCEV corresponding to -V = -1*V 3623 /// 3624 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3625 SCEV::NoWrapFlags Flags) { 3626 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3627 return getConstant( 3628 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3629 3630 Type *Ty = V->getType(); 3631 Ty = getEffectiveSCEVType(Ty); 3632 return getMulExpr( 3633 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3634 } 3635 3636 /// Return a SCEV corresponding to ~V = -1-V 3637 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3638 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3639 return getConstant( 3640 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3641 3642 Type *Ty = V->getType(); 3643 Ty = getEffectiveSCEVType(Ty); 3644 const SCEV *AllOnes = 3645 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3646 return getMinusSCEV(AllOnes, V); 3647 } 3648 3649 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3650 SCEV::NoWrapFlags Flags) { 3651 // Fast path: X - X --> 0. 3652 if (LHS == RHS) 3653 return getZero(LHS->getType()); 3654 3655 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3656 // makes it so that we cannot make much use of NUW. 3657 auto AddFlags = SCEV::FlagAnyWrap; 3658 const bool RHSIsNotMinSigned = 3659 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3660 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3661 // Let M be the minimum representable signed value. Then (-1)*RHS 3662 // signed-wraps if and only if RHS is M. That can happen even for 3663 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3664 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3665 // (-1)*RHS, we need to prove that RHS != M. 3666 // 3667 // If LHS is non-negative and we know that LHS - RHS does not 3668 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3669 // either by proving that RHS > M or that LHS >= 0. 3670 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3671 AddFlags = SCEV::FlagNSW; 3672 } 3673 } 3674 3675 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3676 // RHS is NSW and LHS >= 0. 3677 // 3678 // The difficulty here is that the NSW flag may have been proven 3679 // relative to a loop that is to be found in a recurrence in LHS and 3680 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3681 // larger scope than intended. 3682 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3683 3684 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3685 } 3686 3687 const SCEV * 3688 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3689 Type *SrcTy = V->getType(); 3690 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3691 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3692 "Cannot truncate or zero extend with non-integer arguments!"); 3693 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3694 return V; // No conversion 3695 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3696 return getTruncateExpr(V, Ty); 3697 return getZeroExtendExpr(V, Ty); 3698 } 3699 3700 const SCEV * 3701 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3702 Type *Ty) { 3703 Type *SrcTy = V->getType(); 3704 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3705 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3706 "Cannot truncate or zero extend with non-integer arguments!"); 3707 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3708 return V; // No conversion 3709 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3710 return getTruncateExpr(V, Ty); 3711 return getSignExtendExpr(V, Ty); 3712 } 3713 3714 const SCEV * 3715 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3716 Type *SrcTy = V->getType(); 3717 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3718 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3719 "Cannot noop or zero extend with non-integer arguments!"); 3720 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3721 "getNoopOrZeroExtend cannot truncate!"); 3722 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3723 return V; // No conversion 3724 return getZeroExtendExpr(V, Ty); 3725 } 3726 3727 const SCEV * 3728 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3729 Type *SrcTy = V->getType(); 3730 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3731 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3732 "Cannot noop or sign extend with non-integer arguments!"); 3733 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3734 "getNoopOrSignExtend cannot truncate!"); 3735 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3736 return V; // No conversion 3737 return getSignExtendExpr(V, Ty); 3738 } 3739 3740 const SCEV * 3741 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3742 Type *SrcTy = V->getType(); 3743 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3744 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3745 "Cannot noop or any extend with non-integer arguments!"); 3746 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3747 "getNoopOrAnyExtend cannot truncate!"); 3748 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3749 return V; // No conversion 3750 return getAnyExtendExpr(V, Ty); 3751 } 3752 3753 const SCEV * 3754 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3755 Type *SrcTy = V->getType(); 3756 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3757 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3758 "Cannot truncate or noop with non-integer arguments!"); 3759 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3760 "getTruncateOrNoop cannot extend!"); 3761 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3762 return V; // No conversion 3763 return getTruncateExpr(V, Ty); 3764 } 3765 3766 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3767 const SCEV *RHS) { 3768 const SCEV *PromotedLHS = LHS; 3769 const SCEV *PromotedRHS = RHS; 3770 3771 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3772 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3773 else 3774 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3775 3776 return getUMaxExpr(PromotedLHS, PromotedRHS); 3777 } 3778 3779 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3780 const SCEV *RHS) { 3781 const SCEV *PromotedLHS = LHS; 3782 const SCEV *PromotedRHS = RHS; 3783 3784 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3785 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3786 else 3787 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3788 3789 return getUMinExpr(PromotedLHS, PromotedRHS); 3790 } 3791 3792 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3793 // A pointer operand may evaluate to a nonpointer expression, such as null. 3794 if (!V->getType()->isPointerTy()) 3795 return V; 3796 3797 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3798 return getPointerBase(Cast->getOperand()); 3799 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3800 const SCEV *PtrOp = nullptr; 3801 for (const SCEV *NAryOp : NAry->operands()) { 3802 if (NAryOp->getType()->isPointerTy()) { 3803 // Cannot find the base of an expression with multiple pointer operands. 3804 if (PtrOp) 3805 return V; 3806 PtrOp = NAryOp; 3807 } 3808 } 3809 if (!PtrOp) 3810 return V; 3811 return getPointerBase(PtrOp); 3812 } 3813 return V; 3814 } 3815 3816 /// Push users of the given Instruction onto the given Worklist. 3817 static void 3818 PushDefUseChildren(Instruction *I, 3819 SmallVectorImpl<Instruction *> &Worklist) { 3820 // Push the def-use children onto the Worklist stack. 3821 for (User *U : I->users()) 3822 Worklist.push_back(cast<Instruction>(U)); 3823 } 3824 3825 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3826 SmallVector<Instruction *, 16> Worklist; 3827 PushDefUseChildren(PN, Worklist); 3828 3829 SmallPtrSet<Instruction *, 8> Visited; 3830 Visited.insert(PN); 3831 while (!Worklist.empty()) { 3832 Instruction *I = Worklist.pop_back_val(); 3833 if (!Visited.insert(I).second) 3834 continue; 3835 3836 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3837 if (It != ValueExprMap.end()) { 3838 const SCEV *Old = It->second; 3839 3840 // Short-circuit the def-use traversal if the symbolic name 3841 // ceases to appear in expressions. 3842 if (Old != SymName && !hasOperand(Old, SymName)) 3843 continue; 3844 3845 // SCEVUnknown for a PHI either means that it has an unrecognized 3846 // structure, it's a PHI that's in the progress of being computed 3847 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3848 // additional loop trip count information isn't going to change anything. 3849 // In the second case, createNodeForPHI will perform the necessary 3850 // updates on its own when it gets to that point. In the third, we do 3851 // want to forget the SCEVUnknown. 3852 if (!isa<PHINode>(I) || 3853 !isa<SCEVUnknown>(Old) || 3854 (I != PN && Old == SymName)) { 3855 eraseValueFromMap(It->first); 3856 forgetMemoizedResults(Old); 3857 } 3858 } 3859 3860 PushDefUseChildren(I, Worklist); 3861 } 3862 } 3863 3864 namespace { 3865 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3866 public: 3867 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3868 ScalarEvolution &SE) { 3869 SCEVInitRewriter Rewriter(L, SE); 3870 const SCEV *Result = Rewriter.visit(S); 3871 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3872 } 3873 3874 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3875 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3876 3877 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3878 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3879 Valid = false; 3880 return Expr; 3881 } 3882 3883 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3884 // Only allow AddRecExprs for this loop. 3885 if (Expr->getLoop() == L) 3886 return Expr->getStart(); 3887 Valid = false; 3888 return Expr; 3889 } 3890 3891 bool isValid() { return Valid; } 3892 3893 private: 3894 const Loop *L; 3895 bool Valid; 3896 }; 3897 3898 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3899 public: 3900 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3901 ScalarEvolution &SE) { 3902 SCEVShiftRewriter Rewriter(L, SE); 3903 const SCEV *Result = Rewriter.visit(S); 3904 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3905 } 3906 3907 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3908 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3909 3910 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3911 // Only allow AddRecExprs for this loop. 3912 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3913 Valid = false; 3914 return Expr; 3915 } 3916 3917 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3918 if (Expr->getLoop() == L && Expr->isAffine()) 3919 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3920 Valid = false; 3921 return Expr; 3922 } 3923 bool isValid() { return Valid; } 3924 3925 private: 3926 const Loop *L; 3927 bool Valid; 3928 }; 3929 } // end anonymous namespace 3930 3931 SCEV::NoWrapFlags 3932 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3933 if (!AR->isAffine()) 3934 return SCEV::FlagAnyWrap; 3935 3936 typedef OverflowingBinaryOperator OBO; 3937 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3938 3939 if (!AR->hasNoSignedWrap()) { 3940 ConstantRange AddRecRange = getSignedRange(AR); 3941 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3942 3943 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3944 Instruction::Add, IncRange, OBO::NoSignedWrap); 3945 if (NSWRegion.contains(AddRecRange)) 3946 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3947 } 3948 3949 if (!AR->hasNoUnsignedWrap()) { 3950 ConstantRange AddRecRange = getUnsignedRange(AR); 3951 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3952 3953 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3954 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3955 if (NUWRegion.contains(AddRecRange)) 3956 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3957 } 3958 3959 return Result; 3960 } 3961 3962 namespace { 3963 /// Represents an abstract binary operation. This may exist as a 3964 /// normal instruction or constant expression, or may have been 3965 /// derived from an expression tree. 3966 struct BinaryOp { 3967 unsigned Opcode; 3968 Value *LHS; 3969 Value *RHS; 3970 bool IsNSW; 3971 bool IsNUW; 3972 3973 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3974 /// constant expression. 3975 Operator *Op; 3976 3977 explicit BinaryOp(Operator *Op) 3978 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3979 IsNSW(false), IsNUW(false), Op(Op) { 3980 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3981 IsNSW = OBO->hasNoSignedWrap(); 3982 IsNUW = OBO->hasNoUnsignedWrap(); 3983 } 3984 } 3985 3986 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3987 bool IsNUW = false) 3988 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3989 Op(nullptr) {} 3990 }; 3991 } 3992 3993 3994 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3995 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3996 auto *Op = dyn_cast<Operator>(V); 3997 if (!Op) 3998 return None; 3999 4000 // Implementation detail: all the cleverness here should happen without 4001 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4002 // SCEV expressions when possible, and we should not break that. 4003 4004 switch (Op->getOpcode()) { 4005 case Instruction::Add: 4006 case Instruction::Sub: 4007 case Instruction::Mul: 4008 case Instruction::UDiv: 4009 case Instruction::And: 4010 case Instruction::Or: 4011 case Instruction::AShr: 4012 case Instruction::Shl: 4013 return BinaryOp(Op); 4014 4015 case Instruction::Xor: 4016 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4017 // If the RHS of the xor is a signmask, then this is just an add. 4018 // Instcombine turns add of signmask into xor as a strength reduction step. 4019 if (RHSC->getValue().isSignMask()) 4020 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4021 return BinaryOp(Op); 4022 4023 case Instruction::LShr: 4024 // Turn logical shift right of a constant into a unsigned divide. 4025 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4026 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4027 4028 // If the shift count is not less than the bitwidth, the result of 4029 // the shift is undefined. Don't try to analyze it, because the 4030 // resolution chosen here may differ from the resolution chosen in 4031 // other parts of the compiler. 4032 if (SA->getValue().ult(BitWidth)) { 4033 Constant *X = 4034 ConstantInt::get(SA->getContext(), 4035 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4036 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4037 } 4038 } 4039 return BinaryOp(Op); 4040 4041 case Instruction::ExtractValue: { 4042 auto *EVI = cast<ExtractValueInst>(Op); 4043 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4044 break; 4045 4046 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4047 if (!CI) 4048 break; 4049 4050 if (auto *F = CI->getCalledFunction()) 4051 switch (F->getIntrinsicID()) { 4052 case Intrinsic::sadd_with_overflow: 4053 case Intrinsic::uadd_with_overflow: { 4054 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4055 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4056 CI->getArgOperand(1)); 4057 4058 // Now that we know that all uses of the arithmetic-result component of 4059 // CI are guarded by the overflow check, we can go ahead and pretend 4060 // that the arithmetic is non-overflowing. 4061 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4062 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4063 CI->getArgOperand(1), /* IsNSW = */ true, 4064 /* IsNUW = */ false); 4065 else 4066 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4067 CI->getArgOperand(1), /* IsNSW = */ false, 4068 /* IsNUW*/ true); 4069 } 4070 4071 case Intrinsic::ssub_with_overflow: 4072 case Intrinsic::usub_with_overflow: 4073 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4074 CI->getArgOperand(1)); 4075 4076 case Intrinsic::smul_with_overflow: 4077 case Intrinsic::umul_with_overflow: 4078 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4079 CI->getArgOperand(1)); 4080 default: 4081 break; 4082 } 4083 } 4084 4085 default: 4086 break; 4087 } 4088 4089 return None; 4090 } 4091 4092 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4093 const Loop *L = LI.getLoopFor(PN->getParent()); 4094 if (!L || L->getHeader() != PN->getParent()) 4095 return nullptr; 4096 4097 // The loop may have multiple entrances or multiple exits; we can analyze 4098 // this phi as an addrec if it has a unique entry value and a unique 4099 // backedge value. 4100 Value *BEValueV = nullptr, *StartValueV = nullptr; 4101 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4102 Value *V = PN->getIncomingValue(i); 4103 if (L->contains(PN->getIncomingBlock(i))) { 4104 if (!BEValueV) { 4105 BEValueV = V; 4106 } else if (BEValueV != V) { 4107 BEValueV = nullptr; 4108 break; 4109 } 4110 } else if (!StartValueV) { 4111 StartValueV = V; 4112 } else if (StartValueV != V) { 4113 StartValueV = nullptr; 4114 break; 4115 } 4116 } 4117 if (BEValueV && StartValueV) { 4118 // While we are analyzing this PHI node, handle its value symbolically. 4119 const SCEV *SymbolicName = getUnknown(PN); 4120 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4121 "PHI node already processed?"); 4122 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4123 4124 // Using this symbolic name for the PHI, analyze the value coming around 4125 // the back-edge. 4126 const SCEV *BEValue = getSCEV(BEValueV); 4127 4128 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4129 // has a special value for the first iteration of the loop. 4130 4131 // If the value coming around the backedge is an add with the symbolic 4132 // value we just inserted, then we found a simple induction variable! 4133 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4134 // If there is a single occurrence of the symbolic value, replace it 4135 // with a recurrence. 4136 unsigned FoundIndex = Add->getNumOperands(); 4137 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4138 if (Add->getOperand(i) == SymbolicName) 4139 if (FoundIndex == e) { 4140 FoundIndex = i; 4141 break; 4142 } 4143 4144 if (FoundIndex != Add->getNumOperands()) { 4145 // Create an add with everything but the specified operand. 4146 SmallVector<const SCEV *, 8> Ops; 4147 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4148 if (i != FoundIndex) 4149 Ops.push_back(Add->getOperand(i)); 4150 const SCEV *Accum = getAddExpr(Ops); 4151 4152 // This is not a valid addrec if the step amount is varying each 4153 // loop iteration, but is not itself an addrec in this loop. 4154 if (isLoopInvariant(Accum, L) || 4155 (isa<SCEVAddRecExpr>(Accum) && 4156 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4157 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4158 4159 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4160 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4161 if (BO->IsNUW) 4162 Flags = setFlags(Flags, SCEV::FlagNUW); 4163 if (BO->IsNSW) 4164 Flags = setFlags(Flags, SCEV::FlagNSW); 4165 } 4166 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4167 // If the increment is an inbounds GEP, then we know the address 4168 // space cannot be wrapped around. We cannot make any guarantee 4169 // about signed or unsigned overflow because pointers are 4170 // unsigned but we may have a negative index from the base 4171 // pointer. We can guarantee that no unsigned wrap occurs if the 4172 // indices form a positive value. 4173 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4174 Flags = setFlags(Flags, SCEV::FlagNW); 4175 4176 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4177 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4178 Flags = setFlags(Flags, SCEV::FlagNUW); 4179 } 4180 4181 // We cannot transfer nuw and nsw flags from subtraction 4182 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4183 // for instance. 4184 } 4185 4186 const SCEV *StartVal = getSCEV(StartValueV); 4187 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4188 4189 // Okay, for the entire analysis of this edge we assumed the PHI 4190 // to be symbolic. We now need to go back and purge all of the 4191 // entries for the scalars that use the symbolic expression. 4192 forgetSymbolicName(PN, SymbolicName); 4193 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4194 4195 // We can add Flags to the post-inc expression only if we 4196 // know that it us *undefined behavior* for BEValueV to 4197 // overflow. 4198 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4199 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4200 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4201 4202 return PHISCEV; 4203 } 4204 } 4205 } else { 4206 // Otherwise, this could be a loop like this: 4207 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4208 // In this case, j = {1,+,1} and BEValue is j. 4209 // Because the other in-value of i (0) fits the evolution of BEValue 4210 // i really is an addrec evolution. 4211 // 4212 // We can generalize this saying that i is the shifted value of BEValue 4213 // by one iteration: 4214 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4215 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4216 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4217 if (Shifted != getCouldNotCompute() && 4218 Start != getCouldNotCompute()) { 4219 const SCEV *StartVal = getSCEV(StartValueV); 4220 if (Start == StartVal) { 4221 // Okay, for the entire analysis of this edge we assumed the PHI 4222 // to be symbolic. We now need to go back and purge all of the 4223 // entries for the scalars that use the symbolic expression. 4224 forgetSymbolicName(PN, SymbolicName); 4225 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4226 return Shifted; 4227 } 4228 } 4229 } 4230 4231 // Remove the temporary PHI node SCEV that has been inserted while intending 4232 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4233 // as it will prevent later (possibly simpler) SCEV expressions to be added 4234 // to the ValueExprMap. 4235 eraseValueFromMap(PN); 4236 } 4237 4238 return nullptr; 4239 } 4240 4241 // Checks if the SCEV S is available at BB. S is considered available at BB 4242 // if S can be materialized at BB without introducing a fault. 4243 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4244 BasicBlock *BB) { 4245 struct CheckAvailable { 4246 bool TraversalDone = false; 4247 bool Available = true; 4248 4249 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4250 BasicBlock *BB = nullptr; 4251 DominatorTree &DT; 4252 4253 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4254 : L(L), BB(BB), DT(DT) {} 4255 4256 bool setUnavailable() { 4257 TraversalDone = true; 4258 Available = false; 4259 return false; 4260 } 4261 4262 bool follow(const SCEV *S) { 4263 switch (S->getSCEVType()) { 4264 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4265 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4266 // These expressions are available if their operand(s) is/are. 4267 return true; 4268 4269 case scAddRecExpr: { 4270 // We allow add recurrences that are on the loop BB is in, or some 4271 // outer loop. This guarantees availability because the value of the 4272 // add recurrence at BB is simply the "current" value of the induction 4273 // variable. We can relax this in the future; for instance an add 4274 // recurrence on a sibling dominating loop is also available at BB. 4275 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4276 if (L && (ARLoop == L || ARLoop->contains(L))) 4277 return true; 4278 4279 return setUnavailable(); 4280 } 4281 4282 case scUnknown: { 4283 // For SCEVUnknown, we check for simple dominance. 4284 const auto *SU = cast<SCEVUnknown>(S); 4285 Value *V = SU->getValue(); 4286 4287 if (isa<Argument>(V)) 4288 return false; 4289 4290 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4291 return false; 4292 4293 return setUnavailable(); 4294 } 4295 4296 case scUDivExpr: 4297 case scCouldNotCompute: 4298 // We do not try to smart about these at all. 4299 return setUnavailable(); 4300 } 4301 llvm_unreachable("switch should be fully covered!"); 4302 } 4303 4304 bool isDone() { return TraversalDone; } 4305 }; 4306 4307 CheckAvailable CA(L, BB, DT); 4308 SCEVTraversal<CheckAvailable> ST(CA); 4309 4310 ST.visitAll(S); 4311 return CA.Available; 4312 } 4313 4314 // Try to match a control flow sequence that branches out at BI and merges back 4315 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4316 // match. 4317 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4318 Value *&C, Value *&LHS, Value *&RHS) { 4319 C = BI->getCondition(); 4320 4321 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4322 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4323 4324 if (!LeftEdge.isSingleEdge()) 4325 return false; 4326 4327 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4328 4329 Use &LeftUse = Merge->getOperandUse(0); 4330 Use &RightUse = Merge->getOperandUse(1); 4331 4332 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4333 LHS = LeftUse; 4334 RHS = RightUse; 4335 return true; 4336 } 4337 4338 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4339 LHS = RightUse; 4340 RHS = LeftUse; 4341 return true; 4342 } 4343 4344 return false; 4345 } 4346 4347 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4348 auto IsReachable = 4349 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4350 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4351 const Loop *L = LI.getLoopFor(PN->getParent()); 4352 4353 // We don't want to break LCSSA, even in a SCEV expression tree. 4354 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4355 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4356 return nullptr; 4357 4358 // Try to match 4359 // 4360 // br %cond, label %left, label %right 4361 // left: 4362 // br label %merge 4363 // right: 4364 // br label %merge 4365 // merge: 4366 // V = phi [ %x, %left ], [ %y, %right ] 4367 // 4368 // as "select %cond, %x, %y" 4369 4370 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4371 assert(IDom && "At least the entry block should dominate PN"); 4372 4373 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4374 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4375 4376 if (BI && BI->isConditional() && 4377 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4378 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4379 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4380 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4381 } 4382 4383 return nullptr; 4384 } 4385 4386 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4387 if (const SCEV *S = createAddRecFromPHI(PN)) 4388 return S; 4389 4390 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4391 return S; 4392 4393 // If the PHI has a single incoming value, follow that value, unless the 4394 // PHI's incoming blocks are in a different loop, in which case doing so 4395 // risks breaking LCSSA form. Instcombine would normally zap these, but 4396 // it doesn't have DominatorTree information, so it may miss cases. 4397 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4398 if (LI.replacementPreservesLCSSAForm(PN, V)) 4399 return getSCEV(V); 4400 4401 // If it's not a loop phi, we can't handle it yet. 4402 return getUnknown(PN); 4403 } 4404 4405 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4406 Value *Cond, 4407 Value *TrueVal, 4408 Value *FalseVal) { 4409 // Handle "constant" branch or select. This can occur for instance when a 4410 // loop pass transforms an inner loop and moves on to process the outer loop. 4411 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4412 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4413 4414 // Try to match some simple smax or umax patterns. 4415 auto *ICI = dyn_cast<ICmpInst>(Cond); 4416 if (!ICI) 4417 return getUnknown(I); 4418 4419 Value *LHS = ICI->getOperand(0); 4420 Value *RHS = ICI->getOperand(1); 4421 4422 switch (ICI->getPredicate()) { 4423 case ICmpInst::ICMP_SLT: 4424 case ICmpInst::ICMP_SLE: 4425 std::swap(LHS, RHS); 4426 LLVM_FALLTHROUGH; 4427 case ICmpInst::ICMP_SGT: 4428 case ICmpInst::ICMP_SGE: 4429 // a >s b ? a+x : b+x -> smax(a, b)+x 4430 // a >s b ? b+x : a+x -> smin(a, b)+x 4431 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4432 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4433 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4434 const SCEV *LA = getSCEV(TrueVal); 4435 const SCEV *RA = getSCEV(FalseVal); 4436 const SCEV *LDiff = getMinusSCEV(LA, LS); 4437 const SCEV *RDiff = getMinusSCEV(RA, RS); 4438 if (LDiff == RDiff) 4439 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4440 LDiff = getMinusSCEV(LA, RS); 4441 RDiff = getMinusSCEV(RA, LS); 4442 if (LDiff == RDiff) 4443 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4444 } 4445 break; 4446 case ICmpInst::ICMP_ULT: 4447 case ICmpInst::ICMP_ULE: 4448 std::swap(LHS, RHS); 4449 LLVM_FALLTHROUGH; 4450 case ICmpInst::ICMP_UGT: 4451 case ICmpInst::ICMP_UGE: 4452 // a >u b ? a+x : b+x -> umax(a, b)+x 4453 // a >u b ? b+x : a+x -> umin(a, b)+x 4454 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4455 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4456 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4457 const SCEV *LA = getSCEV(TrueVal); 4458 const SCEV *RA = getSCEV(FalseVal); 4459 const SCEV *LDiff = getMinusSCEV(LA, LS); 4460 const SCEV *RDiff = getMinusSCEV(RA, RS); 4461 if (LDiff == RDiff) 4462 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4463 LDiff = getMinusSCEV(LA, RS); 4464 RDiff = getMinusSCEV(RA, LS); 4465 if (LDiff == RDiff) 4466 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4467 } 4468 break; 4469 case ICmpInst::ICMP_NE: 4470 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4471 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4472 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4473 const SCEV *One = getOne(I->getType()); 4474 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4475 const SCEV *LA = getSCEV(TrueVal); 4476 const SCEV *RA = getSCEV(FalseVal); 4477 const SCEV *LDiff = getMinusSCEV(LA, LS); 4478 const SCEV *RDiff = getMinusSCEV(RA, One); 4479 if (LDiff == RDiff) 4480 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4481 } 4482 break; 4483 case ICmpInst::ICMP_EQ: 4484 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4485 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4486 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4487 const SCEV *One = getOne(I->getType()); 4488 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4489 const SCEV *LA = getSCEV(TrueVal); 4490 const SCEV *RA = getSCEV(FalseVal); 4491 const SCEV *LDiff = getMinusSCEV(LA, One); 4492 const SCEV *RDiff = getMinusSCEV(RA, LS); 4493 if (LDiff == RDiff) 4494 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4495 } 4496 break; 4497 default: 4498 break; 4499 } 4500 4501 return getUnknown(I); 4502 } 4503 4504 /// Expand GEP instructions into add and multiply operations. This allows them 4505 /// to be analyzed by regular SCEV code. 4506 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4507 // Don't attempt to analyze GEPs over unsized objects. 4508 if (!GEP->getSourceElementType()->isSized()) 4509 return getUnknown(GEP); 4510 4511 SmallVector<const SCEV *, 4> IndexExprs; 4512 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4513 IndexExprs.push_back(getSCEV(*Index)); 4514 return getGEPExpr(GEP, IndexExprs); 4515 } 4516 4517 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 4518 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4519 return C->getAPInt().countTrailingZeros(); 4520 4521 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4522 return std::min(GetMinTrailingZeros(T->getOperand()), 4523 (uint32_t)getTypeSizeInBits(T->getType())); 4524 4525 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4526 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4527 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4528 ? getTypeSizeInBits(E->getType()) 4529 : OpRes; 4530 } 4531 4532 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4533 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4534 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4535 ? getTypeSizeInBits(E->getType()) 4536 : OpRes; 4537 } 4538 4539 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4540 // The result is the min of all operands results. 4541 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4542 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4543 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4544 return MinOpRes; 4545 } 4546 4547 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4548 // The result is the sum of all operands results. 4549 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4550 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4551 for (unsigned i = 1, e = M->getNumOperands(); 4552 SumOpRes != BitWidth && i != e; ++i) 4553 SumOpRes = 4554 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 4555 return SumOpRes; 4556 } 4557 4558 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4559 // The result is the min of all operands results. 4560 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4561 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4562 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4563 return MinOpRes; 4564 } 4565 4566 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4567 // The result is the min of all operands results. 4568 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4569 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4570 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4571 return MinOpRes; 4572 } 4573 4574 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4575 // The result is the min of all operands results. 4576 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4577 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4578 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4579 return MinOpRes; 4580 } 4581 4582 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4583 // For a SCEVUnknown, ask ValueTracking. 4584 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4585 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4586 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4587 nullptr, &DT); 4588 return Zeros.countTrailingOnes(); 4589 } 4590 4591 // SCEVUDivExpr 4592 return 0; 4593 } 4594 4595 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4596 auto I = MinTrailingZerosCache.find(S); 4597 if (I != MinTrailingZerosCache.end()) 4598 return I->second; 4599 4600 uint32_t Result = GetMinTrailingZerosImpl(S); 4601 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 4602 assert(InsertPair.second && "Should insert a new key"); 4603 return InsertPair.first->second; 4604 } 4605 4606 /// Helper method to assign a range to V from metadata present in the IR. 4607 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4608 if (Instruction *I = dyn_cast<Instruction>(V)) 4609 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4610 return getConstantRangeFromMetadata(*MD); 4611 4612 return None; 4613 } 4614 4615 /// Determine the range for a particular SCEV. If SignHint is 4616 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4617 /// with a "cleaner" unsigned (resp. signed) representation. 4618 ConstantRange 4619 ScalarEvolution::getRange(const SCEV *S, 4620 ScalarEvolution::RangeSignHint SignHint) { 4621 DenseMap<const SCEV *, ConstantRange> &Cache = 4622 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4623 : SignedRanges; 4624 4625 // See if we've computed this range already. 4626 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4627 if (I != Cache.end()) 4628 return I->second; 4629 4630 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4631 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4632 4633 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4634 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4635 4636 // If the value has known zeros, the maximum value will have those known zeros 4637 // as well. 4638 uint32_t TZ = GetMinTrailingZeros(S); 4639 if (TZ != 0) { 4640 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4641 ConservativeResult = 4642 ConstantRange(APInt::getMinValue(BitWidth), 4643 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4644 else 4645 ConservativeResult = ConstantRange( 4646 APInt::getSignedMinValue(BitWidth), 4647 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4648 } 4649 4650 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4651 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4652 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4653 X = X.add(getRange(Add->getOperand(i), SignHint)); 4654 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4655 } 4656 4657 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4658 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4659 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4660 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4661 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4662 } 4663 4664 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4665 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4666 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4667 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4668 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4669 } 4670 4671 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4672 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4673 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4674 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4675 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4676 } 4677 4678 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4679 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4680 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4681 return setRange(UDiv, SignHint, 4682 ConservativeResult.intersectWith(X.udiv(Y))); 4683 } 4684 4685 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4686 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4687 return setRange(ZExt, SignHint, 4688 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4689 } 4690 4691 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4692 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4693 return setRange(SExt, SignHint, 4694 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4695 } 4696 4697 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4698 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4699 return setRange(Trunc, SignHint, 4700 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4701 } 4702 4703 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4704 // If there's no unsigned wrap, the value will never be less than its 4705 // initial value. 4706 if (AddRec->hasNoUnsignedWrap()) 4707 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4708 if (!C->getValue()->isZero()) 4709 ConservativeResult = ConservativeResult.intersectWith( 4710 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4711 4712 // If there's no signed wrap, and all the operands have the same sign or 4713 // zero, the value won't ever change sign. 4714 if (AddRec->hasNoSignedWrap()) { 4715 bool AllNonNeg = true; 4716 bool AllNonPos = true; 4717 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4718 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4719 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4720 } 4721 if (AllNonNeg) 4722 ConservativeResult = ConservativeResult.intersectWith( 4723 ConstantRange(APInt(BitWidth, 0), 4724 APInt::getSignedMinValue(BitWidth))); 4725 else if (AllNonPos) 4726 ConservativeResult = ConservativeResult.intersectWith( 4727 ConstantRange(APInt::getSignedMinValue(BitWidth), 4728 APInt(BitWidth, 1))); 4729 } 4730 4731 // TODO: non-affine addrec 4732 if (AddRec->isAffine()) { 4733 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4734 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4735 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4736 auto RangeFromAffine = getRangeForAffineAR( 4737 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4738 BitWidth); 4739 if (!RangeFromAffine.isFullSet()) 4740 ConservativeResult = 4741 ConservativeResult.intersectWith(RangeFromAffine); 4742 4743 auto RangeFromFactoring = getRangeViaFactoring( 4744 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4745 BitWidth); 4746 if (!RangeFromFactoring.isFullSet()) 4747 ConservativeResult = 4748 ConservativeResult.intersectWith(RangeFromFactoring); 4749 } 4750 } 4751 4752 return setRange(AddRec, SignHint, ConservativeResult); 4753 } 4754 4755 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4756 // Check if the IR explicitly contains !range metadata. 4757 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4758 if (MDRange.hasValue()) 4759 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4760 4761 // Split here to avoid paying the compile-time cost of calling both 4762 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4763 // if needed. 4764 const DataLayout &DL = getDataLayout(); 4765 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4766 // For a SCEVUnknown, ask ValueTracking. 4767 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4768 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4769 if (Ones != ~Zeros + 1) 4770 ConservativeResult = 4771 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4772 } else { 4773 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4774 "generalize as needed!"); 4775 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4776 if (NS > 1) 4777 ConservativeResult = ConservativeResult.intersectWith( 4778 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4779 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4780 } 4781 4782 return setRange(U, SignHint, ConservativeResult); 4783 } 4784 4785 return setRange(S, SignHint, ConservativeResult); 4786 } 4787 4788 // Given a StartRange, Step and MaxBECount for an expression compute a range of 4789 // values that the expression can take. Initially, the expression has a value 4790 // from StartRange and then is changed by Step up to MaxBECount times. Signed 4791 // argument defines if we treat Step as signed or unsigned. 4792 static ConstantRange getRangeForAffineARHelper(APInt Step, 4793 ConstantRange StartRange, 4794 APInt MaxBECount, 4795 unsigned BitWidth, bool Signed) { 4796 // If either Step or MaxBECount is 0, then the expression won't change, and we 4797 // just need to return the initial range. 4798 if (Step == 0 || MaxBECount == 0) 4799 return StartRange; 4800 4801 // If we don't know anything about the initial value (i.e. StartRange is 4802 // FullRange), then we don't know anything about the final range either. 4803 // Return FullRange. 4804 if (StartRange.isFullSet()) 4805 return ConstantRange(BitWidth, /* isFullSet = */ true); 4806 4807 // If Step is signed and negative, then we use its absolute value, but we also 4808 // note that we're moving in the opposite direction. 4809 bool Descending = Signed && Step.isNegative(); 4810 4811 if (Signed) 4812 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 4813 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 4814 // This equations hold true due to the well-defined wrap-around behavior of 4815 // APInt. 4816 Step = Step.abs(); 4817 4818 // Check if Offset is more than full span of BitWidth. If it is, the 4819 // expression is guaranteed to overflow. 4820 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 4821 return ConstantRange(BitWidth, /* isFullSet = */ true); 4822 4823 // Offset is by how much the expression can change. Checks above guarantee no 4824 // overflow here. 4825 APInt Offset = Step * MaxBECount; 4826 4827 // Minimum value of the final range will match the minimal value of StartRange 4828 // if the expression is increasing and will be decreased by Offset otherwise. 4829 // Maximum value of the final range will match the maximal value of StartRange 4830 // if the expression is decreasing and will be increased by Offset otherwise. 4831 APInt StartLower = StartRange.getLower(); 4832 APInt StartUpper = StartRange.getUpper() - 1; 4833 APInt MovedBoundary = 4834 Descending ? (StartLower - Offset) : (StartUpper + Offset); 4835 4836 // It's possible that the new minimum/maximum value will fall into the initial 4837 // range (due to wrap around). This means that the expression can take any 4838 // value in this bitwidth, and we have to return full range. 4839 if (StartRange.contains(MovedBoundary)) 4840 return ConstantRange(BitWidth, /* isFullSet = */ true); 4841 4842 APInt NewLower, NewUpper; 4843 if (Descending) { 4844 NewLower = MovedBoundary; 4845 NewUpper = StartUpper; 4846 } else { 4847 NewLower = StartLower; 4848 NewUpper = MovedBoundary; 4849 } 4850 4851 // If we end up with full range, return a proper full range. 4852 if (NewLower == NewUpper + 1) 4853 return ConstantRange(BitWidth, /* isFullSet = */ true); 4854 4855 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 4856 return ConstantRange(NewLower, NewUpper + 1); 4857 } 4858 4859 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4860 const SCEV *Step, 4861 const SCEV *MaxBECount, 4862 unsigned BitWidth) { 4863 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4864 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4865 "Precondition!"); 4866 4867 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4868 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4869 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax(); 4870 4871 // First, consider step signed. 4872 ConstantRange StartSRange = getSignedRange(Start); 4873 ConstantRange StepSRange = getSignedRange(Step); 4874 4875 // If Step can be both positive and negative, we need to find ranges for the 4876 // maximum absolute step values in both directions and union them. 4877 ConstantRange SR = 4878 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 4879 MaxBECountValue, BitWidth, /* Signed = */ true); 4880 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 4881 StartSRange, MaxBECountValue, 4882 BitWidth, /* Signed = */ true)); 4883 4884 // Next, consider step unsigned. 4885 ConstantRange UR = getRangeForAffineARHelper( 4886 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start), 4887 MaxBECountValue, BitWidth, /* Signed = */ false); 4888 4889 // Finally, intersect signed and unsigned ranges. 4890 return SR.intersectWith(UR); 4891 } 4892 4893 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4894 const SCEV *Step, 4895 const SCEV *MaxBECount, 4896 unsigned BitWidth) { 4897 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4898 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4899 4900 struct SelectPattern { 4901 Value *Condition = nullptr; 4902 APInt TrueValue; 4903 APInt FalseValue; 4904 4905 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4906 const SCEV *S) { 4907 Optional<unsigned> CastOp; 4908 APInt Offset(BitWidth, 0); 4909 4910 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4911 "Should be!"); 4912 4913 // Peel off a constant offset: 4914 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4915 // In the future we could consider being smarter here and handle 4916 // {Start+Step,+,Step} too. 4917 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4918 return; 4919 4920 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4921 S = SA->getOperand(1); 4922 } 4923 4924 // Peel off a cast operation 4925 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4926 CastOp = SCast->getSCEVType(); 4927 S = SCast->getOperand(); 4928 } 4929 4930 using namespace llvm::PatternMatch; 4931 4932 auto *SU = dyn_cast<SCEVUnknown>(S); 4933 const APInt *TrueVal, *FalseVal; 4934 if (!SU || 4935 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4936 m_APInt(FalseVal)))) { 4937 Condition = nullptr; 4938 return; 4939 } 4940 4941 TrueValue = *TrueVal; 4942 FalseValue = *FalseVal; 4943 4944 // Re-apply the cast we peeled off earlier 4945 if (CastOp.hasValue()) 4946 switch (*CastOp) { 4947 default: 4948 llvm_unreachable("Unknown SCEV cast type!"); 4949 4950 case scTruncate: 4951 TrueValue = TrueValue.trunc(BitWidth); 4952 FalseValue = FalseValue.trunc(BitWidth); 4953 break; 4954 case scZeroExtend: 4955 TrueValue = TrueValue.zext(BitWidth); 4956 FalseValue = FalseValue.zext(BitWidth); 4957 break; 4958 case scSignExtend: 4959 TrueValue = TrueValue.sext(BitWidth); 4960 FalseValue = FalseValue.sext(BitWidth); 4961 break; 4962 } 4963 4964 // Re-apply the constant offset we peeled off earlier 4965 TrueValue += Offset; 4966 FalseValue += Offset; 4967 } 4968 4969 bool isRecognized() { return Condition != nullptr; } 4970 }; 4971 4972 SelectPattern StartPattern(*this, BitWidth, Start); 4973 if (!StartPattern.isRecognized()) 4974 return ConstantRange(BitWidth, /* isFullSet = */ true); 4975 4976 SelectPattern StepPattern(*this, BitWidth, Step); 4977 if (!StepPattern.isRecognized()) 4978 return ConstantRange(BitWidth, /* isFullSet = */ true); 4979 4980 if (StartPattern.Condition != StepPattern.Condition) { 4981 // We don't handle this case today; but we could, by considering four 4982 // possibilities below instead of two. I'm not sure if there are cases where 4983 // that will help over what getRange already does, though. 4984 return ConstantRange(BitWidth, /* isFullSet = */ true); 4985 } 4986 4987 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4988 // construct arbitrary general SCEV expressions here. This function is called 4989 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4990 // say) can end up caching a suboptimal value. 4991 4992 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4993 // C2352 and C2512 (otherwise it isn't needed). 4994 4995 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4996 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4997 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4998 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4999 5000 ConstantRange TrueRange = 5001 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5002 ConstantRange FalseRange = 5003 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5004 5005 return TrueRange.unionWith(FalseRange); 5006 } 5007 5008 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5009 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5010 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5011 5012 // Return early if there are no flags to propagate to the SCEV. 5013 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5014 if (BinOp->hasNoUnsignedWrap()) 5015 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5016 if (BinOp->hasNoSignedWrap()) 5017 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5018 if (Flags == SCEV::FlagAnyWrap) 5019 return SCEV::FlagAnyWrap; 5020 5021 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5022 } 5023 5024 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5025 // Here we check that I is in the header of the innermost loop containing I, 5026 // since we only deal with instructions in the loop header. The actual loop we 5027 // need to check later will come from an add recurrence, but getting that 5028 // requires computing the SCEV of the operands, which can be expensive. This 5029 // check we can do cheaply to rule out some cases early. 5030 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5031 if (InnermostContainingLoop == nullptr || 5032 InnermostContainingLoop->getHeader() != I->getParent()) 5033 return false; 5034 5035 // Only proceed if we can prove that I does not yield poison. 5036 if (!isKnownNotFullPoison(I)) return false; 5037 5038 // At this point we know that if I is executed, then it does not wrap 5039 // according to at least one of NSW or NUW. If I is not executed, then we do 5040 // not know if the calculation that I represents would wrap. Multiple 5041 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5042 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5043 // derived from other instructions that map to the same SCEV. We cannot make 5044 // that guarantee for cases where I is not executed. So we need to find the 5045 // loop that I is considered in relation to and prove that I is executed for 5046 // every iteration of that loop. That implies that the value that I 5047 // calculates does not wrap anywhere in the loop, so then we can apply the 5048 // flags to the SCEV. 5049 // 5050 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5051 // from different loops, so that we know which loop to prove that I is 5052 // executed in. 5053 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5054 // I could be an extractvalue from a call to an overflow intrinsic. 5055 // TODO: We can do better here in some cases. 5056 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5057 return false; 5058 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5059 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5060 bool AllOtherOpsLoopInvariant = true; 5061 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5062 ++OtherOpIndex) { 5063 if (OtherOpIndex != OpIndex) { 5064 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5065 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5066 AllOtherOpsLoopInvariant = false; 5067 break; 5068 } 5069 } 5070 } 5071 if (AllOtherOpsLoopInvariant && 5072 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5073 return true; 5074 } 5075 } 5076 return false; 5077 } 5078 5079 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5080 // If we know that \c I can never be poison period, then that's enough. 5081 if (isSCEVExprNeverPoison(I)) 5082 return true; 5083 5084 // For an add recurrence specifically, we assume that infinite loops without 5085 // side effects are undefined behavior, and then reason as follows: 5086 // 5087 // If the add recurrence is poison in any iteration, it is poison on all 5088 // future iterations (since incrementing poison yields poison). If the result 5089 // of the add recurrence is fed into the loop latch condition and the loop 5090 // does not contain any throws or exiting blocks other than the latch, we now 5091 // have the ability to "choose" whether the backedge is taken or not (by 5092 // choosing a sufficiently evil value for the poison feeding into the branch) 5093 // for every iteration including and after the one in which \p I first became 5094 // poison. There are two possibilities (let's call the iteration in which \p 5095 // I first became poison as K): 5096 // 5097 // 1. In the set of iterations including and after K, the loop body executes 5098 // no side effects. In this case executing the backege an infinte number 5099 // of times will yield undefined behavior. 5100 // 5101 // 2. In the set of iterations including and after K, the loop body executes 5102 // at least one side effect. In this case, that specific instance of side 5103 // effect is control dependent on poison, which also yields undefined 5104 // behavior. 5105 5106 auto *ExitingBB = L->getExitingBlock(); 5107 auto *LatchBB = L->getLoopLatch(); 5108 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5109 return false; 5110 5111 SmallPtrSet<const Instruction *, 16> Pushed; 5112 SmallVector<const Instruction *, 8> PoisonStack; 5113 5114 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5115 // things that are known to be fully poison under that assumption go on the 5116 // PoisonStack. 5117 Pushed.insert(I); 5118 PoisonStack.push_back(I); 5119 5120 bool LatchControlDependentOnPoison = false; 5121 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5122 const Instruction *Poison = PoisonStack.pop_back_val(); 5123 5124 for (auto *PoisonUser : Poison->users()) { 5125 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5126 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5127 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5128 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5129 assert(BI->isConditional() && "Only possibility!"); 5130 if (BI->getParent() == LatchBB) { 5131 LatchControlDependentOnPoison = true; 5132 break; 5133 } 5134 } 5135 } 5136 } 5137 5138 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5139 } 5140 5141 ScalarEvolution::LoopProperties 5142 ScalarEvolution::getLoopProperties(const Loop *L) { 5143 typedef ScalarEvolution::LoopProperties LoopProperties; 5144 5145 auto Itr = LoopPropertiesCache.find(L); 5146 if (Itr == LoopPropertiesCache.end()) { 5147 auto HasSideEffects = [](Instruction *I) { 5148 if (auto *SI = dyn_cast<StoreInst>(I)) 5149 return !SI->isSimple(); 5150 5151 return I->mayHaveSideEffects(); 5152 }; 5153 5154 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5155 /*HasNoSideEffects*/ true}; 5156 5157 for (auto *BB : L->getBlocks()) 5158 for (auto &I : *BB) { 5159 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5160 LP.HasNoAbnormalExits = false; 5161 if (HasSideEffects(&I)) 5162 LP.HasNoSideEffects = false; 5163 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5164 break; // We're already as pessimistic as we can get. 5165 } 5166 5167 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5168 assert(InsertPair.second && "We just checked!"); 5169 Itr = InsertPair.first; 5170 } 5171 5172 return Itr->second; 5173 } 5174 5175 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5176 if (!isSCEVable(V->getType())) 5177 return getUnknown(V); 5178 5179 if (Instruction *I = dyn_cast<Instruction>(V)) { 5180 // Don't attempt to analyze instructions in blocks that aren't 5181 // reachable. Such instructions don't matter, and they aren't required 5182 // to obey basic rules for definitions dominating uses which this 5183 // analysis depends on. 5184 if (!DT.isReachableFromEntry(I->getParent())) 5185 return getUnknown(V); 5186 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5187 return getConstant(CI); 5188 else if (isa<ConstantPointerNull>(V)) 5189 return getZero(V->getType()); 5190 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5191 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5192 else if (!isa<ConstantExpr>(V)) 5193 return getUnknown(V); 5194 5195 Operator *U = cast<Operator>(V); 5196 if (auto BO = MatchBinaryOp(U, DT)) { 5197 switch (BO->Opcode) { 5198 case Instruction::Add: { 5199 // The simple thing to do would be to just call getSCEV on both operands 5200 // and call getAddExpr with the result. However if we're looking at a 5201 // bunch of things all added together, this can be quite inefficient, 5202 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5203 // Instead, gather up all the operands and make a single getAddExpr call. 5204 // LLVM IR canonical form means we need only traverse the left operands. 5205 SmallVector<const SCEV *, 4> AddOps; 5206 do { 5207 if (BO->Op) { 5208 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5209 AddOps.push_back(OpSCEV); 5210 break; 5211 } 5212 5213 // If a NUW or NSW flag can be applied to the SCEV for this 5214 // addition, then compute the SCEV for this addition by itself 5215 // with a separate call to getAddExpr. We need to do that 5216 // instead of pushing the operands of the addition onto AddOps, 5217 // since the flags are only known to apply to this particular 5218 // addition - they may not apply to other additions that can be 5219 // formed with operands from AddOps. 5220 const SCEV *RHS = getSCEV(BO->RHS); 5221 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5222 if (Flags != SCEV::FlagAnyWrap) { 5223 const SCEV *LHS = getSCEV(BO->LHS); 5224 if (BO->Opcode == Instruction::Sub) 5225 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5226 else 5227 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5228 break; 5229 } 5230 } 5231 5232 if (BO->Opcode == Instruction::Sub) 5233 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5234 else 5235 AddOps.push_back(getSCEV(BO->RHS)); 5236 5237 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5238 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5239 NewBO->Opcode != Instruction::Sub)) { 5240 AddOps.push_back(getSCEV(BO->LHS)); 5241 break; 5242 } 5243 BO = NewBO; 5244 } while (true); 5245 5246 return getAddExpr(AddOps); 5247 } 5248 5249 case Instruction::Mul: { 5250 SmallVector<const SCEV *, 4> MulOps; 5251 do { 5252 if (BO->Op) { 5253 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5254 MulOps.push_back(OpSCEV); 5255 break; 5256 } 5257 5258 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5259 if (Flags != SCEV::FlagAnyWrap) { 5260 MulOps.push_back( 5261 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5262 break; 5263 } 5264 } 5265 5266 MulOps.push_back(getSCEV(BO->RHS)); 5267 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5268 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5269 MulOps.push_back(getSCEV(BO->LHS)); 5270 break; 5271 } 5272 BO = NewBO; 5273 } while (true); 5274 5275 return getMulExpr(MulOps); 5276 } 5277 case Instruction::UDiv: 5278 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5279 case Instruction::Sub: { 5280 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5281 if (BO->Op) 5282 Flags = getNoWrapFlagsFromUB(BO->Op); 5283 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5284 } 5285 case Instruction::And: 5286 // For an expression like x&255 that merely masks off the high bits, 5287 // use zext(trunc(x)) as the SCEV expression. 5288 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5289 if (CI->isNullValue()) 5290 return getSCEV(BO->RHS); 5291 if (CI->isAllOnesValue()) 5292 return getSCEV(BO->LHS); 5293 const APInt &A = CI->getValue(); 5294 5295 // Instcombine's ShrinkDemandedConstant may strip bits out of 5296 // constants, obscuring what would otherwise be a low-bits mask. 5297 // Use computeKnownBits to compute what ShrinkDemandedConstant 5298 // knew about to reconstruct a low-bits mask value. 5299 unsigned LZ = A.countLeadingZeros(); 5300 unsigned TZ = A.countTrailingZeros(); 5301 unsigned BitWidth = A.getBitWidth(); 5302 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5303 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5304 0, &AC, nullptr, &DT); 5305 5306 APInt EffectiveMask = 5307 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5308 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5309 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5310 const SCEV *LHS = getSCEV(BO->LHS); 5311 const SCEV *ShiftedLHS = nullptr; 5312 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5313 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5314 // For an expression like (x * 8) & 8, simplify the multiply. 5315 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5316 unsigned GCD = std::min(MulZeros, TZ); 5317 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5318 SmallVector<const SCEV*, 4> MulOps; 5319 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5320 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5321 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5322 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5323 } 5324 } 5325 if (!ShiftedLHS) 5326 ShiftedLHS = getUDivExpr(LHS, MulCount); 5327 return getMulExpr( 5328 getZeroExtendExpr( 5329 getTruncateExpr(ShiftedLHS, 5330 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5331 BO->LHS->getType()), 5332 MulCount); 5333 } 5334 } 5335 break; 5336 5337 case Instruction::Or: 5338 // If the RHS of the Or is a constant, we may have something like: 5339 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5340 // optimizations will transparently handle this case. 5341 // 5342 // In order for this transformation to be safe, the LHS must be of the 5343 // form X*(2^n) and the Or constant must be less than 2^n. 5344 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5345 const SCEV *LHS = getSCEV(BO->LHS); 5346 const APInt &CIVal = CI->getValue(); 5347 if (GetMinTrailingZeros(LHS) >= 5348 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5349 // Build a plain add SCEV. 5350 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5351 // If the LHS of the add was an addrec and it has no-wrap flags, 5352 // transfer the no-wrap flags, since an or won't introduce a wrap. 5353 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5354 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5355 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5356 OldAR->getNoWrapFlags()); 5357 } 5358 return S; 5359 } 5360 } 5361 break; 5362 5363 case Instruction::Xor: 5364 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5365 // If the RHS of xor is -1, then this is a not operation. 5366 if (CI->isAllOnesValue()) 5367 return getNotSCEV(getSCEV(BO->LHS)); 5368 5369 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5370 // This is a variant of the check for xor with -1, and it handles 5371 // the case where instcombine has trimmed non-demanded bits out 5372 // of an xor with -1. 5373 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5374 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5375 if (LBO->getOpcode() == Instruction::And && 5376 LCI->getValue() == CI->getValue()) 5377 if (const SCEVZeroExtendExpr *Z = 5378 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5379 Type *UTy = BO->LHS->getType(); 5380 const SCEV *Z0 = Z->getOperand(); 5381 Type *Z0Ty = Z0->getType(); 5382 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5383 5384 // If C is a low-bits mask, the zero extend is serving to 5385 // mask off the high bits. Complement the operand and 5386 // re-apply the zext. 5387 if (CI->getValue().isMask(Z0TySize)) 5388 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5389 5390 // If C is a single bit, it may be in the sign-bit position 5391 // before the zero-extend. In this case, represent the xor 5392 // using an add, which is equivalent, and re-apply the zext. 5393 APInt Trunc = CI->getValue().trunc(Z0TySize); 5394 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5395 Trunc.isSignMask()) 5396 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5397 UTy); 5398 } 5399 } 5400 break; 5401 5402 case Instruction::Shl: 5403 // Turn shift left of a constant amount into a multiply. 5404 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5405 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5406 5407 // If the shift count is not less than the bitwidth, the result of 5408 // the shift is undefined. Don't try to analyze it, because the 5409 // resolution chosen here may differ from the resolution chosen in 5410 // other parts of the compiler. 5411 if (SA->getValue().uge(BitWidth)) 5412 break; 5413 5414 // It is currently not resolved how to interpret NSW for left 5415 // shift by BitWidth - 1, so we avoid applying flags in that 5416 // case. Remove this check (or this comment) once the situation 5417 // is resolved. See 5418 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5419 // and http://reviews.llvm.org/D8890 . 5420 auto Flags = SCEV::FlagAnyWrap; 5421 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5422 Flags = getNoWrapFlagsFromUB(BO->Op); 5423 5424 Constant *X = ConstantInt::get(getContext(), 5425 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5426 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5427 } 5428 break; 5429 5430 case Instruction::AShr: 5431 // AShr X, C, where C is a constant. 5432 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5433 if (!CI) 5434 break; 5435 5436 Type *OuterTy = BO->LHS->getType(); 5437 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5438 // If the shift count is not less than the bitwidth, the result of 5439 // the shift is undefined. Don't try to analyze it, because the 5440 // resolution chosen here may differ from the resolution chosen in 5441 // other parts of the compiler. 5442 if (CI->getValue().uge(BitWidth)) 5443 break; 5444 5445 if (CI->isNullValue()) 5446 return getSCEV(BO->LHS); // shift by zero --> noop 5447 5448 uint64_t AShrAmt = CI->getZExtValue(); 5449 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5450 5451 Operator *L = dyn_cast<Operator>(BO->LHS); 5452 if (L && L->getOpcode() == Instruction::Shl) { 5453 // X = Shl A, n 5454 // Y = AShr X, m 5455 // Both n and m are constant. 5456 5457 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5458 if (L->getOperand(1) == BO->RHS) 5459 // For a two-shift sext-inreg, i.e. n = m, 5460 // use sext(trunc(x)) as the SCEV expression. 5461 return getSignExtendExpr( 5462 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5463 5464 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5465 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5466 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5467 if (ShlAmt > AShrAmt) { 5468 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5469 // expression. We already checked that ShlAmt < BitWidth, so 5470 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5471 // ShlAmt - AShrAmt < Amt. 5472 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5473 ShlAmt - AShrAmt); 5474 return getSignExtendExpr( 5475 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5476 getConstant(Mul)), OuterTy); 5477 } 5478 } 5479 } 5480 break; 5481 } 5482 } 5483 5484 switch (U->getOpcode()) { 5485 case Instruction::Trunc: 5486 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5487 5488 case Instruction::ZExt: 5489 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5490 5491 case Instruction::SExt: 5492 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5493 5494 case Instruction::BitCast: 5495 // BitCasts are no-op casts so we just eliminate the cast. 5496 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5497 return getSCEV(U->getOperand(0)); 5498 break; 5499 5500 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5501 // lead to pointer expressions which cannot safely be expanded to GEPs, 5502 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5503 // simplifying integer expressions. 5504 5505 case Instruction::GetElementPtr: 5506 return createNodeForGEP(cast<GEPOperator>(U)); 5507 5508 case Instruction::PHI: 5509 return createNodeForPHI(cast<PHINode>(U)); 5510 5511 case Instruction::Select: 5512 // U can also be a select constant expr, which let fall through. Since 5513 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5514 // constant expressions cannot have instructions as operands, we'd have 5515 // returned getUnknown for a select constant expressions anyway. 5516 if (isa<Instruction>(U)) 5517 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5518 U->getOperand(1), U->getOperand(2)); 5519 break; 5520 5521 case Instruction::Call: 5522 case Instruction::Invoke: 5523 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5524 return getSCEV(RV); 5525 break; 5526 } 5527 5528 return getUnknown(V); 5529 } 5530 5531 5532 5533 //===----------------------------------------------------------------------===// 5534 // Iteration Count Computation Code 5535 // 5536 5537 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5538 if (!ExitCount) 5539 return 0; 5540 5541 ConstantInt *ExitConst = ExitCount->getValue(); 5542 5543 // Guard against huge trip counts. 5544 if (ExitConst->getValue().getActiveBits() > 32) 5545 return 0; 5546 5547 // In case of integer overflow, this returns 0, which is correct. 5548 return ((unsigned)ExitConst->getZExtValue()) + 1; 5549 } 5550 5551 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 5552 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5553 return getSmallConstantTripCount(L, ExitingBB); 5554 5555 // No trip count information for multiple exits. 5556 return 0; 5557 } 5558 5559 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 5560 BasicBlock *ExitingBlock) { 5561 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5562 assert(L->isLoopExiting(ExitingBlock) && 5563 "Exiting block must actually branch out of the loop!"); 5564 const SCEVConstant *ExitCount = 5565 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5566 return getConstantTripCount(ExitCount); 5567 } 5568 5569 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 5570 const auto *MaxExitCount = 5571 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5572 return getConstantTripCount(MaxExitCount); 5573 } 5574 5575 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 5576 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5577 return getSmallConstantTripMultiple(L, ExitingBB); 5578 5579 // No trip multiple information for multiple exits. 5580 return 0; 5581 } 5582 5583 /// Returns the largest constant divisor of the trip count of this loop as a 5584 /// normal unsigned value, if possible. This means that the actual trip count is 5585 /// always a multiple of the returned value (don't forget the trip count could 5586 /// very well be zero as well!). 5587 /// 5588 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5589 /// multiple of a constant (which is also the case if the trip count is simply 5590 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5591 /// if the trip count is very large (>= 2^32). 5592 /// 5593 /// As explained in the comments for getSmallConstantTripCount, this assumes 5594 /// that control exits the loop via ExitingBlock. 5595 unsigned 5596 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 5597 BasicBlock *ExitingBlock) { 5598 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5599 assert(L->isLoopExiting(ExitingBlock) && 5600 "Exiting block must actually branch out of the loop!"); 5601 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5602 if (ExitCount == getCouldNotCompute()) 5603 return 1; 5604 5605 // Get the trip count from the BE count by adding 1. 5606 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5607 5608 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 5609 if (!TC) 5610 // Attempt to factor more general cases. Returns the greatest power of 5611 // two divisor. If overflow happens, the trip count expression is still 5612 // divisible by the greatest power of 2 divisor returned. 5613 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 5614 5615 ConstantInt *Result = TC->getValue(); 5616 5617 // Guard against huge trip counts (this requires checking 5618 // for zero to handle the case where the trip count == -1 and the 5619 // addition wraps). 5620 if (!Result || Result->getValue().getActiveBits() > 32 || 5621 Result->getValue().getActiveBits() == 0) 5622 return 1; 5623 5624 return (unsigned)Result->getZExtValue(); 5625 } 5626 5627 /// Get the expression for the number of loop iterations for which this loop is 5628 /// guaranteed not to exit via ExitingBlock. Otherwise return 5629 /// SCEVCouldNotCompute. 5630 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 5631 BasicBlock *ExitingBlock) { 5632 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5633 } 5634 5635 const SCEV * 5636 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5637 SCEVUnionPredicate &Preds) { 5638 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5639 } 5640 5641 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5642 return getBackedgeTakenInfo(L).getExact(this); 5643 } 5644 5645 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5646 /// known never to be less than the actual backedge taken count. 5647 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5648 return getBackedgeTakenInfo(L).getMax(this); 5649 } 5650 5651 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5652 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5653 } 5654 5655 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5656 static void 5657 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5658 BasicBlock *Header = L->getHeader(); 5659 5660 // Push all Loop-header PHIs onto the Worklist stack. 5661 for (BasicBlock::iterator I = Header->begin(); 5662 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5663 Worklist.push_back(PN); 5664 } 5665 5666 const ScalarEvolution::BackedgeTakenInfo & 5667 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5668 auto &BTI = getBackedgeTakenInfo(L); 5669 if (BTI.hasFullInfo()) 5670 return BTI; 5671 5672 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5673 5674 if (!Pair.second) 5675 return Pair.first->second; 5676 5677 BackedgeTakenInfo Result = 5678 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5679 5680 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5681 } 5682 5683 const ScalarEvolution::BackedgeTakenInfo & 5684 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5685 // Initially insert an invalid entry for this loop. If the insertion 5686 // succeeds, proceed to actually compute a backedge-taken count and 5687 // update the value. The temporary CouldNotCompute value tells SCEV 5688 // code elsewhere that it shouldn't attempt to request a new 5689 // backedge-taken count, which could result in infinite recursion. 5690 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5691 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5692 if (!Pair.second) 5693 return Pair.first->second; 5694 5695 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5696 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5697 // must be cleared in this scope. 5698 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5699 5700 if (Result.getExact(this) != getCouldNotCompute()) { 5701 assert(isLoopInvariant(Result.getExact(this), L) && 5702 isLoopInvariant(Result.getMax(this), L) && 5703 "Computed backedge-taken count isn't loop invariant for loop!"); 5704 ++NumTripCountsComputed; 5705 } 5706 else if (Result.getMax(this) == getCouldNotCompute() && 5707 isa<PHINode>(L->getHeader()->begin())) { 5708 // Only count loops that have phi nodes as not being computable. 5709 ++NumTripCountsNotComputed; 5710 } 5711 5712 // Now that we know more about the trip count for this loop, forget any 5713 // existing SCEV values for PHI nodes in this loop since they are only 5714 // conservative estimates made without the benefit of trip count 5715 // information. This is similar to the code in forgetLoop, except that 5716 // it handles SCEVUnknown PHI nodes specially. 5717 if (Result.hasAnyInfo()) { 5718 SmallVector<Instruction *, 16> Worklist; 5719 PushLoopPHIs(L, Worklist); 5720 5721 SmallPtrSet<Instruction *, 8> Visited; 5722 while (!Worklist.empty()) { 5723 Instruction *I = Worklist.pop_back_val(); 5724 if (!Visited.insert(I).second) 5725 continue; 5726 5727 ValueExprMapType::iterator It = 5728 ValueExprMap.find_as(static_cast<Value *>(I)); 5729 if (It != ValueExprMap.end()) { 5730 const SCEV *Old = It->second; 5731 5732 // SCEVUnknown for a PHI either means that it has an unrecognized 5733 // structure, or it's a PHI that's in the progress of being computed 5734 // by createNodeForPHI. In the former case, additional loop trip 5735 // count information isn't going to change anything. In the later 5736 // case, createNodeForPHI will perform the necessary updates on its 5737 // own when it gets to that point. 5738 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5739 eraseValueFromMap(It->first); 5740 forgetMemoizedResults(Old); 5741 } 5742 if (PHINode *PN = dyn_cast<PHINode>(I)) 5743 ConstantEvolutionLoopExitValue.erase(PN); 5744 } 5745 5746 PushDefUseChildren(I, Worklist); 5747 } 5748 } 5749 5750 // Re-lookup the insert position, since the call to 5751 // computeBackedgeTakenCount above could result in a 5752 // recusive call to getBackedgeTakenInfo (on a different 5753 // loop), which would invalidate the iterator computed 5754 // earlier. 5755 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5756 } 5757 5758 void ScalarEvolution::forgetLoop(const Loop *L) { 5759 // Drop any stored trip count value. 5760 auto RemoveLoopFromBackedgeMap = 5761 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5762 auto BTCPos = Map.find(L); 5763 if (BTCPos != Map.end()) { 5764 BTCPos->second.clear(); 5765 Map.erase(BTCPos); 5766 } 5767 }; 5768 5769 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5770 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5771 5772 // Drop information about expressions based on loop-header PHIs. 5773 SmallVector<Instruction *, 16> Worklist; 5774 PushLoopPHIs(L, Worklist); 5775 5776 SmallPtrSet<Instruction *, 8> Visited; 5777 while (!Worklist.empty()) { 5778 Instruction *I = Worklist.pop_back_val(); 5779 if (!Visited.insert(I).second) 5780 continue; 5781 5782 ValueExprMapType::iterator It = 5783 ValueExprMap.find_as(static_cast<Value *>(I)); 5784 if (It != ValueExprMap.end()) { 5785 eraseValueFromMap(It->first); 5786 forgetMemoizedResults(It->second); 5787 if (PHINode *PN = dyn_cast<PHINode>(I)) 5788 ConstantEvolutionLoopExitValue.erase(PN); 5789 } 5790 5791 PushDefUseChildren(I, Worklist); 5792 } 5793 5794 // Forget all contained loops too, to avoid dangling entries in the 5795 // ValuesAtScopes map. 5796 for (Loop *I : *L) 5797 forgetLoop(I); 5798 5799 LoopPropertiesCache.erase(L); 5800 } 5801 5802 void ScalarEvolution::forgetValue(Value *V) { 5803 Instruction *I = dyn_cast<Instruction>(V); 5804 if (!I) return; 5805 5806 // Drop information about expressions based on loop-header PHIs. 5807 SmallVector<Instruction *, 16> Worklist; 5808 Worklist.push_back(I); 5809 5810 SmallPtrSet<Instruction *, 8> Visited; 5811 while (!Worklist.empty()) { 5812 I = Worklist.pop_back_val(); 5813 if (!Visited.insert(I).second) 5814 continue; 5815 5816 ValueExprMapType::iterator It = 5817 ValueExprMap.find_as(static_cast<Value *>(I)); 5818 if (It != ValueExprMap.end()) { 5819 eraseValueFromMap(It->first); 5820 forgetMemoizedResults(It->second); 5821 if (PHINode *PN = dyn_cast<PHINode>(I)) 5822 ConstantEvolutionLoopExitValue.erase(PN); 5823 } 5824 5825 PushDefUseChildren(I, Worklist); 5826 } 5827 } 5828 5829 /// Get the exact loop backedge taken count considering all loop exits. A 5830 /// computable result can only be returned for loops with a single exit. 5831 /// Returning the minimum taken count among all exits is incorrect because one 5832 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5833 /// the limit of each loop test is never skipped. This is a valid assumption as 5834 /// long as the loop exits via that test. For precise results, it is the 5835 /// caller's responsibility to specify the relevant loop exit using 5836 /// getExact(ExitingBlock, SE). 5837 const SCEV * 5838 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5839 SCEVUnionPredicate *Preds) const { 5840 // If any exits were not computable, the loop is not computable. 5841 if (!isComplete() || ExitNotTaken.empty()) 5842 return SE->getCouldNotCompute(); 5843 5844 const SCEV *BECount = nullptr; 5845 for (auto &ENT : ExitNotTaken) { 5846 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5847 5848 if (!BECount) 5849 BECount = ENT.ExactNotTaken; 5850 else if (BECount != ENT.ExactNotTaken) 5851 return SE->getCouldNotCompute(); 5852 if (Preds && !ENT.hasAlwaysTruePredicate()) 5853 Preds->add(ENT.Predicate.get()); 5854 5855 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5856 "Predicate should be always true!"); 5857 } 5858 5859 assert(BECount && "Invalid not taken count for loop exit"); 5860 return BECount; 5861 } 5862 5863 /// Get the exact not taken count for this loop exit. 5864 const SCEV * 5865 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5866 ScalarEvolution *SE) const { 5867 for (auto &ENT : ExitNotTaken) 5868 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5869 return ENT.ExactNotTaken; 5870 5871 return SE->getCouldNotCompute(); 5872 } 5873 5874 /// getMax - Get the max backedge taken count for the loop. 5875 const SCEV * 5876 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5877 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5878 return !ENT.hasAlwaysTruePredicate(); 5879 }; 5880 5881 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5882 return SE->getCouldNotCompute(); 5883 5884 return getMax(); 5885 } 5886 5887 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5888 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5889 return !ENT.hasAlwaysTruePredicate(); 5890 }; 5891 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5892 } 5893 5894 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5895 ScalarEvolution *SE) const { 5896 if (getMax() && getMax() != SE->getCouldNotCompute() && 5897 SE->hasOperand(getMax(), S)) 5898 return true; 5899 5900 for (auto &ENT : ExitNotTaken) 5901 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5902 SE->hasOperand(ENT.ExactNotTaken, S)) 5903 return true; 5904 5905 return false; 5906 } 5907 5908 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5909 /// computable exit into a persistent ExitNotTakenInfo array. 5910 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5911 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5912 &&ExitCounts, 5913 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5914 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5915 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5916 ExitNotTaken.reserve(ExitCounts.size()); 5917 std::transform( 5918 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5919 [&](const EdgeExitInfo &EEI) { 5920 BasicBlock *ExitBB = EEI.first; 5921 const ExitLimit &EL = EEI.second; 5922 if (EL.Predicates.empty()) 5923 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5924 5925 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5926 for (auto *Pred : EL.Predicates) 5927 Predicate->add(Pred); 5928 5929 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5930 }); 5931 } 5932 5933 /// Invalidate this result and free the ExitNotTakenInfo array. 5934 void ScalarEvolution::BackedgeTakenInfo::clear() { 5935 ExitNotTaken.clear(); 5936 } 5937 5938 /// Compute the number of times the backedge of the specified loop will execute. 5939 ScalarEvolution::BackedgeTakenInfo 5940 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5941 bool AllowPredicates) { 5942 SmallVector<BasicBlock *, 8> ExitingBlocks; 5943 L->getExitingBlocks(ExitingBlocks); 5944 5945 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5946 5947 SmallVector<EdgeExitInfo, 4> ExitCounts; 5948 bool CouldComputeBECount = true; 5949 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5950 const SCEV *MustExitMaxBECount = nullptr; 5951 const SCEV *MayExitMaxBECount = nullptr; 5952 bool MustExitMaxOrZero = false; 5953 5954 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5955 // and compute maxBECount. 5956 // Do a union of all the predicates here. 5957 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5958 BasicBlock *ExitBB = ExitingBlocks[i]; 5959 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5960 5961 assert((AllowPredicates || EL.Predicates.empty()) && 5962 "Predicated exit limit when predicates are not allowed!"); 5963 5964 // 1. For each exit that can be computed, add an entry to ExitCounts. 5965 // CouldComputeBECount is true only if all exits can be computed. 5966 if (EL.ExactNotTaken == getCouldNotCompute()) 5967 // We couldn't compute an exact value for this exit, so 5968 // we won't be able to compute an exact value for the loop. 5969 CouldComputeBECount = false; 5970 else 5971 ExitCounts.emplace_back(ExitBB, EL); 5972 5973 // 2. Derive the loop's MaxBECount from each exit's max number of 5974 // non-exiting iterations. Partition the loop exits into two kinds: 5975 // LoopMustExits and LoopMayExits. 5976 // 5977 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5978 // is a LoopMayExit. If any computable LoopMustExit is found, then 5979 // MaxBECount is the minimum EL.MaxNotTaken of computable 5980 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5981 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5982 // computable EL.MaxNotTaken. 5983 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5984 DT.dominates(ExitBB, Latch)) { 5985 if (!MustExitMaxBECount) { 5986 MustExitMaxBECount = EL.MaxNotTaken; 5987 MustExitMaxOrZero = EL.MaxOrZero; 5988 } else { 5989 MustExitMaxBECount = 5990 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5991 } 5992 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5993 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5994 MayExitMaxBECount = EL.MaxNotTaken; 5995 else { 5996 MayExitMaxBECount = 5997 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5998 } 5999 } 6000 } 6001 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6002 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6003 // The loop backedge will be taken the maximum or zero times if there's 6004 // a single exit that must be taken the maximum or zero times. 6005 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6006 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6007 MaxBECount, MaxOrZero); 6008 } 6009 6010 ScalarEvolution::ExitLimit 6011 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6012 bool AllowPredicates) { 6013 6014 // Okay, we've chosen an exiting block. See what condition causes us to exit 6015 // at this block and remember the exit block and whether all other targets 6016 // lead to the loop header. 6017 bool MustExecuteLoopHeader = true; 6018 BasicBlock *Exit = nullptr; 6019 for (auto *SBB : successors(ExitingBlock)) 6020 if (!L->contains(SBB)) { 6021 if (Exit) // Multiple exit successors. 6022 return getCouldNotCompute(); 6023 Exit = SBB; 6024 } else if (SBB != L->getHeader()) { 6025 MustExecuteLoopHeader = false; 6026 } 6027 6028 // At this point, we know we have a conditional branch that determines whether 6029 // the loop is exited. However, we don't know if the branch is executed each 6030 // time through the loop. If not, then the execution count of the branch will 6031 // not be equal to the trip count of the loop. 6032 // 6033 // Currently we check for this by checking to see if the Exit branch goes to 6034 // the loop header. If so, we know it will always execute the same number of 6035 // times as the loop. We also handle the case where the exit block *is* the 6036 // loop header. This is common for un-rotated loops. 6037 // 6038 // If both of those tests fail, walk up the unique predecessor chain to the 6039 // header, stopping if there is an edge that doesn't exit the loop. If the 6040 // header is reached, the execution count of the branch will be equal to the 6041 // trip count of the loop. 6042 // 6043 // More extensive analysis could be done to handle more cases here. 6044 // 6045 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6046 // The simple checks failed, try climbing the unique predecessor chain 6047 // up to the header. 6048 bool Ok = false; 6049 for (BasicBlock *BB = ExitingBlock; BB; ) { 6050 BasicBlock *Pred = BB->getUniquePredecessor(); 6051 if (!Pred) 6052 return getCouldNotCompute(); 6053 TerminatorInst *PredTerm = Pred->getTerminator(); 6054 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6055 if (PredSucc == BB) 6056 continue; 6057 // If the predecessor has a successor that isn't BB and isn't 6058 // outside the loop, assume the worst. 6059 if (L->contains(PredSucc)) 6060 return getCouldNotCompute(); 6061 } 6062 if (Pred == L->getHeader()) { 6063 Ok = true; 6064 break; 6065 } 6066 BB = Pred; 6067 } 6068 if (!Ok) 6069 return getCouldNotCompute(); 6070 } 6071 6072 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6073 TerminatorInst *Term = ExitingBlock->getTerminator(); 6074 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6075 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6076 // Proceed to the next level to examine the exit condition expression. 6077 return computeExitLimitFromCond( 6078 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6079 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6080 } 6081 6082 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6083 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6084 /*ControlsExit=*/IsOnlyExit); 6085 6086 return getCouldNotCompute(); 6087 } 6088 6089 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6090 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6091 bool ControlsExit, bool AllowPredicates) { 6092 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6093 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6094 ControlsExit, AllowPredicates); 6095 } 6096 6097 Optional<ScalarEvolution::ExitLimit> 6098 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6099 BasicBlock *TBB, BasicBlock *FBB, 6100 bool ControlsExit, bool AllowPredicates) { 6101 (void)this->L; 6102 (void)this->TBB; 6103 (void)this->FBB; 6104 (void)this->AllowPredicates; 6105 6106 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6107 this->AllowPredicates == AllowPredicates && 6108 "Variance in assumed invariant key components!"); 6109 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6110 if (Itr == TripCountMap.end()) 6111 return None; 6112 return Itr->second; 6113 } 6114 6115 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6116 BasicBlock *TBB, BasicBlock *FBB, 6117 bool ControlsExit, 6118 bool AllowPredicates, 6119 const ExitLimit &EL) { 6120 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6121 this->AllowPredicates == AllowPredicates && 6122 "Variance in assumed invariant key components!"); 6123 6124 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6125 assert(InsertResult.second && "Expected successful insertion!"); 6126 (void)InsertResult; 6127 } 6128 6129 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6130 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6131 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6132 6133 if (auto MaybeEL = 6134 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6135 return *MaybeEL; 6136 6137 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6138 ControlsExit, AllowPredicates); 6139 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6140 return EL; 6141 } 6142 6143 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6144 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6145 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6146 // Check if the controlling expression for this loop is an And or Or. 6147 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6148 if (BO->getOpcode() == Instruction::And) { 6149 // Recurse on the operands of the and. 6150 bool EitherMayExit = L->contains(TBB); 6151 ExitLimit EL0 = computeExitLimitFromCondCached( 6152 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6153 AllowPredicates); 6154 ExitLimit EL1 = computeExitLimitFromCondCached( 6155 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6156 AllowPredicates); 6157 const SCEV *BECount = getCouldNotCompute(); 6158 const SCEV *MaxBECount = getCouldNotCompute(); 6159 if (EitherMayExit) { 6160 // Both conditions must be true for the loop to continue executing. 6161 // Choose the less conservative count. 6162 if (EL0.ExactNotTaken == getCouldNotCompute() || 6163 EL1.ExactNotTaken == getCouldNotCompute()) 6164 BECount = getCouldNotCompute(); 6165 else 6166 BECount = 6167 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6168 if (EL0.MaxNotTaken == getCouldNotCompute()) 6169 MaxBECount = EL1.MaxNotTaken; 6170 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6171 MaxBECount = EL0.MaxNotTaken; 6172 else 6173 MaxBECount = 6174 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6175 } else { 6176 // Both conditions must be true at the same time for the loop to exit. 6177 // For now, be conservative. 6178 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6179 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6180 MaxBECount = EL0.MaxNotTaken; 6181 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6182 BECount = EL0.ExactNotTaken; 6183 } 6184 6185 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6186 // to be more aggressive when computing BECount than when computing 6187 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6188 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6189 // to not. 6190 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6191 !isa<SCEVCouldNotCompute>(BECount)) 6192 MaxBECount = BECount; 6193 6194 return ExitLimit(BECount, MaxBECount, false, 6195 {&EL0.Predicates, &EL1.Predicates}); 6196 } 6197 if (BO->getOpcode() == Instruction::Or) { 6198 // Recurse on the operands of the or. 6199 bool EitherMayExit = L->contains(FBB); 6200 ExitLimit EL0 = computeExitLimitFromCondCached( 6201 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6202 AllowPredicates); 6203 ExitLimit EL1 = computeExitLimitFromCondCached( 6204 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6205 AllowPredicates); 6206 const SCEV *BECount = getCouldNotCompute(); 6207 const SCEV *MaxBECount = getCouldNotCompute(); 6208 if (EitherMayExit) { 6209 // Both conditions must be false for the loop to continue executing. 6210 // Choose the less conservative count. 6211 if (EL0.ExactNotTaken == getCouldNotCompute() || 6212 EL1.ExactNotTaken == getCouldNotCompute()) 6213 BECount = getCouldNotCompute(); 6214 else 6215 BECount = 6216 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6217 if (EL0.MaxNotTaken == getCouldNotCompute()) 6218 MaxBECount = EL1.MaxNotTaken; 6219 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6220 MaxBECount = EL0.MaxNotTaken; 6221 else 6222 MaxBECount = 6223 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6224 } else { 6225 // Both conditions must be false at the same time for the loop to exit. 6226 // For now, be conservative. 6227 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6228 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6229 MaxBECount = EL0.MaxNotTaken; 6230 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6231 BECount = EL0.ExactNotTaken; 6232 } 6233 6234 return ExitLimit(BECount, MaxBECount, false, 6235 {&EL0.Predicates, &EL1.Predicates}); 6236 } 6237 } 6238 6239 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6240 // Proceed to the next level to examine the icmp. 6241 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6242 ExitLimit EL = 6243 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6244 if (EL.hasFullInfo() || !AllowPredicates) 6245 return EL; 6246 6247 // Try again, but use SCEV predicates this time. 6248 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6249 /*AllowPredicates=*/true); 6250 } 6251 6252 // Check for a constant condition. These are normally stripped out by 6253 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6254 // preserve the CFG and is temporarily leaving constant conditions 6255 // in place. 6256 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6257 if (L->contains(FBB) == !CI->getZExtValue()) 6258 // The backedge is always taken. 6259 return getCouldNotCompute(); 6260 else 6261 // The backedge is never taken. 6262 return getZero(CI->getType()); 6263 } 6264 6265 // If it's not an integer or pointer comparison then compute it the hard way. 6266 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6267 } 6268 6269 ScalarEvolution::ExitLimit 6270 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6271 ICmpInst *ExitCond, 6272 BasicBlock *TBB, 6273 BasicBlock *FBB, 6274 bool ControlsExit, 6275 bool AllowPredicates) { 6276 6277 // If the condition was exit on true, convert the condition to exit on false 6278 ICmpInst::Predicate Cond; 6279 if (!L->contains(FBB)) 6280 Cond = ExitCond->getPredicate(); 6281 else 6282 Cond = ExitCond->getInversePredicate(); 6283 6284 // Handle common loops like: for (X = "string"; *X; ++X) 6285 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6286 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6287 ExitLimit ItCnt = 6288 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6289 if (ItCnt.hasAnyInfo()) 6290 return ItCnt; 6291 } 6292 6293 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6294 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6295 6296 // Try to evaluate any dependencies out of the loop. 6297 LHS = getSCEVAtScope(LHS, L); 6298 RHS = getSCEVAtScope(RHS, L); 6299 6300 // At this point, we would like to compute how many iterations of the 6301 // loop the predicate will return true for these inputs. 6302 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6303 // If there is a loop-invariant, force it into the RHS. 6304 std::swap(LHS, RHS); 6305 Cond = ICmpInst::getSwappedPredicate(Cond); 6306 } 6307 6308 // Simplify the operands before analyzing them. 6309 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6310 6311 // If we have a comparison of a chrec against a constant, try to use value 6312 // ranges to answer this query. 6313 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6314 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6315 if (AddRec->getLoop() == L) { 6316 // Form the constant range. 6317 ConstantRange CompRange = 6318 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6319 6320 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6321 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6322 } 6323 6324 switch (Cond) { 6325 case ICmpInst::ICMP_NE: { // while (X != Y) 6326 // Convert to: while (X-Y != 0) 6327 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6328 AllowPredicates); 6329 if (EL.hasAnyInfo()) return EL; 6330 break; 6331 } 6332 case ICmpInst::ICMP_EQ: { // while (X == Y) 6333 // Convert to: while (X-Y == 0) 6334 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6335 if (EL.hasAnyInfo()) return EL; 6336 break; 6337 } 6338 case ICmpInst::ICMP_SLT: 6339 case ICmpInst::ICMP_ULT: { // while (X < Y) 6340 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6341 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6342 AllowPredicates); 6343 if (EL.hasAnyInfo()) return EL; 6344 break; 6345 } 6346 case ICmpInst::ICMP_SGT: 6347 case ICmpInst::ICMP_UGT: { // while (X > Y) 6348 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6349 ExitLimit EL = 6350 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6351 AllowPredicates); 6352 if (EL.hasAnyInfo()) return EL; 6353 break; 6354 } 6355 default: 6356 break; 6357 } 6358 6359 auto *ExhaustiveCount = 6360 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6361 6362 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6363 return ExhaustiveCount; 6364 6365 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6366 ExitCond->getOperand(1), L, Cond); 6367 } 6368 6369 ScalarEvolution::ExitLimit 6370 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6371 SwitchInst *Switch, 6372 BasicBlock *ExitingBlock, 6373 bool ControlsExit) { 6374 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6375 6376 // Give up if the exit is the default dest of a switch. 6377 if (Switch->getDefaultDest() == ExitingBlock) 6378 return getCouldNotCompute(); 6379 6380 assert(L->contains(Switch->getDefaultDest()) && 6381 "Default case must not exit the loop!"); 6382 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6383 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6384 6385 // while (X != Y) --> while (X-Y != 0) 6386 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6387 if (EL.hasAnyInfo()) 6388 return EL; 6389 6390 return getCouldNotCompute(); 6391 } 6392 6393 static ConstantInt * 6394 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6395 ScalarEvolution &SE) { 6396 const SCEV *InVal = SE.getConstant(C); 6397 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6398 assert(isa<SCEVConstant>(Val) && 6399 "Evaluation of SCEV at constant didn't fold correctly?"); 6400 return cast<SCEVConstant>(Val)->getValue(); 6401 } 6402 6403 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6404 /// compute the backedge execution count. 6405 ScalarEvolution::ExitLimit 6406 ScalarEvolution::computeLoadConstantCompareExitLimit( 6407 LoadInst *LI, 6408 Constant *RHS, 6409 const Loop *L, 6410 ICmpInst::Predicate predicate) { 6411 6412 if (LI->isVolatile()) return getCouldNotCompute(); 6413 6414 // Check to see if the loaded pointer is a getelementptr of a global. 6415 // TODO: Use SCEV instead of manually grubbing with GEPs. 6416 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6417 if (!GEP) return getCouldNotCompute(); 6418 6419 // Make sure that it is really a constant global we are gepping, with an 6420 // initializer, and make sure the first IDX is really 0. 6421 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6422 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6423 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6424 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6425 return getCouldNotCompute(); 6426 6427 // Okay, we allow one non-constant index into the GEP instruction. 6428 Value *VarIdx = nullptr; 6429 std::vector<Constant*> Indexes; 6430 unsigned VarIdxNum = 0; 6431 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6432 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6433 Indexes.push_back(CI); 6434 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6435 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6436 VarIdx = GEP->getOperand(i); 6437 VarIdxNum = i-2; 6438 Indexes.push_back(nullptr); 6439 } 6440 6441 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6442 if (!VarIdx) 6443 return getCouldNotCompute(); 6444 6445 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6446 // Check to see if X is a loop variant variable value now. 6447 const SCEV *Idx = getSCEV(VarIdx); 6448 Idx = getSCEVAtScope(Idx, L); 6449 6450 // We can only recognize very limited forms of loop index expressions, in 6451 // particular, only affine AddRec's like {C1,+,C2}. 6452 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6453 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6454 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6455 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6456 return getCouldNotCompute(); 6457 6458 unsigned MaxSteps = MaxBruteForceIterations; 6459 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6460 ConstantInt *ItCst = ConstantInt::get( 6461 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6462 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6463 6464 // Form the GEP offset. 6465 Indexes[VarIdxNum] = Val; 6466 6467 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6468 Indexes); 6469 if (!Result) break; // Cannot compute! 6470 6471 // Evaluate the condition for this iteration. 6472 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6473 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6474 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6475 ++NumArrayLenItCounts; 6476 return getConstant(ItCst); // Found terminating iteration! 6477 } 6478 } 6479 return getCouldNotCompute(); 6480 } 6481 6482 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6483 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6484 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6485 if (!RHS) 6486 return getCouldNotCompute(); 6487 6488 const BasicBlock *Latch = L->getLoopLatch(); 6489 if (!Latch) 6490 return getCouldNotCompute(); 6491 6492 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6493 if (!Predecessor) 6494 return getCouldNotCompute(); 6495 6496 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6497 // Return LHS in OutLHS and shift_opt in OutOpCode. 6498 auto MatchPositiveShift = 6499 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6500 6501 using namespace PatternMatch; 6502 6503 ConstantInt *ShiftAmt; 6504 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6505 OutOpCode = Instruction::LShr; 6506 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6507 OutOpCode = Instruction::AShr; 6508 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6509 OutOpCode = Instruction::Shl; 6510 else 6511 return false; 6512 6513 return ShiftAmt->getValue().isStrictlyPositive(); 6514 }; 6515 6516 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6517 // 6518 // loop: 6519 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6520 // %iv.shifted = lshr i32 %iv, <positive constant> 6521 // 6522 // Return true on a successful match. Return the corresponding PHI node (%iv 6523 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6524 auto MatchShiftRecurrence = 6525 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6526 Optional<Instruction::BinaryOps> PostShiftOpCode; 6527 6528 { 6529 Instruction::BinaryOps OpC; 6530 Value *V; 6531 6532 // If we encounter a shift instruction, "peel off" the shift operation, 6533 // and remember that we did so. Later when we inspect %iv's backedge 6534 // value, we will make sure that the backedge value uses the same 6535 // operation. 6536 // 6537 // Note: the peeled shift operation does not have to be the same 6538 // instruction as the one feeding into the PHI's backedge value. We only 6539 // really care about it being the same *kind* of shift instruction -- 6540 // that's all that is required for our later inferences to hold. 6541 if (MatchPositiveShift(LHS, V, OpC)) { 6542 PostShiftOpCode = OpC; 6543 LHS = V; 6544 } 6545 } 6546 6547 PNOut = dyn_cast<PHINode>(LHS); 6548 if (!PNOut || PNOut->getParent() != L->getHeader()) 6549 return false; 6550 6551 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6552 Value *OpLHS; 6553 6554 return 6555 // The backedge value for the PHI node must be a shift by a positive 6556 // amount 6557 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6558 6559 // of the PHI node itself 6560 OpLHS == PNOut && 6561 6562 // and the kind of shift should be match the kind of shift we peeled 6563 // off, if any. 6564 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6565 }; 6566 6567 PHINode *PN; 6568 Instruction::BinaryOps OpCode; 6569 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6570 return getCouldNotCompute(); 6571 6572 const DataLayout &DL = getDataLayout(); 6573 6574 // The key rationale for this optimization is that for some kinds of shift 6575 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6576 // within a finite number of iterations. If the condition guarding the 6577 // backedge (in the sense that the backedge is taken if the condition is true) 6578 // is false for the value the shift recurrence stabilizes to, then we know 6579 // that the backedge is taken only a finite number of times. 6580 6581 ConstantInt *StableValue = nullptr; 6582 switch (OpCode) { 6583 default: 6584 llvm_unreachable("Impossible case!"); 6585 6586 case Instruction::AShr: { 6587 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6588 // bitwidth(K) iterations. 6589 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6590 bool KnownZero, KnownOne; 6591 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6592 Predecessor->getTerminator(), &DT); 6593 auto *Ty = cast<IntegerType>(RHS->getType()); 6594 if (KnownZero) 6595 StableValue = ConstantInt::get(Ty, 0); 6596 else if (KnownOne) 6597 StableValue = ConstantInt::get(Ty, -1, true); 6598 else 6599 return getCouldNotCompute(); 6600 6601 break; 6602 } 6603 case Instruction::LShr: 6604 case Instruction::Shl: 6605 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6606 // stabilize to 0 in at most bitwidth(K) iterations. 6607 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6608 break; 6609 } 6610 6611 auto *Result = 6612 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6613 assert(Result->getType()->isIntegerTy(1) && 6614 "Otherwise cannot be an operand to a branch instruction"); 6615 6616 if (Result->isZeroValue()) { 6617 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6618 const SCEV *UpperBound = 6619 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6620 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6621 } 6622 6623 return getCouldNotCompute(); 6624 } 6625 6626 /// Return true if we can constant fold an instruction of the specified type, 6627 /// assuming that all operands were constants. 6628 static bool CanConstantFold(const Instruction *I) { 6629 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6630 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6631 isa<LoadInst>(I)) 6632 return true; 6633 6634 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6635 if (const Function *F = CI->getCalledFunction()) 6636 return canConstantFoldCallTo(F); 6637 return false; 6638 } 6639 6640 /// Determine whether this instruction can constant evolve within this loop 6641 /// assuming its operands can all constant evolve. 6642 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6643 // An instruction outside of the loop can't be derived from a loop PHI. 6644 if (!L->contains(I)) return false; 6645 6646 if (isa<PHINode>(I)) { 6647 // We don't currently keep track of the control flow needed to evaluate 6648 // PHIs, so we cannot handle PHIs inside of loops. 6649 return L->getHeader() == I->getParent(); 6650 } 6651 6652 // If we won't be able to constant fold this expression even if the operands 6653 // are constants, bail early. 6654 return CanConstantFold(I); 6655 } 6656 6657 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6658 /// recursing through each instruction operand until reaching a loop header phi. 6659 static PHINode * 6660 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6661 DenseMap<Instruction *, PHINode *> &PHIMap, 6662 unsigned Depth) { 6663 if (Depth > MaxConstantEvolvingDepth) 6664 return nullptr; 6665 6666 // Otherwise, we can evaluate this instruction if all of its operands are 6667 // constant or derived from a PHI node themselves. 6668 PHINode *PHI = nullptr; 6669 for (Value *Op : UseInst->operands()) { 6670 if (isa<Constant>(Op)) continue; 6671 6672 Instruction *OpInst = dyn_cast<Instruction>(Op); 6673 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6674 6675 PHINode *P = dyn_cast<PHINode>(OpInst); 6676 if (!P) 6677 // If this operand is already visited, reuse the prior result. 6678 // We may have P != PHI if this is the deepest point at which the 6679 // inconsistent paths meet. 6680 P = PHIMap.lookup(OpInst); 6681 if (!P) { 6682 // Recurse and memoize the results, whether a phi is found or not. 6683 // This recursive call invalidates pointers into PHIMap. 6684 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 6685 PHIMap[OpInst] = P; 6686 } 6687 if (!P) 6688 return nullptr; // Not evolving from PHI 6689 if (PHI && PHI != P) 6690 return nullptr; // Evolving from multiple different PHIs. 6691 PHI = P; 6692 } 6693 // This is a expression evolving from a constant PHI! 6694 return PHI; 6695 } 6696 6697 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6698 /// in the loop that V is derived from. We allow arbitrary operations along the 6699 /// way, but the operands of an operation must either be constants or a value 6700 /// derived from a constant PHI. If this expression does not fit with these 6701 /// constraints, return null. 6702 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6703 Instruction *I = dyn_cast<Instruction>(V); 6704 if (!I || !canConstantEvolve(I, L)) return nullptr; 6705 6706 if (PHINode *PN = dyn_cast<PHINode>(I)) 6707 return PN; 6708 6709 // Record non-constant instructions contained by the loop. 6710 DenseMap<Instruction *, PHINode *> PHIMap; 6711 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 6712 } 6713 6714 /// EvaluateExpression - Given an expression that passes the 6715 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6716 /// in the loop has the value PHIVal. If we can't fold this expression for some 6717 /// reason, return null. 6718 static Constant *EvaluateExpression(Value *V, const Loop *L, 6719 DenseMap<Instruction *, Constant *> &Vals, 6720 const DataLayout &DL, 6721 const TargetLibraryInfo *TLI) { 6722 // Convenient constant check, but redundant for recursive calls. 6723 if (Constant *C = dyn_cast<Constant>(V)) return C; 6724 Instruction *I = dyn_cast<Instruction>(V); 6725 if (!I) return nullptr; 6726 6727 if (Constant *C = Vals.lookup(I)) return C; 6728 6729 // An instruction inside the loop depends on a value outside the loop that we 6730 // weren't given a mapping for, or a value such as a call inside the loop. 6731 if (!canConstantEvolve(I, L)) return nullptr; 6732 6733 // An unmapped PHI can be due to a branch or another loop inside this loop, 6734 // or due to this not being the initial iteration through a loop where we 6735 // couldn't compute the evolution of this particular PHI last time. 6736 if (isa<PHINode>(I)) return nullptr; 6737 6738 std::vector<Constant*> Operands(I->getNumOperands()); 6739 6740 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6741 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6742 if (!Operand) { 6743 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6744 if (!Operands[i]) return nullptr; 6745 continue; 6746 } 6747 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6748 Vals[Operand] = C; 6749 if (!C) return nullptr; 6750 Operands[i] = C; 6751 } 6752 6753 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6754 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6755 Operands[1], DL, TLI); 6756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6757 if (!LI->isVolatile()) 6758 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6759 } 6760 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6761 } 6762 6763 6764 // If every incoming value to PN except the one for BB is a specific Constant, 6765 // return that, else return nullptr. 6766 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6767 Constant *IncomingVal = nullptr; 6768 6769 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6770 if (PN->getIncomingBlock(i) == BB) 6771 continue; 6772 6773 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6774 if (!CurrentVal) 6775 return nullptr; 6776 6777 if (IncomingVal != CurrentVal) { 6778 if (IncomingVal) 6779 return nullptr; 6780 IncomingVal = CurrentVal; 6781 } 6782 } 6783 6784 return IncomingVal; 6785 } 6786 6787 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6788 /// in the header of its containing loop, we know the loop executes a 6789 /// constant number of times, and the PHI node is just a recurrence 6790 /// involving constants, fold it. 6791 Constant * 6792 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6793 const APInt &BEs, 6794 const Loop *L) { 6795 auto I = ConstantEvolutionLoopExitValue.find(PN); 6796 if (I != ConstantEvolutionLoopExitValue.end()) 6797 return I->second; 6798 6799 if (BEs.ugt(MaxBruteForceIterations)) 6800 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6801 6802 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6803 6804 DenseMap<Instruction *, Constant *> CurrentIterVals; 6805 BasicBlock *Header = L->getHeader(); 6806 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6807 6808 BasicBlock *Latch = L->getLoopLatch(); 6809 if (!Latch) 6810 return nullptr; 6811 6812 for (auto &I : *Header) { 6813 PHINode *PHI = dyn_cast<PHINode>(&I); 6814 if (!PHI) break; 6815 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6816 if (!StartCST) continue; 6817 CurrentIterVals[PHI] = StartCST; 6818 } 6819 if (!CurrentIterVals.count(PN)) 6820 return RetVal = nullptr; 6821 6822 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6823 6824 // Execute the loop symbolically to determine the exit value. 6825 if (BEs.getActiveBits() >= 32) 6826 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6827 6828 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6829 unsigned IterationNum = 0; 6830 const DataLayout &DL = getDataLayout(); 6831 for (; ; ++IterationNum) { 6832 if (IterationNum == NumIterations) 6833 return RetVal = CurrentIterVals[PN]; // Got exit value! 6834 6835 // Compute the value of the PHIs for the next iteration. 6836 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6837 DenseMap<Instruction *, Constant *> NextIterVals; 6838 Constant *NextPHI = 6839 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6840 if (!NextPHI) 6841 return nullptr; // Couldn't evaluate! 6842 NextIterVals[PN] = NextPHI; 6843 6844 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6845 6846 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6847 // cease to be able to evaluate one of them or if they stop evolving, 6848 // because that doesn't necessarily prevent us from computing PN. 6849 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6850 for (const auto &I : CurrentIterVals) { 6851 PHINode *PHI = dyn_cast<PHINode>(I.first); 6852 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6853 PHIsToCompute.emplace_back(PHI, I.second); 6854 } 6855 // We use two distinct loops because EvaluateExpression may invalidate any 6856 // iterators into CurrentIterVals. 6857 for (const auto &I : PHIsToCompute) { 6858 PHINode *PHI = I.first; 6859 Constant *&NextPHI = NextIterVals[PHI]; 6860 if (!NextPHI) { // Not already computed. 6861 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6862 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6863 } 6864 if (NextPHI != I.second) 6865 StoppedEvolving = false; 6866 } 6867 6868 // If all entries in CurrentIterVals == NextIterVals then we can stop 6869 // iterating, the loop can't continue to change. 6870 if (StoppedEvolving) 6871 return RetVal = CurrentIterVals[PN]; 6872 6873 CurrentIterVals.swap(NextIterVals); 6874 } 6875 } 6876 6877 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6878 Value *Cond, 6879 bool ExitWhen) { 6880 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6881 if (!PN) return getCouldNotCompute(); 6882 6883 // If the loop is canonicalized, the PHI will have exactly two entries. 6884 // That's the only form we support here. 6885 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6886 6887 DenseMap<Instruction *, Constant *> CurrentIterVals; 6888 BasicBlock *Header = L->getHeader(); 6889 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6890 6891 BasicBlock *Latch = L->getLoopLatch(); 6892 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6893 6894 for (auto &I : *Header) { 6895 PHINode *PHI = dyn_cast<PHINode>(&I); 6896 if (!PHI) 6897 break; 6898 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6899 if (!StartCST) continue; 6900 CurrentIterVals[PHI] = StartCST; 6901 } 6902 if (!CurrentIterVals.count(PN)) 6903 return getCouldNotCompute(); 6904 6905 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6906 // the loop symbolically to determine when the condition gets a value of 6907 // "ExitWhen". 6908 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6909 const DataLayout &DL = getDataLayout(); 6910 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6911 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6912 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6913 6914 // Couldn't symbolically evaluate. 6915 if (!CondVal) return getCouldNotCompute(); 6916 6917 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6918 ++NumBruteForceTripCountsComputed; 6919 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6920 } 6921 6922 // Update all the PHI nodes for the next iteration. 6923 DenseMap<Instruction *, Constant *> NextIterVals; 6924 6925 // Create a list of which PHIs we need to compute. We want to do this before 6926 // calling EvaluateExpression on them because that may invalidate iterators 6927 // into CurrentIterVals. 6928 SmallVector<PHINode *, 8> PHIsToCompute; 6929 for (const auto &I : CurrentIterVals) { 6930 PHINode *PHI = dyn_cast<PHINode>(I.first); 6931 if (!PHI || PHI->getParent() != Header) continue; 6932 PHIsToCompute.push_back(PHI); 6933 } 6934 for (PHINode *PHI : PHIsToCompute) { 6935 Constant *&NextPHI = NextIterVals[PHI]; 6936 if (NextPHI) continue; // Already computed! 6937 6938 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6939 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6940 } 6941 CurrentIterVals.swap(NextIterVals); 6942 } 6943 6944 // Too many iterations were needed to evaluate. 6945 return getCouldNotCompute(); 6946 } 6947 6948 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6949 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6950 ValuesAtScopes[V]; 6951 // Check to see if we've folded this expression at this loop before. 6952 for (auto &LS : Values) 6953 if (LS.first == L) 6954 return LS.second ? LS.second : V; 6955 6956 Values.emplace_back(L, nullptr); 6957 6958 // Otherwise compute it. 6959 const SCEV *C = computeSCEVAtScope(V, L); 6960 for (auto &LS : reverse(ValuesAtScopes[V])) 6961 if (LS.first == L) { 6962 LS.second = C; 6963 break; 6964 } 6965 return C; 6966 } 6967 6968 /// This builds up a Constant using the ConstantExpr interface. That way, we 6969 /// will return Constants for objects which aren't represented by a 6970 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6971 /// Returns NULL if the SCEV isn't representable as a Constant. 6972 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6973 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6974 case scCouldNotCompute: 6975 case scAddRecExpr: 6976 break; 6977 case scConstant: 6978 return cast<SCEVConstant>(V)->getValue(); 6979 case scUnknown: 6980 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6981 case scSignExtend: { 6982 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6983 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6984 return ConstantExpr::getSExt(CastOp, SS->getType()); 6985 break; 6986 } 6987 case scZeroExtend: { 6988 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6989 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6990 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6991 break; 6992 } 6993 case scTruncate: { 6994 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6995 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6996 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6997 break; 6998 } 6999 case scAddExpr: { 7000 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7001 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7002 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7003 unsigned AS = PTy->getAddressSpace(); 7004 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7005 C = ConstantExpr::getBitCast(C, DestPtrTy); 7006 } 7007 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7008 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7009 if (!C2) return nullptr; 7010 7011 // First pointer! 7012 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7013 unsigned AS = C2->getType()->getPointerAddressSpace(); 7014 std::swap(C, C2); 7015 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7016 // The offsets have been converted to bytes. We can add bytes to an 7017 // i8* by GEP with the byte count in the first index. 7018 C = ConstantExpr::getBitCast(C, DestPtrTy); 7019 } 7020 7021 // Don't bother trying to sum two pointers. We probably can't 7022 // statically compute a load that results from it anyway. 7023 if (C2->getType()->isPointerTy()) 7024 return nullptr; 7025 7026 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7027 if (PTy->getElementType()->isStructTy()) 7028 C2 = ConstantExpr::getIntegerCast( 7029 C2, Type::getInt32Ty(C->getContext()), true); 7030 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7031 } else 7032 C = ConstantExpr::getAdd(C, C2); 7033 } 7034 return C; 7035 } 7036 break; 7037 } 7038 case scMulExpr: { 7039 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7040 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7041 // Don't bother with pointers at all. 7042 if (C->getType()->isPointerTy()) return nullptr; 7043 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7044 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7045 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7046 C = ConstantExpr::getMul(C, C2); 7047 } 7048 return C; 7049 } 7050 break; 7051 } 7052 case scUDivExpr: { 7053 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7054 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7055 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7056 if (LHS->getType() == RHS->getType()) 7057 return ConstantExpr::getUDiv(LHS, RHS); 7058 break; 7059 } 7060 case scSMaxExpr: 7061 case scUMaxExpr: 7062 break; // TODO: smax, umax. 7063 } 7064 return nullptr; 7065 } 7066 7067 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7068 if (isa<SCEVConstant>(V)) return V; 7069 7070 // If this instruction is evolved from a constant-evolving PHI, compute the 7071 // exit value from the loop without using SCEVs. 7072 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7073 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7074 const Loop *LI = this->LI[I->getParent()]; 7075 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7076 if (PHINode *PN = dyn_cast<PHINode>(I)) 7077 if (PN->getParent() == LI->getHeader()) { 7078 // Okay, there is no closed form solution for the PHI node. Check 7079 // to see if the loop that contains it has a known backedge-taken 7080 // count. If so, we may be able to force computation of the exit 7081 // value. 7082 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7083 if (const SCEVConstant *BTCC = 7084 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7085 // Okay, we know how many times the containing loop executes. If 7086 // this is a constant evolving PHI node, get the final value at 7087 // the specified iteration number. 7088 Constant *RV = 7089 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7090 if (RV) return getSCEV(RV); 7091 } 7092 } 7093 7094 // Okay, this is an expression that we cannot symbolically evaluate 7095 // into a SCEV. Check to see if it's possible to symbolically evaluate 7096 // the arguments into constants, and if so, try to constant propagate the 7097 // result. This is particularly useful for computing loop exit values. 7098 if (CanConstantFold(I)) { 7099 SmallVector<Constant *, 4> Operands; 7100 bool MadeImprovement = false; 7101 for (Value *Op : I->operands()) { 7102 if (Constant *C = dyn_cast<Constant>(Op)) { 7103 Operands.push_back(C); 7104 continue; 7105 } 7106 7107 // If any of the operands is non-constant and if they are 7108 // non-integer and non-pointer, don't even try to analyze them 7109 // with scev techniques. 7110 if (!isSCEVable(Op->getType())) 7111 return V; 7112 7113 const SCEV *OrigV = getSCEV(Op); 7114 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7115 MadeImprovement |= OrigV != OpV; 7116 7117 Constant *C = BuildConstantFromSCEV(OpV); 7118 if (!C) return V; 7119 if (C->getType() != Op->getType()) 7120 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7121 Op->getType(), 7122 false), 7123 C, Op->getType()); 7124 Operands.push_back(C); 7125 } 7126 7127 // Check to see if getSCEVAtScope actually made an improvement. 7128 if (MadeImprovement) { 7129 Constant *C = nullptr; 7130 const DataLayout &DL = getDataLayout(); 7131 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7132 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7133 Operands[1], DL, &TLI); 7134 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7135 if (!LI->isVolatile()) 7136 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7137 } else 7138 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7139 if (!C) return V; 7140 return getSCEV(C); 7141 } 7142 } 7143 } 7144 7145 // This is some other type of SCEVUnknown, just return it. 7146 return V; 7147 } 7148 7149 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7150 // Avoid performing the look-up in the common case where the specified 7151 // expression has no loop-variant portions. 7152 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7153 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7154 if (OpAtScope != Comm->getOperand(i)) { 7155 // Okay, at least one of these operands is loop variant but might be 7156 // foldable. Build a new instance of the folded commutative expression. 7157 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7158 Comm->op_begin()+i); 7159 NewOps.push_back(OpAtScope); 7160 7161 for (++i; i != e; ++i) { 7162 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7163 NewOps.push_back(OpAtScope); 7164 } 7165 if (isa<SCEVAddExpr>(Comm)) 7166 return getAddExpr(NewOps); 7167 if (isa<SCEVMulExpr>(Comm)) 7168 return getMulExpr(NewOps); 7169 if (isa<SCEVSMaxExpr>(Comm)) 7170 return getSMaxExpr(NewOps); 7171 if (isa<SCEVUMaxExpr>(Comm)) 7172 return getUMaxExpr(NewOps); 7173 llvm_unreachable("Unknown commutative SCEV type!"); 7174 } 7175 } 7176 // If we got here, all operands are loop invariant. 7177 return Comm; 7178 } 7179 7180 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7181 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7182 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7183 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7184 return Div; // must be loop invariant 7185 return getUDivExpr(LHS, RHS); 7186 } 7187 7188 // If this is a loop recurrence for a loop that does not contain L, then we 7189 // are dealing with the final value computed by the loop. 7190 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7191 // First, attempt to evaluate each operand. 7192 // Avoid performing the look-up in the common case where the specified 7193 // expression has no loop-variant portions. 7194 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7195 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7196 if (OpAtScope == AddRec->getOperand(i)) 7197 continue; 7198 7199 // Okay, at least one of these operands is loop variant but might be 7200 // foldable. Build a new instance of the folded commutative expression. 7201 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7202 AddRec->op_begin()+i); 7203 NewOps.push_back(OpAtScope); 7204 for (++i; i != e; ++i) 7205 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7206 7207 const SCEV *FoldedRec = 7208 getAddRecExpr(NewOps, AddRec->getLoop(), 7209 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7210 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7211 // The addrec may be folded to a nonrecurrence, for example, if the 7212 // induction variable is multiplied by zero after constant folding. Go 7213 // ahead and return the folded value. 7214 if (!AddRec) 7215 return FoldedRec; 7216 break; 7217 } 7218 7219 // If the scope is outside the addrec's loop, evaluate it by using the 7220 // loop exit value of the addrec. 7221 if (!AddRec->getLoop()->contains(L)) { 7222 // To evaluate this recurrence, we need to know how many times the AddRec 7223 // loop iterates. Compute this now. 7224 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7225 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7226 7227 // Then, evaluate the AddRec. 7228 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7229 } 7230 7231 return AddRec; 7232 } 7233 7234 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7235 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7236 if (Op == Cast->getOperand()) 7237 return Cast; // must be loop invariant 7238 return getZeroExtendExpr(Op, Cast->getType()); 7239 } 7240 7241 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7242 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7243 if (Op == Cast->getOperand()) 7244 return Cast; // must be loop invariant 7245 return getSignExtendExpr(Op, Cast->getType()); 7246 } 7247 7248 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7249 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7250 if (Op == Cast->getOperand()) 7251 return Cast; // must be loop invariant 7252 return getTruncateExpr(Op, Cast->getType()); 7253 } 7254 7255 llvm_unreachable("Unknown SCEV type!"); 7256 } 7257 7258 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7259 return getSCEVAtScope(getSCEV(V), L); 7260 } 7261 7262 /// Finds the minimum unsigned root of the following equation: 7263 /// 7264 /// A * X = B (mod N) 7265 /// 7266 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7267 /// A and B isn't important. 7268 /// 7269 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7270 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7271 ScalarEvolution &SE) { 7272 uint32_t BW = A.getBitWidth(); 7273 assert(BW == SE.getTypeSizeInBits(B->getType())); 7274 assert(A != 0 && "A must be non-zero."); 7275 7276 // 1. D = gcd(A, N) 7277 // 7278 // The gcd of A and N may have only one prime factor: 2. The number of 7279 // trailing zeros in A is its multiplicity 7280 uint32_t Mult2 = A.countTrailingZeros(); 7281 // D = 2^Mult2 7282 7283 // 2. Check if B is divisible by D. 7284 // 7285 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7286 // is not less than multiplicity of this prime factor for D. 7287 if (SE.GetMinTrailingZeros(B) < Mult2) 7288 return SE.getCouldNotCompute(); 7289 7290 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7291 // modulo (N / D). 7292 // 7293 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7294 // (N / D) in general. The inverse itself always fits into BW bits, though, 7295 // so we immediately truncate it. 7296 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7297 APInt Mod(BW + 1, 0); 7298 Mod.setBit(BW - Mult2); // Mod = N / D 7299 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7300 7301 // 4. Compute the minimum unsigned root of the equation: 7302 // I * (B / D) mod (N / D) 7303 // To simplify the computation, we factor out the divide by D: 7304 // (I * B mod N) / D 7305 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7306 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7307 } 7308 7309 /// Find the roots of the quadratic equation for the given quadratic chrec 7310 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7311 /// two SCEVCouldNotCompute objects. 7312 /// 7313 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7314 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7315 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7316 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7317 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7318 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7319 7320 // We currently can only solve this if the coefficients are constants. 7321 if (!LC || !MC || !NC) 7322 return None; 7323 7324 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7325 const APInt &L = LC->getAPInt(); 7326 const APInt &M = MC->getAPInt(); 7327 const APInt &N = NC->getAPInt(); 7328 APInt Two(BitWidth, 2); 7329 APInt Four(BitWidth, 4); 7330 7331 { 7332 using namespace APIntOps; 7333 const APInt& C = L; 7334 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7335 // The B coefficient is M-N/2 7336 APInt B(M); 7337 B -= N.sdiv(Two); 7338 7339 // The A coefficient is N/2 7340 APInt A(N.sdiv(Two)); 7341 7342 // Compute the B^2-4ac term. 7343 APInt SqrtTerm(B); 7344 SqrtTerm *= B; 7345 SqrtTerm -= Four * (A * C); 7346 7347 if (SqrtTerm.isNegative()) { 7348 // The loop is provably infinite. 7349 return None; 7350 } 7351 7352 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7353 // integer value or else APInt::sqrt() will assert. 7354 APInt SqrtVal(SqrtTerm.sqrt()); 7355 7356 // Compute the two solutions for the quadratic formula. 7357 // The divisions must be performed as signed divisions. 7358 APInt NegB(-B); 7359 APInt TwoA(A << 1); 7360 if (TwoA.isMinValue()) 7361 return None; 7362 7363 LLVMContext &Context = SE.getContext(); 7364 7365 ConstantInt *Solution1 = 7366 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7367 ConstantInt *Solution2 = 7368 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7369 7370 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7371 cast<SCEVConstant>(SE.getConstant(Solution2))); 7372 } // end APIntOps namespace 7373 } 7374 7375 ScalarEvolution::ExitLimit 7376 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7377 bool AllowPredicates) { 7378 7379 // This is only used for loops with a "x != y" exit test. The exit condition 7380 // is now expressed as a single expression, V = x-y. So the exit test is 7381 // effectively V != 0. We know and take advantage of the fact that this 7382 // expression only being used in a comparison by zero context. 7383 7384 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7385 // If the value is a constant 7386 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7387 // If the value is already zero, the branch will execute zero times. 7388 if (C->getValue()->isZero()) return C; 7389 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7390 } 7391 7392 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7393 if (!AddRec && AllowPredicates) 7394 // Try to make this an AddRec using runtime tests, in the first X 7395 // iterations of this loop, where X is the SCEV expression found by the 7396 // algorithm below. 7397 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7398 7399 if (!AddRec || AddRec->getLoop() != L) 7400 return getCouldNotCompute(); 7401 7402 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7403 // the quadratic equation to solve it. 7404 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7405 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7406 const SCEVConstant *R1 = Roots->first; 7407 const SCEVConstant *R2 = Roots->second; 7408 // Pick the smallest positive root value. 7409 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7410 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7411 if (!CB->getZExtValue()) 7412 std::swap(R1, R2); // R1 is the minimum root now. 7413 7414 // We can only use this value if the chrec ends up with an exact zero 7415 // value at this index. When solving for "X*X != 5", for example, we 7416 // should not accept a root of 2. 7417 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7418 if (Val->isZero()) 7419 // We found a quadratic root! 7420 return ExitLimit(R1, R1, false, Predicates); 7421 } 7422 } 7423 return getCouldNotCompute(); 7424 } 7425 7426 // Otherwise we can only handle this if it is affine. 7427 if (!AddRec->isAffine()) 7428 return getCouldNotCompute(); 7429 7430 // If this is an affine expression, the execution count of this branch is 7431 // the minimum unsigned root of the following equation: 7432 // 7433 // Start + Step*N = 0 (mod 2^BW) 7434 // 7435 // equivalent to: 7436 // 7437 // Step*N = -Start (mod 2^BW) 7438 // 7439 // where BW is the common bit width of Start and Step. 7440 7441 // Get the initial value for the loop. 7442 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7443 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7444 7445 // For now we handle only constant steps. 7446 // 7447 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7448 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7449 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7450 // We have not yet seen any such cases. 7451 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7452 if (!StepC || StepC->getValue()->equalsInt(0)) 7453 return getCouldNotCompute(); 7454 7455 // For positive steps (counting up until unsigned overflow): 7456 // N = -Start/Step (as unsigned) 7457 // For negative steps (counting down to zero): 7458 // N = Start/-Step 7459 // First compute the unsigned distance from zero in the direction of Step. 7460 bool CountDown = StepC->getAPInt().isNegative(); 7461 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7462 7463 // Handle unitary steps, which cannot wraparound. 7464 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7465 // N = Distance (as unsigned) 7466 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7467 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); 7468 7469 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7470 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7471 // case, and see if we can improve the bound. 7472 // 7473 // Explicitly handling this here is necessary because getUnsignedRange 7474 // isn't context-sensitive; it doesn't know that we only care about the 7475 // range inside the loop. 7476 const SCEV *Zero = getZero(Distance->getType()); 7477 const SCEV *One = getOne(Distance->getType()); 7478 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7479 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7480 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7481 // as "unsigned_max(Distance + 1) - 1". 7482 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7483 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7484 } 7485 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7486 } 7487 7488 // If the condition controls loop exit (the loop exits only if the expression 7489 // is true) and the addition is no-wrap we can use unsigned divide to 7490 // compute the backedge count. In this case, the step may not divide the 7491 // distance, but we don't care because if the condition is "missed" the loop 7492 // will have undefined behavior due to wrapping. 7493 if (ControlsExit && AddRec->hasNoSelfWrap() && 7494 loopHasNoAbnormalExits(AddRec->getLoop())) { 7495 const SCEV *Exact = 7496 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7497 return ExitLimit(Exact, Exact, false, Predicates); 7498 } 7499 7500 // Solve the general equation. 7501 const SCEV *E = SolveLinEquationWithOverflow( 7502 StepC->getAPInt(), getNegativeSCEV(Start), *this); 7503 return ExitLimit(E, E, false, Predicates); 7504 } 7505 7506 ScalarEvolution::ExitLimit 7507 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7508 // Loops that look like: while (X == 0) are very strange indeed. We don't 7509 // handle them yet except for the trivial case. This could be expanded in the 7510 // future as needed. 7511 7512 // If the value is a constant, check to see if it is known to be non-zero 7513 // already. If so, the backedge will execute zero times. 7514 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7515 if (!C->getValue()->isNullValue()) 7516 return getZero(C->getType()); 7517 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7518 } 7519 7520 // We could implement others, but I really doubt anyone writes loops like 7521 // this, and if they did, they would already be constant folded. 7522 return getCouldNotCompute(); 7523 } 7524 7525 std::pair<BasicBlock *, BasicBlock *> 7526 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7527 // If the block has a unique predecessor, then there is no path from the 7528 // predecessor to the block that does not go through the direct edge 7529 // from the predecessor to the block. 7530 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7531 return {Pred, BB}; 7532 7533 // A loop's header is defined to be a block that dominates the loop. 7534 // If the header has a unique predecessor outside the loop, it must be 7535 // a block that has exactly one successor that can reach the loop. 7536 if (Loop *L = LI.getLoopFor(BB)) 7537 return {L->getLoopPredecessor(), L->getHeader()}; 7538 7539 return {nullptr, nullptr}; 7540 } 7541 7542 /// SCEV structural equivalence is usually sufficient for testing whether two 7543 /// expressions are equal, however for the purposes of looking for a condition 7544 /// guarding a loop, it can be useful to be a little more general, since a 7545 /// front-end may have replicated the controlling expression. 7546 /// 7547 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7548 // Quick check to see if they are the same SCEV. 7549 if (A == B) return true; 7550 7551 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7552 // Not all instructions that are "identical" compute the same value. For 7553 // instance, two distinct alloca instructions allocating the same type are 7554 // identical and do not read memory; but compute distinct values. 7555 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7556 }; 7557 7558 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7559 // two different instructions with the same value. Check for this case. 7560 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7561 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7562 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7563 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7564 if (ComputesEqualValues(AI, BI)) 7565 return true; 7566 7567 // Otherwise assume they may have a different value. 7568 return false; 7569 } 7570 7571 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7572 const SCEV *&LHS, const SCEV *&RHS, 7573 unsigned Depth) { 7574 bool Changed = false; 7575 7576 // If we hit the max recursion limit bail out. 7577 if (Depth >= 3) 7578 return false; 7579 7580 // Canonicalize a constant to the right side. 7581 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7582 // Check for both operands constant. 7583 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7584 if (ConstantExpr::getICmp(Pred, 7585 LHSC->getValue(), 7586 RHSC->getValue())->isNullValue()) 7587 goto trivially_false; 7588 else 7589 goto trivially_true; 7590 } 7591 // Otherwise swap the operands to put the constant on the right. 7592 std::swap(LHS, RHS); 7593 Pred = ICmpInst::getSwappedPredicate(Pred); 7594 Changed = true; 7595 } 7596 7597 // If we're comparing an addrec with a value which is loop-invariant in the 7598 // addrec's loop, put the addrec on the left. Also make a dominance check, 7599 // as both operands could be addrecs loop-invariant in each other's loop. 7600 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7601 const Loop *L = AR->getLoop(); 7602 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7603 std::swap(LHS, RHS); 7604 Pred = ICmpInst::getSwappedPredicate(Pred); 7605 Changed = true; 7606 } 7607 } 7608 7609 // If there's a constant operand, canonicalize comparisons with boundary 7610 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7611 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7612 const APInt &RA = RC->getAPInt(); 7613 7614 bool SimplifiedByConstantRange = false; 7615 7616 if (!ICmpInst::isEquality(Pred)) { 7617 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7618 if (ExactCR.isFullSet()) 7619 goto trivially_true; 7620 else if (ExactCR.isEmptySet()) 7621 goto trivially_false; 7622 7623 APInt NewRHS; 7624 CmpInst::Predicate NewPred; 7625 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7626 ICmpInst::isEquality(NewPred)) { 7627 // We were able to convert an inequality to an equality. 7628 Pred = NewPred; 7629 RHS = getConstant(NewRHS); 7630 Changed = SimplifiedByConstantRange = true; 7631 } 7632 } 7633 7634 if (!SimplifiedByConstantRange) { 7635 switch (Pred) { 7636 default: 7637 break; 7638 case ICmpInst::ICMP_EQ: 7639 case ICmpInst::ICMP_NE: 7640 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7641 if (!RA) 7642 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7643 if (const SCEVMulExpr *ME = 7644 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7645 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7646 ME->getOperand(0)->isAllOnesValue()) { 7647 RHS = AE->getOperand(1); 7648 LHS = ME->getOperand(1); 7649 Changed = true; 7650 } 7651 break; 7652 7653 7654 // The "Should have been caught earlier!" messages refer to the fact 7655 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7656 // should have fired on the corresponding cases, and canonicalized the 7657 // check to trivially_true or trivially_false. 7658 7659 case ICmpInst::ICMP_UGE: 7660 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7661 Pred = ICmpInst::ICMP_UGT; 7662 RHS = getConstant(RA - 1); 7663 Changed = true; 7664 break; 7665 case ICmpInst::ICMP_ULE: 7666 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7667 Pred = ICmpInst::ICMP_ULT; 7668 RHS = getConstant(RA + 1); 7669 Changed = true; 7670 break; 7671 case ICmpInst::ICMP_SGE: 7672 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7673 Pred = ICmpInst::ICMP_SGT; 7674 RHS = getConstant(RA - 1); 7675 Changed = true; 7676 break; 7677 case ICmpInst::ICMP_SLE: 7678 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7679 Pred = ICmpInst::ICMP_SLT; 7680 RHS = getConstant(RA + 1); 7681 Changed = true; 7682 break; 7683 } 7684 } 7685 } 7686 7687 // Check for obvious equality. 7688 if (HasSameValue(LHS, RHS)) { 7689 if (ICmpInst::isTrueWhenEqual(Pred)) 7690 goto trivially_true; 7691 if (ICmpInst::isFalseWhenEqual(Pred)) 7692 goto trivially_false; 7693 } 7694 7695 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7696 // adding or subtracting 1 from one of the operands. 7697 switch (Pred) { 7698 case ICmpInst::ICMP_SLE: 7699 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7700 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7701 SCEV::FlagNSW); 7702 Pred = ICmpInst::ICMP_SLT; 7703 Changed = true; 7704 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7705 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7706 SCEV::FlagNSW); 7707 Pred = ICmpInst::ICMP_SLT; 7708 Changed = true; 7709 } 7710 break; 7711 case ICmpInst::ICMP_SGE: 7712 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7713 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7714 SCEV::FlagNSW); 7715 Pred = ICmpInst::ICMP_SGT; 7716 Changed = true; 7717 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7718 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7719 SCEV::FlagNSW); 7720 Pred = ICmpInst::ICMP_SGT; 7721 Changed = true; 7722 } 7723 break; 7724 case ICmpInst::ICMP_ULE: 7725 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7726 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7727 SCEV::FlagNUW); 7728 Pred = ICmpInst::ICMP_ULT; 7729 Changed = true; 7730 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7731 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7732 Pred = ICmpInst::ICMP_ULT; 7733 Changed = true; 7734 } 7735 break; 7736 case ICmpInst::ICMP_UGE: 7737 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7738 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7739 Pred = ICmpInst::ICMP_UGT; 7740 Changed = true; 7741 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7742 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7743 SCEV::FlagNUW); 7744 Pred = ICmpInst::ICMP_UGT; 7745 Changed = true; 7746 } 7747 break; 7748 default: 7749 break; 7750 } 7751 7752 // TODO: More simplifications are possible here. 7753 7754 // Recursively simplify until we either hit a recursion limit or nothing 7755 // changes. 7756 if (Changed) 7757 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7758 7759 return Changed; 7760 7761 trivially_true: 7762 // Return 0 == 0. 7763 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7764 Pred = ICmpInst::ICMP_EQ; 7765 return true; 7766 7767 trivially_false: 7768 // Return 0 != 0. 7769 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7770 Pred = ICmpInst::ICMP_NE; 7771 return true; 7772 } 7773 7774 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7775 return getSignedRange(S).getSignedMax().isNegative(); 7776 } 7777 7778 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7779 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7780 } 7781 7782 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7783 return !getSignedRange(S).getSignedMin().isNegative(); 7784 } 7785 7786 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7787 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7788 } 7789 7790 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7791 return isKnownNegative(S) || isKnownPositive(S); 7792 } 7793 7794 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7795 const SCEV *LHS, const SCEV *RHS) { 7796 // Canonicalize the inputs first. 7797 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7798 7799 // If LHS or RHS is an addrec, check to see if the condition is true in 7800 // every iteration of the loop. 7801 // If LHS and RHS are both addrec, both conditions must be true in 7802 // every iteration of the loop. 7803 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7804 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7805 bool LeftGuarded = false; 7806 bool RightGuarded = false; 7807 if (LAR) { 7808 const Loop *L = LAR->getLoop(); 7809 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7810 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7811 if (!RAR) return true; 7812 LeftGuarded = true; 7813 } 7814 } 7815 if (RAR) { 7816 const Loop *L = RAR->getLoop(); 7817 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7818 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7819 if (!LAR) return true; 7820 RightGuarded = true; 7821 } 7822 } 7823 if (LeftGuarded && RightGuarded) 7824 return true; 7825 7826 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7827 return true; 7828 7829 // Otherwise see what can be done with known constant ranges. 7830 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7831 } 7832 7833 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7834 ICmpInst::Predicate Pred, 7835 bool &Increasing) { 7836 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7837 7838 #ifndef NDEBUG 7839 // Verify an invariant: inverting the predicate should turn a monotonically 7840 // increasing change to a monotonically decreasing one, and vice versa. 7841 bool IncreasingSwapped; 7842 bool ResultSwapped = isMonotonicPredicateImpl( 7843 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7844 7845 assert(Result == ResultSwapped && "should be able to analyze both!"); 7846 if (ResultSwapped) 7847 assert(Increasing == !IncreasingSwapped && 7848 "monotonicity should flip as we flip the predicate"); 7849 #endif 7850 7851 return Result; 7852 } 7853 7854 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7855 ICmpInst::Predicate Pred, 7856 bool &Increasing) { 7857 7858 // A zero step value for LHS means the induction variable is essentially a 7859 // loop invariant value. We don't really depend on the predicate actually 7860 // flipping from false to true (for increasing predicates, and the other way 7861 // around for decreasing predicates), all we care about is that *if* the 7862 // predicate changes then it only changes from false to true. 7863 // 7864 // A zero step value in itself is not very useful, but there may be places 7865 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7866 // as general as possible. 7867 7868 switch (Pred) { 7869 default: 7870 return false; // Conservative answer 7871 7872 case ICmpInst::ICMP_UGT: 7873 case ICmpInst::ICMP_UGE: 7874 case ICmpInst::ICMP_ULT: 7875 case ICmpInst::ICMP_ULE: 7876 if (!LHS->hasNoUnsignedWrap()) 7877 return false; 7878 7879 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7880 return true; 7881 7882 case ICmpInst::ICMP_SGT: 7883 case ICmpInst::ICMP_SGE: 7884 case ICmpInst::ICMP_SLT: 7885 case ICmpInst::ICMP_SLE: { 7886 if (!LHS->hasNoSignedWrap()) 7887 return false; 7888 7889 const SCEV *Step = LHS->getStepRecurrence(*this); 7890 7891 if (isKnownNonNegative(Step)) { 7892 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7893 return true; 7894 } 7895 7896 if (isKnownNonPositive(Step)) { 7897 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7898 return true; 7899 } 7900 7901 return false; 7902 } 7903 7904 } 7905 7906 llvm_unreachable("switch has default clause!"); 7907 } 7908 7909 bool ScalarEvolution::isLoopInvariantPredicate( 7910 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7911 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7912 const SCEV *&InvariantRHS) { 7913 7914 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7915 if (!isLoopInvariant(RHS, L)) { 7916 if (!isLoopInvariant(LHS, L)) 7917 return false; 7918 7919 std::swap(LHS, RHS); 7920 Pred = ICmpInst::getSwappedPredicate(Pred); 7921 } 7922 7923 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7924 if (!ArLHS || ArLHS->getLoop() != L) 7925 return false; 7926 7927 bool Increasing; 7928 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7929 return false; 7930 7931 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7932 // true as the loop iterates, and the backedge is control dependent on 7933 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7934 // 7935 // * if the predicate was false in the first iteration then the predicate 7936 // is never evaluated again, since the loop exits without taking the 7937 // backedge. 7938 // * if the predicate was true in the first iteration then it will 7939 // continue to be true for all future iterations since it is 7940 // monotonically increasing. 7941 // 7942 // For both the above possibilities, we can replace the loop varying 7943 // predicate with its value on the first iteration of the loop (which is 7944 // loop invariant). 7945 // 7946 // A similar reasoning applies for a monotonically decreasing predicate, by 7947 // replacing true with false and false with true in the above two bullets. 7948 7949 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7950 7951 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7952 return false; 7953 7954 InvariantPred = Pred; 7955 InvariantLHS = ArLHS->getStart(); 7956 InvariantRHS = RHS; 7957 return true; 7958 } 7959 7960 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7961 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7962 if (HasSameValue(LHS, RHS)) 7963 return ICmpInst::isTrueWhenEqual(Pred); 7964 7965 // This code is split out from isKnownPredicate because it is called from 7966 // within isLoopEntryGuardedByCond. 7967 7968 auto CheckRanges = 7969 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7970 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7971 .contains(RangeLHS); 7972 }; 7973 7974 // The check at the top of the function catches the case where the values are 7975 // known to be equal. 7976 if (Pred == CmpInst::ICMP_EQ) 7977 return false; 7978 7979 if (Pred == CmpInst::ICMP_NE) 7980 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7981 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7982 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7983 7984 if (CmpInst::isSigned(Pred)) 7985 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7986 7987 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7988 } 7989 7990 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7991 const SCEV *LHS, 7992 const SCEV *RHS) { 7993 7994 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7995 // Return Y via OutY. 7996 auto MatchBinaryAddToConst = 7997 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7998 SCEV::NoWrapFlags ExpectedFlags) { 7999 const SCEV *NonConstOp, *ConstOp; 8000 SCEV::NoWrapFlags FlagsPresent; 8001 8002 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8003 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8004 return false; 8005 8006 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8007 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8008 }; 8009 8010 APInt C; 8011 8012 switch (Pred) { 8013 default: 8014 break; 8015 8016 case ICmpInst::ICMP_SGE: 8017 std::swap(LHS, RHS); 8018 case ICmpInst::ICMP_SLE: 8019 // X s<= (X + C)<nsw> if C >= 0 8020 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8021 return true; 8022 8023 // (X + C)<nsw> s<= X if C <= 0 8024 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8025 !C.isStrictlyPositive()) 8026 return true; 8027 break; 8028 8029 case ICmpInst::ICMP_SGT: 8030 std::swap(LHS, RHS); 8031 case ICmpInst::ICMP_SLT: 8032 // X s< (X + C)<nsw> if C > 0 8033 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8034 C.isStrictlyPositive()) 8035 return true; 8036 8037 // (X + C)<nsw> s< X if C < 0 8038 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8039 return true; 8040 break; 8041 } 8042 8043 return false; 8044 } 8045 8046 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8047 const SCEV *LHS, 8048 const SCEV *RHS) { 8049 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8050 return false; 8051 8052 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8053 // the stack can result in exponential time complexity. 8054 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8055 8056 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8057 // 8058 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8059 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8060 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8061 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8062 // use isKnownPredicate later if needed. 8063 return isKnownNonNegative(RHS) && 8064 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8065 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8066 } 8067 8068 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8069 ICmpInst::Predicate Pred, 8070 const SCEV *LHS, const SCEV *RHS) { 8071 // No need to even try if we know the module has no guards. 8072 if (!HasGuards) 8073 return false; 8074 8075 return any_of(*BB, [&](Instruction &I) { 8076 using namespace llvm::PatternMatch; 8077 8078 Value *Condition; 8079 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8080 m_Value(Condition))) && 8081 isImpliedCond(Pred, LHS, RHS, Condition, false); 8082 }); 8083 } 8084 8085 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8086 /// protected by a conditional between LHS and RHS. This is used to 8087 /// to eliminate casts. 8088 bool 8089 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8090 ICmpInst::Predicate Pred, 8091 const SCEV *LHS, const SCEV *RHS) { 8092 // Interpret a null as meaning no loop, where there is obviously no guard 8093 // (interprocedural conditions notwithstanding). 8094 if (!L) return true; 8095 8096 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8097 return true; 8098 8099 BasicBlock *Latch = L->getLoopLatch(); 8100 if (!Latch) 8101 return false; 8102 8103 BranchInst *LoopContinuePredicate = 8104 dyn_cast<BranchInst>(Latch->getTerminator()); 8105 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8106 isImpliedCond(Pred, LHS, RHS, 8107 LoopContinuePredicate->getCondition(), 8108 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8109 return true; 8110 8111 // We don't want more than one activation of the following loops on the stack 8112 // -- that can lead to O(n!) time complexity. 8113 if (WalkingBEDominatingConds) 8114 return false; 8115 8116 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8117 8118 // See if we can exploit a trip count to prove the predicate. 8119 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8120 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8121 if (LatchBECount != getCouldNotCompute()) { 8122 // We know that Latch branches back to the loop header exactly 8123 // LatchBECount times. This means the backdege condition at Latch is 8124 // equivalent to "{0,+,1} u< LatchBECount". 8125 Type *Ty = LatchBECount->getType(); 8126 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8127 const SCEV *LoopCounter = 8128 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8129 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8130 LatchBECount)) 8131 return true; 8132 } 8133 8134 // Check conditions due to any @llvm.assume intrinsics. 8135 for (auto &AssumeVH : AC.assumptions()) { 8136 if (!AssumeVH) 8137 continue; 8138 auto *CI = cast<CallInst>(AssumeVH); 8139 if (!DT.dominates(CI, Latch->getTerminator())) 8140 continue; 8141 8142 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8143 return true; 8144 } 8145 8146 // If the loop is not reachable from the entry block, we risk running into an 8147 // infinite loop as we walk up into the dom tree. These loops do not matter 8148 // anyway, so we just return a conservative answer when we see them. 8149 if (!DT.isReachableFromEntry(L->getHeader())) 8150 return false; 8151 8152 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8153 return true; 8154 8155 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8156 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8157 8158 assert(DTN && "should reach the loop header before reaching the root!"); 8159 8160 BasicBlock *BB = DTN->getBlock(); 8161 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8162 return true; 8163 8164 BasicBlock *PBB = BB->getSinglePredecessor(); 8165 if (!PBB) 8166 continue; 8167 8168 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8169 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8170 continue; 8171 8172 Value *Condition = ContinuePredicate->getCondition(); 8173 8174 // If we have an edge `E` within the loop body that dominates the only 8175 // latch, the condition guarding `E` also guards the backedge. This 8176 // reasoning works only for loops with a single latch. 8177 8178 BasicBlockEdge DominatingEdge(PBB, BB); 8179 if (DominatingEdge.isSingleEdge()) { 8180 // We're constructively (and conservatively) enumerating edges within the 8181 // loop body that dominate the latch. The dominator tree better agree 8182 // with us on this: 8183 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8184 8185 if (isImpliedCond(Pred, LHS, RHS, Condition, 8186 BB != ContinuePredicate->getSuccessor(0))) 8187 return true; 8188 } 8189 } 8190 8191 return false; 8192 } 8193 8194 bool 8195 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8196 ICmpInst::Predicate Pred, 8197 const SCEV *LHS, const SCEV *RHS) { 8198 // Interpret a null as meaning no loop, where there is obviously no guard 8199 // (interprocedural conditions notwithstanding). 8200 if (!L) return false; 8201 8202 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8203 return true; 8204 8205 // Starting at the loop predecessor, climb up the predecessor chain, as long 8206 // as there are predecessors that can be found that have unique successors 8207 // leading to the original header. 8208 for (std::pair<BasicBlock *, BasicBlock *> 8209 Pair(L->getLoopPredecessor(), L->getHeader()); 8210 Pair.first; 8211 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8212 8213 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8214 return true; 8215 8216 BranchInst *LoopEntryPredicate = 8217 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8218 if (!LoopEntryPredicate || 8219 LoopEntryPredicate->isUnconditional()) 8220 continue; 8221 8222 if (isImpliedCond(Pred, LHS, RHS, 8223 LoopEntryPredicate->getCondition(), 8224 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8225 return true; 8226 } 8227 8228 // Check conditions due to any @llvm.assume intrinsics. 8229 for (auto &AssumeVH : AC.assumptions()) { 8230 if (!AssumeVH) 8231 continue; 8232 auto *CI = cast<CallInst>(AssumeVH); 8233 if (!DT.dominates(CI, L->getHeader())) 8234 continue; 8235 8236 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8237 return true; 8238 } 8239 8240 return false; 8241 } 8242 8243 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8244 const SCEV *LHS, const SCEV *RHS, 8245 Value *FoundCondValue, 8246 bool Inverse) { 8247 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8248 return false; 8249 8250 auto ClearOnExit = 8251 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8252 8253 // Recursively handle And and Or conditions. 8254 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8255 if (BO->getOpcode() == Instruction::And) { 8256 if (!Inverse) 8257 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8258 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8259 } else if (BO->getOpcode() == Instruction::Or) { 8260 if (Inverse) 8261 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8262 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8263 } 8264 } 8265 8266 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8267 if (!ICI) return false; 8268 8269 // Now that we found a conditional branch that dominates the loop or controls 8270 // the loop latch. Check to see if it is the comparison we are looking for. 8271 ICmpInst::Predicate FoundPred; 8272 if (Inverse) 8273 FoundPred = ICI->getInversePredicate(); 8274 else 8275 FoundPred = ICI->getPredicate(); 8276 8277 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8278 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8279 8280 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8281 } 8282 8283 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8284 const SCEV *RHS, 8285 ICmpInst::Predicate FoundPred, 8286 const SCEV *FoundLHS, 8287 const SCEV *FoundRHS) { 8288 // Balance the types. 8289 if (getTypeSizeInBits(LHS->getType()) < 8290 getTypeSizeInBits(FoundLHS->getType())) { 8291 if (CmpInst::isSigned(Pred)) { 8292 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8293 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8294 } else { 8295 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8296 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8297 } 8298 } else if (getTypeSizeInBits(LHS->getType()) > 8299 getTypeSizeInBits(FoundLHS->getType())) { 8300 if (CmpInst::isSigned(FoundPred)) { 8301 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8302 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8303 } else { 8304 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8305 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8306 } 8307 } 8308 8309 // Canonicalize the query to match the way instcombine will have 8310 // canonicalized the comparison. 8311 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8312 if (LHS == RHS) 8313 return CmpInst::isTrueWhenEqual(Pred); 8314 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8315 if (FoundLHS == FoundRHS) 8316 return CmpInst::isFalseWhenEqual(FoundPred); 8317 8318 // Check to see if we can make the LHS or RHS match. 8319 if (LHS == FoundRHS || RHS == FoundLHS) { 8320 if (isa<SCEVConstant>(RHS)) { 8321 std::swap(FoundLHS, FoundRHS); 8322 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8323 } else { 8324 std::swap(LHS, RHS); 8325 Pred = ICmpInst::getSwappedPredicate(Pred); 8326 } 8327 } 8328 8329 // Check whether the found predicate is the same as the desired predicate. 8330 if (FoundPred == Pred) 8331 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8332 8333 // Check whether swapping the found predicate makes it the same as the 8334 // desired predicate. 8335 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8336 if (isa<SCEVConstant>(RHS)) 8337 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8338 else 8339 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8340 RHS, LHS, FoundLHS, FoundRHS); 8341 } 8342 8343 // Unsigned comparison is the same as signed comparison when both the operands 8344 // are non-negative. 8345 if (CmpInst::isUnsigned(FoundPred) && 8346 CmpInst::getSignedPredicate(FoundPred) == Pred && 8347 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8348 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8349 8350 // Check if we can make progress by sharpening ranges. 8351 if (FoundPred == ICmpInst::ICMP_NE && 8352 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8353 8354 const SCEVConstant *C = nullptr; 8355 const SCEV *V = nullptr; 8356 8357 if (isa<SCEVConstant>(FoundLHS)) { 8358 C = cast<SCEVConstant>(FoundLHS); 8359 V = FoundRHS; 8360 } else { 8361 C = cast<SCEVConstant>(FoundRHS); 8362 V = FoundLHS; 8363 } 8364 8365 // The guarding predicate tells us that C != V. If the known range 8366 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8367 // range we consider has to correspond to same signedness as the 8368 // predicate we're interested in folding. 8369 8370 APInt Min = ICmpInst::isSigned(Pred) ? 8371 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8372 8373 if (Min == C->getAPInt()) { 8374 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8375 // This is true even if (Min + 1) wraps around -- in case of 8376 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8377 8378 APInt SharperMin = Min + 1; 8379 8380 switch (Pred) { 8381 case ICmpInst::ICMP_SGE: 8382 case ICmpInst::ICMP_UGE: 8383 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8384 // RHS, we're done. 8385 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8386 getConstant(SharperMin))) 8387 return true; 8388 8389 case ICmpInst::ICMP_SGT: 8390 case ICmpInst::ICMP_UGT: 8391 // We know from the range information that (V `Pred` Min || 8392 // V == Min). We know from the guarding condition that !(V 8393 // == Min). This gives us 8394 // 8395 // V `Pred` Min || V == Min && !(V == Min) 8396 // => V `Pred` Min 8397 // 8398 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8399 8400 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8401 return true; 8402 8403 default: 8404 // No change 8405 break; 8406 } 8407 } 8408 } 8409 8410 // Check whether the actual condition is beyond sufficient. 8411 if (FoundPred == ICmpInst::ICMP_EQ) 8412 if (ICmpInst::isTrueWhenEqual(Pred)) 8413 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8414 return true; 8415 if (Pred == ICmpInst::ICMP_NE) 8416 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8417 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8418 return true; 8419 8420 // Otherwise assume the worst. 8421 return false; 8422 } 8423 8424 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8425 const SCEV *&L, const SCEV *&R, 8426 SCEV::NoWrapFlags &Flags) { 8427 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8428 if (!AE || AE->getNumOperands() != 2) 8429 return false; 8430 8431 L = AE->getOperand(0); 8432 R = AE->getOperand(1); 8433 Flags = AE->getNoWrapFlags(); 8434 return true; 8435 } 8436 8437 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8438 const SCEV *Less) { 8439 // We avoid subtracting expressions here because this function is usually 8440 // fairly deep in the call stack (i.e. is called many times). 8441 8442 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8443 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8444 const auto *MAR = cast<SCEVAddRecExpr>(More); 8445 8446 if (LAR->getLoop() != MAR->getLoop()) 8447 return None; 8448 8449 // We look at affine expressions only; not for correctness but to keep 8450 // getStepRecurrence cheap. 8451 if (!LAR->isAffine() || !MAR->isAffine()) 8452 return None; 8453 8454 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8455 return None; 8456 8457 Less = LAR->getStart(); 8458 More = MAR->getStart(); 8459 8460 // fall through 8461 } 8462 8463 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8464 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8465 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8466 return M - L; 8467 } 8468 8469 const SCEV *L, *R; 8470 SCEV::NoWrapFlags Flags; 8471 if (splitBinaryAdd(Less, L, R, Flags)) 8472 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8473 if (R == More) 8474 return -(LC->getAPInt()); 8475 8476 if (splitBinaryAdd(More, L, R, Flags)) 8477 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8478 if (R == Less) 8479 return LC->getAPInt(); 8480 8481 return None; 8482 } 8483 8484 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8485 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8486 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8487 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8488 return false; 8489 8490 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8491 if (!AddRecLHS) 8492 return false; 8493 8494 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8495 if (!AddRecFoundLHS) 8496 return false; 8497 8498 // We'd like to let SCEV reason about control dependencies, so we constrain 8499 // both the inequalities to be about add recurrences on the same loop. This 8500 // way we can use isLoopEntryGuardedByCond later. 8501 8502 const Loop *L = AddRecFoundLHS->getLoop(); 8503 if (L != AddRecLHS->getLoop()) 8504 return false; 8505 8506 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8507 // 8508 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8509 // ... (2) 8510 // 8511 // Informal proof for (2), assuming (1) [*]: 8512 // 8513 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8514 // 8515 // Then 8516 // 8517 // FoundLHS s< FoundRHS s< INT_MIN - C 8518 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8519 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8520 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8521 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8522 // <=> FoundLHS + C s< FoundRHS + C 8523 // 8524 // [*]: (1) can be proved by ruling out overflow. 8525 // 8526 // [**]: This can be proved by analyzing all the four possibilities: 8527 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8528 // (A s>= 0, B s>= 0). 8529 // 8530 // Note: 8531 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8532 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8533 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8534 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8535 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8536 // C)". 8537 8538 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8539 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8540 if (!LDiff || !RDiff || *LDiff != *RDiff) 8541 return false; 8542 8543 if (LDiff->isMinValue()) 8544 return true; 8545 8546 APInt FoundRHSLimit; 8547 8548 if (Pred == CmpInst::ICMP_ULT) { 8549 FoundRHSLimit = -(*RDiff); 8550 } else { 8551 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8552 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8553 } 8554 8555 // Try to prove (1) or (2), as needed. 8556 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8557 getConstant(FoundRHSLimit)); 8558 } 8559 8560 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8561 const SCEV *LHS, const SCEV *RHS, 8562 const SCEV *FoundLHS, 8563 const SCEV *FoundRHS) { 8564 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8565 return true; 8566 8567 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8568 return true; 8569 8570 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8571 FoundLHS, FoundRHS) || 8572 // ~x < ~y --> x > y 8573 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8574 getNotSCEV(FoundRHS), 8575 getNotSCEV(FoundLHS)); 8576 } 8577 8578 8579 /// If Expr computes ~A, return A else return nullptr 8580 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8581 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8582 if (!Add || Add->getNumOperands() != 2 || 8583 !Add->getOperand(0)->isAllOnesValue()) 8584 return nullptr; 8585 8586 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8587 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8588 !AddRHS->getOperand(0)->isAllOnesValue()) 8589 return nullptr; 8590 8591 return AddRHS->getOperand(1); 8592 } 8593 8594 8595 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8596 template<typename MaxExprType> 8597 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8598 const SCEV *Candidate) { 8599 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8600 if (!MaxExpr) return false; 8601 8602 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8603 } 8604 8605 8606 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8607 template<typename MaxExprType> 8608 static bool IsMinConsistingOf(ScalarEvolution &SE, 8609 const SCEV *MaybeMinExpr, 8610 const SCEV *Candidate) { 8611 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8612 if (!MaybeMaxExpr) 8613 return false; 8614 8615 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8616 } 8617 8618 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8619 ICmpInst::Predicate Pred, 8620 const SCEV *LHS, const SCEV *RHS) { 8621 8622 // If both sides are affine addrecs for the same loop, with equal 8623 // steps, and we know the recurrences don't wrap, then we only 8624 // need to check the predicate on the starting values. 8625 8626 if (!ICmpInst::isRelational(Pred)) 8627 return false; 8628 8629 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8630 if (!LAR) 8631 return false; 8632 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8633 if (!RAR) 8634 return false; 8635 if (LAR->getLoop() != RAR->getLoop()) 8636 return false; 8637 if (!LAR->isAffine() || !RAR->isAffine()) 8638 return false; 8639 8640 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8641 return false; 8642 8643 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8644 SCEV::FlagNSW : SCEV::FlagNUW; 8645 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8646 return false; 8647 8648 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8649 } 8650 8651 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8652 /// expression? 8653 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8654 ICmpInst::Predicate Pred, 8655 const SCEV *LHS, const SCEV *RHS) { 8656 switch (Pred) { 8657 default: 8658 return false; 8659 8660 case ICmpInst::ICMP_SGE: 8661 std::swap(LHS, RHS); 8662 LLVM_FALLTHROUGH; 8663 case ICmpInst::ICMP_SLE: 8664 return 8665 // min(A, ...) <= A 8666 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8667 // A <= max(A, ...) 8668 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8669 8670 case ICmpInst::ICMP_UGE: 8671 std::swap(LHS, RHS); 8672 LLVM_FALLTHROUGH; 8673 case ICmpInst::ICMP_ULE: 8674 return 8675 // min(A, ...) <= A 8676 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8677 // A <= max(A, ...) 8678 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8679 } 8680 8681 llvm_unreachable("covered switch fell through?!"); 8682 } 8683 8684 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 8685 const SCEV *LHS, const SCEV *RHS, 8686 const SCEV *FoundLHS, 8687 const SCEV *FoundRHS, 8688 unsigned Depth) { 8689 assert(getTypeSizeInBits(LHS->getType()) == 8690 getTypeSizeInBits(RHS->getType()) && 8691 "LHS and RHS have different sizes?"); 8692 assert(getTypeSizeInBits(FoundLHS->getType()) == 8693 getTypeSizeInBits(FoundRHS->getType()) && 8694 "FoundLHS and FoundRHS have different sizes?"); 8695 // We want to avoid hurting the compile time with analysis of too big trees. 8696 if (Depth > MaxSCEVOperationsImplicationDepth) 8697 return false; 8698 // We only want to work with ICMP_SGT comparison so far. 8699 // TODO: Extend to ICMP_UGT? 8700 if (Pred == ICmpInst::ICMP_SLT) { 8701 Pred = ICmpInst::ICMP_SGT; 8702 std::swap(LHS, RHS); 8703 std::swap(FoundLHS, FoundRHS); 8704 } 8705 if (Pred != ICmpInst::ICMP_SGT) 8706 return false; 8707 8708 auto GetOpFromSExt = [&](const SCEV *S) { 8709 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 8710 return Ext->getOperand(); 8711 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 8712 // the constant in some cases. 8713 return S; 8714 }; 8715 8716 // Acquire values from extensions. 8717 auto *OrigFoundLHS = FoundLHS; 8718 LHS = GetOpFromSExt(LHS); 8719 FoundLHS = GetOpFromSExt(FoundLHS); 8720 8721 // Is the SGT predicate can be proved trivially or using the found context. 8722 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 8723 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 8724 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 8725 FoundRHS, Depth + 1); 8726 }; 8727 8728 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 8729 // We want to avoid creation of any new non-constant SCEV. Since we are 8730 // going to compare the operands to RHS, we should be certain that we don't 8731 // need any size extensions for this. So let's decline all cases when the 8732 // sizes of types of LHS and RHS do not match. 8733 // TODO: Maybe try to get RHS from sext to catch more cases? 8734 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 8735 return false; 8736 8737 // Should not overflow. 8738 if (!LHSAddExpr->hasNoSignedWrap()) 8739 return false; 8740 8741 auto *LL = LHSAddExpr->getOperand(0); 8742 auto *LR = LHSAddExpr->getOperand(1); 8743 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 8744 8745 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 8746 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 8747 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 8748 }; 8749 // Try to prove the following rule: 8750 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 8751 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 8752 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 8753 return true; 8754 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 8755 Value *LL, *LR; 8756 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 8757 using namespace llvm::PatternMatch; 8758 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 8759 // Rules for division. 8760 // We are going to perform some comparisons with Denominator and its 8761 // derivative expressions. In general case, creating a SCEV for it may 8762 // lead to a complex analysis of the entire graph, and in particular it 8763 // can request trip count recalculation for the same loop. This would 8764 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 8765 // this, we only want to create SCEVs that are constants in this section. 8766 // So we bail if Denominator is not a constant. 8767 if (!isa<ConstantInt>(LR)) 8768 return false; 8769 8770 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 8771 8772 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 8773 // then a SCEV for the numerator already exists and matches with FoundLHS. 8774 auto *Numerator = getExistingSCEV(LL); 8775 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 8776 return false; 8777 8778 // Make sure that the numerator matches with FoundLHS and the denominator 8779 // is positive. 8780 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 8781 return false; 8782 8783 auto *DTy = Denominator->getType(); 8784 auto *FRHSTy = FoundRHS->getType(); 8785 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 8786 // One of types is a pointer and another one is not. We cannot extend 8787 // them properly to a wider type, so let us just reject this case. 8788 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 8789 // to avoid this check. 8790 return false; 8791 8792 // Given that: 8793 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 8794 auto *WTy = getWiderType(DTy, FRHSTy); 8795 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 8796 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 8797 8798 // Try to prove the following rule: 8799 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 8800 // For example, given that FoundLHS > 2. It means that FoundLHS is at 8801 // least 3. If we divide it by Denominator < 4, we will have at least 1. 8802 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 8803 if (isKnownNonPositive(RHS) && 8804 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 8805 return true; 8806 8807 // Try to prove the following rule: 8808 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 8809 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 8810 // If we divide it by Denominator > 2, then: 8811 // 1. If FoundLHS is negative, then the result is 0. 8812 // 2. If FoundLHS is non-negative, then the result is non-negative. 8813 // Anyways, the result is non-negative. 8814 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 8815 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 8816 if (isKnownNegative(RHS) && 8817 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 8818 return true; 8819 } 8820 } 8821 8822 return false; 8823 } 8824 8825 bool 8826 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 8827 const SCEV *LHS, const SCEV *RHS) { 8828 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8829 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8830 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8831 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8832 } 8833 8834 bool 8835 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8836 const SCEV *LHS, const SCEV *RHS, 8837 const SCEV *FoundLHS, 8838 const SCEV *FoundRHS) { 8839 switch (Pred) { 8840 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8841 case ICmpInst::ICMP_EQ: 8842 case ICmpInst::ICMP_NE: 8843 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8844 return true; 8845 break; 8846 case ICmpInst::ICMP_SLT: 8847 case ICmpInst::ICMP_SLE: 8848 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8849 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8850 return true; 8851 break; 8852 case ICmpInst::ICMP_SGT: 8853 case ICmpInst::ICMP_SGE: 8854 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8855 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8856 return true; 8857 break; 8858 case ICmpInst::ICMP_ULT: 8859 case ICmpInst::ICMP_ULE: 8860 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8861 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8862 return true; 8863 break; 8864 case ICmpInst::ICMP_UGT: 8865 case ICmpInst::ICMP_UGE: 8866 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8867 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8868 return true; 8869 break; 8870 } 8871 8872 // Maybe it can be proved via operations? 8873 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8874 return true; 8875 8876 return false; 8877 } 8878 8879 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8880 const SCEV *LHS, 8881 const SCEV *RHS, 8882 const SCEV *FoundLHS, 8883 const SCEV *FoundRHS) { 8884 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8885 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8886 // reduce the compile time impact of this optimization. 8887 return false; 8888 8889 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8890 if (!Addend) 8891 return false; 8892 8893 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8894 8895 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8896 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8897 ConstantRange FoundLHSRange = 8898 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8899 8900 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8901 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8902 8903 // We can also compute the range of values for `LHS` that satisfy the 8904 // consequent, "`LHS` `Pred` `RHS`": 8905 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8906 ConstantRange SatisfyingLHSRange = 8907 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8908 8909 // The antecedent implies the consequent if every value of `LHS` that 8910 // satisfies the antecedent also satisfies the consequent. 8911 return SatisfyingLHSRange.contains(LHSRange); 8912 } 8913 8914 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8915 bool IsSigned, bool NoWrap) { 8916 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8917 8918 if (NoWrap) return false; 8919 8920 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8921 const SCEV *One = getOne(Stride->getType()); 8922 8923 if (IsSigned) { 8924 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8925 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8926 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8927 .getSignedMax(); 8928 8929 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8930 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8931 } 8932 8933 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8934 APInt MaxValue = APInt::getMaxValue(BitWidth); 8935 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8936 .getUnsignedMax(); 8937 8938 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8939 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8940 } 8941 8942 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8943 bool IsSigned, bool NoWrap) { 8944 if (NoWrap) return false; 8945 8946 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8947 const SCEV *One = getOne(Stride->getType()); 8948 8949 if (IsSigned) { 8950 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8951 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8952 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8953 .getSignedMax(); 8954 8955 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8956 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8957 } 8958 8959 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8960 APInt MinValue = APInt::getMinValue(BitWidth); 8961 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8962 .getUnsignedMax(); 8963 8964 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8965 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8966 } 8967 8968 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8969 bool Equality) { 8970 const SCEV *One = getOne(Step->getType()); 8971 Delta = Equality ? getAddExpr(Delta, Step) 8972 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8973 return getUDivExpr(Delta, Step); 8974 } 8975 8976 ScalarEvolution::ExitLimit 8977 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8978 const Loop *L, bool IsSigned, 8979 bool ControlsExit, bool AllowPredicates) { 8980 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8981 // We handle only IV < Invariant 8982 if (!isLoopInvariant(RHS, L)) 8983 return getCouldNotCompute(); 8984 8985 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8986 bool PredicatedIV = false; 8987 8988 if (!IV && AllowPredicates) { 8989 // Try to make this an AddRec using runtime tests, in the first X 8990 // iterations of this loop, where X is the SCEV expression found by the 8991 // algorithm below. 8992 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8993 PredicatedIV = true; 8994 } 8995 8996 // Avoid weird loops 8997 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8998 return getCouldNotCompute(); 8999 9000 bool NoWrap = ControlsExit && 9001 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9002 9003 const SCEV *Stride = IV->getStepRecurrence(*this); 9004 9005 bool PositiveStride = isKnownPositive(Stride); 9006 9007 // Avoid negative or zero stride values. 9008 if (!PositiveStride) { 9009 // We can compute the correct backedge taken count for loops with unknown 9010 // strides if we can prove that the loop is not an infinite loop with side 9011 // effects. Here's the loop structure we are trying to handle - 9012 // 9013 // i = start 9014 // do { 9015 // A[i] = i; 9016 // i += s; 9017 // } while (i < end); 9018 // 9019 // The backedge taken count for such loops is evaluated as - 9020 // (max(end, start + stride) - start - 1) /u stride 9021 // 9022 // The additional preconditions that we need to check to prove correctness 9023 // of the above formula is as follows - 9024 // 9025 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9026 // NoWrap flag). 9027 // b) loop is single exit with no side effects. 9028 // 9029 // 9030 // Precondition a) implies that if the stride is negative, this is a single 9031 // trip loop. The backedge taken count formula reduces to zero in this case. 9032 // 9033 // Precondition b) implies that the unknown stride cannot be zero otherwise 9034 // we have UB. 9035 // 9036 // The positive stride case is the same as isKnownPositive(Stride) returning 9037 // true (original behavior of the function). 9038 // 9039 // We want to make sure that the stride is truly unknown as there are edge 9040 // cases where ScalarEvolution propagates no wrap flags to the 9041 // post-increment/decrement IV even though the increment/decrement operation 9042 // itself is wrapping. The computed backedge taken count may be wrong in 9043 // such cases. This is prevented by checking that the stride is not known to 9044 // be either positive or non-positive. For example, no wrap flags are 9045 // propagated to the post-increment IV of this loop with a trip count of 2 - 9046 // 9047 // unsigned char i; 9048 // for(i=127; i<128; i+=129) 9049 // A[i] = i; 9050 // 9051 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9052 !loopHasNoSideEffects(L)) 9053 return getCouldNotCompute(); 9054 9055 } else if (!Stride->isOne() && 9056 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9057 // Avoid proven overflow cases: this will ensure that the backedge taken 9058 // count will not generate any unsigned overflow. Relaxed no-overflow 9059 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9060 // undefined behaviors like the case of C language. 9061 return getCouldNotCompute(); 9062 9063 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9064 : ICmpInst::ICMP_ULT; 9065 const SCEV *Start = IV->getStart(); 9066 const SCEV *End = RHS; 9067 // If the backedge is taken at least once, then it will be taken 9068 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9069 // is the LHS value of the less-than comparison the first time it is evaluated 9070 // and End is the RHS. 9071 const SCEV *BECountIfBackedgeTaken = 9072 computeBECount(getMinusSCEV(End, Start), Stride, false); 9073 // If the loop entry is guarded by the result of the backedge test of the 9074 // first loop iteration, then we know the backedge will be taken at least 9075 // once and so the backedge taken count is as above. If not then we use the 9076 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9077 // as if the backedge is taken at least once max(End,Start) is End and so the 9078 // result is as above, and if not max(End,Start) is Start so we get a backedge 9079 // count of zero. 9080 const SCEV *BECount; 9081 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9082 BECount = BECountIfBackedgeTaken; 9083 else { 9084 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9085 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9086 } 9087 9088 const SCEV *MaxBECount; 9089 bool MaxOrZero = false; 9090 if (isa<SCEVConstant>(BECount)) 9091 MaxBECount = BECount; 9092 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9093 // If we know exactly how many times the backedge will be taken if it's 9094 // taken at least once, then the backedge count will either be that or 9095 // zero. 9096 MaxBECount = BECountIfBackedgeTaken; 9097 MaxOrZero = true; 9098 } else { 9099 // Calculate the maximum backedge count based on the range of values 9100 // permitted by Start, End, and Stride. 9101 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 9102 : getUnsignedRange(Start).getUnsignedMin(); 9103 9104 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9105 9106 APInt StrideForMaxBECount; 9107 9108 if (PositiveStride) 9109 StrideForMaxBECount = 9110 IsSigned ? getSignedRange(Stride).getSignedMin() 9111 : getUnsignedRange(Stride).getUnsignedMin(); 9112 else 9113 // Using a stride of 1 is safe when computing max backedge taken count for 9114 // a loop with unknown stride. 9115 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9116 9117 APInt Limit = 9118 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9119 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9120 9121 // Although End can be a MAX expression we estimate MaxEnd considering only 9122 // the case End = RHS. This is safe because in the other case (End - Start) 9123 // is zero, leading to a zero maximum backedge taken count. 9124 APInt MaxEnd = 9125 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 9126 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 9127 9128 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9129 getConstant(StrideForMaxBECount), false); 9130 } 9131 9132 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9133 MaxBECount = BECount; 9134 9135 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9136 } 9137 9138 ScalarEvolution::ExitLimit 9139 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9140 const Loop *L, bool IsSigned, 9141 bool ControlsExit, bool AllowPredicates) { 9142 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9143 // We handle only IV > Invariant 9144 if (!isLoopInvariant(RHS, L)) 9145 return getCouldNotCompute(); 9146 9147 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9148 if (!IV && AllowPredicates) 9149 // Try to make this an AddRec using runtime tests, in the first X 9150 // iterations of this loop, where X is the SCEV expression found by the 9151 // algorithm below. 9152 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9153 9154 // Avoid weird loops 9155 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9156 return getCouldNotCompute(); 9157 9158 bool NoWrap = ControlsExit && 9159 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9160 9161 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9162 9163 // Avoid negative or zero stride values 9164 if (!isKnownPositive(Stride)) 9165 return getCouldNotCompute(); 9166 9167 // Avoid proven overflow cases: this will ensure that the backedge taken count 9168 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9169 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9170 // behaviors like the case of C language. 9171 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9172 return getCouldNotCompute(); 9173 9174 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9175 : ICmpInst::ICMP_UGT; 9176 9177 const SCEV *Start = IV->getStart(); 9178 const SCEV *End = RHS; 9179 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9180 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9181 9182 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9183 9184 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 9185 : getUnsignedRange(Start).getUnsignedMax(); 9186 9187 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 9188 : getUnsignedRange(Stride).getUnsignedMin(); 9189 9190 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9191 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9192 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9193 9194 // Although End can be a MIN expression we estimate MinEnd considering only 9195 // the case End = RHS. This is safe because in the other case (Start - End) 9196 // is zero, leading to a zero maximum backedge taken count. 9197 APInt MinEnd = 9198 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 9199 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 9200 9201 9202 const SCEV *MaxBECount = getCouldNotCompute(); 9203 if (isa<SCEVConstant>(BECount)) 9204 MaxBECount = BECount; 9205 else 9206 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9207 getConstant(MinStride), false); 9208 9209 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9210 MaxBECount = BECount; 9211 9212 return ExitLimit(BECount, MaxBECount, false, Predicates); 9213 } 9214 9215 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9216 ScalarEvolution &SE) const { 9217 if (Range.isFullSet()) // Infinite loop. 9218 return SE.getCouldNotCompute(); 9219 9220 // If the start is a non-zero constant, shift the range to simplify things. 9221 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9222 if (!SC->getValue()->isZero()) { 9223 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9224 Operands[0] = SE.getZero(SC->getType()); 9225 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9226 getNoWrapFlags(FlagNW)); 9227 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9228 return ShiftedAddRec->getNumIterationsInRange( 9229 Range.subtract(SC->getAPInt()), SE); 9230 // This is strange and shouldn't happen. 9231 return SE.getCouldNotCompute(); 9232 } 9233 9234 // The only time we can solve this is when we have all constant indices. 9235 // Otherwise, we cannot determine the overflow conditions. 9236 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9237 return SE.getCouldNotCompute(); 9238 9239 // Okay at this point we know that all elements of the chrec are constants and 9240 // that the start element is zero. 9241 9242 // First check to see if the range contains zero. If not, the first 9243 // iteration exits. 9244 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9245 if (!Range.contains(APInt(BitWidth, 0))) 9246 return SE.getZero(getType()); 9247 9248 if (isAffine()) { 9249 // If this is an affine expression then we have this situation: 9250 // Solve {0,+,A} in Range === Ax in Range 9251 9252 // We know that zero is in the range. If A is positive then we know that 9253 // the upper value of the range must be the first possible exit value. 9254 // If A is negative then the lower of the range is the last possible loop 9255 // value. Also note that we already checked for a full range. 9256 APInt One(BitWidth,1); 9257 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9258 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 9259 9260 // The exit value should be (End+A)/A. 9261 APInt ExitVal = (End + A).udiv(A); 9262 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9263 9264 // Evaluate at the exit value. If we really did fall out of the valid 9265 // range, then we computed our trip count, otherwise wrap around or other 9266 // things must have happened. 9267 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9268 if (Range.contains(Val->getValue())) 9269 return SE.getCouldNotCompute(); // Something strange happened 9270 9271 // Ensure that the previous value is in the range. This is a sanity check. 9272 assert(Range.contains( 9273 EvaluateConstantChrecAtConstant(this, 9274 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 9275 "Linear scev computation is off in a bad way!"); 9276 return SE.getConstant(ExitValue); 9277 } else if (isQuadratic()) { 9278 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9279 // quadratic equation to solve it. To do this, we must frame our problem in 9280 // terms of figuring out when zero is crossed, instead of when 9281 // Range.getUpper() is crossed. 9282 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9283 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9284 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9285 9286 // Next, solve the constructed addrec 9287 if (auto Roots = 9288 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9289 const SCEVConstant *R1 = Roots->first; 9290 const SCEVConstant *R2 = Roots->second; 9291 // Pick the smallest positive root value. 9292 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9293 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9294 if (!CB->getZExtValue()) 9295 std::swap(R1, R2); // R1 is the minimum root now. 9296 9297 // Make sure the root is not off by one. The returned iteration should 9298 // not be in the range, but the previous one should be. When solving 9299 // for "X*X < 5", for example, we should not return a root of 2. 9300 ConstantInt *R1Val = 9301 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9302 if (Range.contains(R1Val->getValue())) { 9303 // The next iteration must be out of the range... 9304 ConstantInt *NextVal = 9305 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9306 9307 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9308 if (!Range.contains(R1Val->getValue())) 9309 return SE.getConstant(NextVal); 9310 return SE.getCouldNotCompute(); // Something strange happened 9311 } 9312 9313 // If R1 was not in the range, then it is a good return value. Make 9314 // sure that R1-1 WAS in the range though, just in case. 9315 ConstantInt *NextVal = 9316 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9317 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9318 if (Range.contains(R1Val->getValue())) 9319 return R1; 9320 return SE.getCouldNotCompute(); // Something strange happened 9321 } 9322 } 9323 } 9324 9325 return SE.getCouldNotCompute(); 9326 } 9327 9328 // Return true when S contains at least an undef value. 9329 static inline bool containsUndefs(const SCEV *S) { 9330 return SCEVExprContains(S, [](const SCEV *S) { 9331 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9332 return isa<UndefValue>(SU->getValue()); 9333 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9334 return isa<UndefValue>(SC->getValue()); 9335 return false; 9336 }); 9337 } 9338 9339 namespace { 9340 // Collect all steps of SCEV expressions. 9341 struct SCEVCollectStrides { 9342 ScalarEvolution &SE; 9343 SmallVectorImpl<const SCEV *> &Strides; 9344 9345 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9346 : SE(SE), Strides(S) {} 9347 9348 bool follow(const SCEV *S) { 9349 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9350 Strides.push_back(AR->getStepRecurrence(SE)); 9351 return true; 9352 } 9353 bool isDone() const { return false; } 9354 }; 9355 9356 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9357 struct SCEVCollectTerms { 9358 SmallVectorImpl<const SCEV *> &Terms; 9359 9360 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9361 : Terms(T) {} 9362 9363 bool follow(const SCEV *S) { 9364 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9365 isa<SCEVSignExtendExpr>(S)) { 9366 if (!containsUndefs(S)) 9367 Terms.push_back(S); 9368 9369 // Stop recursion: once we collected a term, do not walk its operands. 9370 return false; 9371 } 9372 9373 // Keep looking. 9374 return true; 9375 } 9376 bool isDone() const { return false; } 9377 }; 9378 9379 // Check if a SCEV contains an AddRecExpr. 9380 struct SCEVHasAddRec { 9381 bool &ContainsAddRec; 9382 9383 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9384 ContainsAddRec = false; 9385 } 9386 9387 bool follow(const SCEV *S) { 9388 if (isa<SCEVAddRecExpr>(S)) { 9389 ContainsAddRec = true; 9390 9391 // Stop recursion: once we collected a term, do not walk its operands. 9392 return false; 9393 } 9394 9395 // Keep looking. 9396 return true; 9397 } 9398 bool isDone() const { return false; } 9399 }; 9400 9401 // Find factors that are multiplied with an expression that (possibly as a 9402 // subexpression) contains an AddRecExpr. In the expression: 9403 // 9404 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9405 // 9406 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9407 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9408 // parameters as they form a product with an induction variable. 9409 // 9410 // This collector expects all array size parameters to be in the same MulExpr. 9411 // It might be necessary to later add support for collecting parameters that are 9412 // spread over different nested MulExpr. 9413 struct SCEVCollectAddRecMultiplies { 9414 SmallVectorImpl<const SCEV *> &Terms; 9415 ScalarEvolution &SE; 9416 9417 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9418 : Terms(T), SE(SE) {} 9419 9420 bool follow(const SCEV *S) { 9421 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9422 bool HasAddRec = false; 9423 SmallVector<const SCEV *, 0> Operands; 9424 for (auto Op : Mul->operands()) { 9425 if (isa<SCEVUnknown>(Op)) { 9426 Operands.push_back(Op); 9427 } else { 9428 bool ContainsAddRec; 9429 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9430 visitAll(Op, ContiansAddRec); 9431 HasAddRec |= ContainsAddRec; 9432 } 9433 } 9434 if (Operands.size() == 0) 9435 return true; 9436 9437 if (!HasAddRec) 9438 return false; 9439 9440 Terms.push_back(SE.getMulExpr(Operands)); 9441 // Stop recursion: once we collected a term, do not walk its operands. 9442 return false; 9443 } 9444 9445 // Keep looking. 9446 return true; 9447 } 9448 bool isDone() const { return false; } 9449 }; 9450 } 9451 9452 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9453 /// two places: 9454 /// 1) The strides of AddRec expressions. 9455 /// 2) Unknowns that are multiplied with AddRec expressions. 9456 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9457 SmallVectorImpl<const SCEV *> &Terms) { 9458 SmallVector<const SCEV *, 4> Strides; 9459 SCEVCollectStrides StrideCollector(*this, Strides); 9460 visitAll(Expr, StrideCollector); 9461 9462 DEBUG({ 9463 dbgs() << "Strides:\n"; 9464 for (const SCEV *S : Strides) 9465 dbgs() << *S << "\n"; 9466 }); 9467 9468 for (const SCEV *S : Strides) { 9469 SCEVCollectTerms TermCollector(Terms); 9470 visitAll(S, TermCollector); 9471 } 9472 9473 DEBUG({ 9474 dbgs() << "Terms:\n"; 9475 for (const SCEV *T : Terms) 9476 dbgs() << *T << "\n"; 9477 }); 9478 9479 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9480 visitAll(Expr, MulCollector); 9481 } 9482 9483 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9484 SmallVectorImpl<const SCEV *> &Terms, 9485 SmallVectorImpl<const SCEV *> &Sizes) { 9486 int Last = Terms.size() - 1; 9487 const SCEV *Step = Terms[Last]; 9488 9489 // End of recursion. 9490 if (Last == 0) { 9491 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9492 SmallVector<const SCEV *, 2> Qs; 9493 for (const SCEV *Op : M->operands()) 9494 if (!isa<SCEVConstant>(Op)) 9495 Qs.push_back(Op); 9496 9497 Step = SE.getMulExpr(Qs); 9498 } 9499 9500 Sizes.push_back(Step); 9501 return true; 9502 } 9503 9504 for (const SCEV *&Term : Terms) { 9505 // Normalize the terms before the next call to findArrayDimensionsRec. 9506 const SCEV *Q, *R; 9507 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9508 9509 // Bail out when GCD does not evenly divide one of the terms. 9510 if (!R->isZero()) 9511 return false; 9512 9513 Term = Q; 9514 } 9515 9516 // Remove all SCEVConstants. 9517 Terms.erase( 9518 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9519 Terms.end()); 9520 9521 if (Terms.size() > 0) 9522 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9523 return false; 9524 9525 Sizes.push_back(Step); 9526 return true; 9527 } 9528 9529 9530 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9531 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9532 for (const SCEV *T : Terms) 9533 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9534 return true; 9535 return false; 9536 } 9537 9538 // Return the number of product terms in S. 9539 static inline int numberOfTerms(const SCEV *S) { 9540 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9541 return Expr->getNumOperands(); 9542 return 1; 9543 } 9544 9545 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9546 if (isa<SCEVConstant>(T)) 9547 return nullptr; 9548 9549 if (isa<SCEVUnknown>(T)) 9550 return T; 9551 9552 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9553 SmallVector<const SCEV *, 2> Factors; 9554 for (const SCEV *Op : M->operands()) 9555 if (!isa<SCEVConstant>(Op)) 9556 Factors.push_back(Op); 9557 9558 return SE.getMulExpr(Factors); 9559 } 9560 9561 return T; 9562 } 9563 9564 /// Return the size of an element read or written by Inst. 9565 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9566 Type *Ty; 9567 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9568 Ty = Store->getValueOperand()->getType(); 9569 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9570 Ty = Load->getType(); 9571 else 9572 return nullptr; 9573 9574 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9575 return getSizeOfExpr(ETy, Ty); 9576 } 9577 9578 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9579 SmallVectorImpl<const SCEV *> &Sizes, 9580 const SCEV *ElementSize) const { 9581 if (Terms.size() < 1 || !ElementSize) 9582 return; 9583 9584 // Early return when Terms do not contain parameters: we do not delinearize 9585 // non parametric SCEVs. 9586 if (!containsParameters(Terms)) 9587 return; 9588 9589 DEBUG({ 9590 dbgs() << "Terms:\n"; 9591 for (const SCEV *T : Terms) 9592 dbgs() << *T << "\n"; 9593 }); 9594 9595 // Remove duplicates. 9596 std::sort(Terms.begin(), Terms.end()); 9597 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9598 9599 // Put larger terms first. 9600 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9601 return numberOfTerms(LHS) > numberOfTerms(RHS); 9602 }); 9603 9604 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9605 9606 // Try to divide all terms by the element size. If term is not divisible by 9607 // element size, proceed with the original term. 9608 for (const SCEV *&Term : Terms) { 9609 const SCEV *Q, *R; 9610 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9611 if (!Q->isZero()) 9612 Term = Q; 9613 } 9614 9615 SmallVector<const SCEV *, 4> NewTerms; 9616 9617 // Remove constant factors. 9618 for (const SCEV *T : Terms) 9619 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9620 NewTerms.push_back(NewT); 9621 9622 DEBUG({ 9623 dbgs() << "Terms after sorting:\n"; 9624 for (const SCEV *T : NewTerms) 9625 dbgs() << *T << "\n"; 9626 }); 9627 9628 if (NewTerms.empty() || 9629 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9630 Sizes.clear(); 9631 return; 9632 } 9633 9634 // The last element to be pushed into Sizes is the size of an element. 9635 Sizes.push_back(ElementSize); 9636 9637 DEBUG({ 9638 dbgs() << "Sizes:\n"; 9639 for (const SCEV *S : Sizes) 9640 dbgs() << *S << "\n"; 9641 }); 9642 } 9643 9644 void ScalarEvolution::computeAccessFunctions( 9645 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9646 SmallVectorImpl<const SCEV *> &Sizes) { 9647 9648 // Early exit in case this SCEV is not an affine multivariate function. 9649 if (Sizes.empty()) 9650 return; 9651 9652 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9653 if (!AR->isAffine()) 9654 return; 9655 9656 const SCEV *Res = Expr; 9657 int Last = Sizes.size() - 1; 9658 for (int i = Last; i >= 0; i--) { 9659 const SCEV *Q, *R; 9660 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9661 9662 DEBUG({ 9663 dbgs() << "Res: " << *Res << "\n"; 9664 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9665 dbgs() << "Res divided by Sizes[i]:\n"; 9666 dbgs() << "Quotient: " << *Q << "\n"; 9667 dbgs() << "Remainder: " << *R << "\n"; 9668 }); 9669 9670 Res = Q; 9671 9672 // Do not record the last subscript corresponding to the size of elements in 9673 // the array. 9674 if (i == Last) { 9675 9676 // Bail out if the remainder is too complex. 9677 if (isa<SCEVAddRecExpr>(R)) { 9678 Subscripts.clear(); 9679 Sizes.clear(); 9680 return; 9681 } 9682 9683 continue; 9684 } 9685 9686 // Record the access function for the current subscript. 9687 Subscripts.push_back(R); 9688 } 9689 9690 // Also push in last position the remainder of the last division: it will be 9691 // the access function of the innermost dimension. 9692 Subscripts.push_back(Res); 9693 9694 std::reverse(Subscripts.begin(), Subscripts.end()); 9695 9696 DEBUG({ 9697 dbgs() << "Subscripts:\n"; 9698 for (const SCEV *S : Subscripts) 9699 dbgs() << *S << "\n"; 9700 }); 9701 } 9702 9703 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9704 /// sizes of an array access. Returns the remainder of the delinearization that 9705 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9706 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9707 /// expressions in the stride and base of a SCEV corresponding to the 9708 /// computation of a GCD (greatest common divisor) of base and stride. When 9709 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9710 /// 9711 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9712 /// 9713 /// void foo(long n, long m, long o, double A[n][m][o]) { 9714 /// 9715 /// for (long i = 0; i < n; i++) 9716 /// for (long j = 0; j < m; j++) 9717 /// for (long k = 0; k < o; k++) 9718 /// A[i][j][k] = 1.0; 9719 /// } 9720 /// 9721 /// the delinearization input is the following AddRec SCEV: 9722 /// 9723 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9724 /// 9725 /// From this SCEV, we are able to say that the base offset of the access is %A 9726 /// because it appears as an offset that does not divide any of the strides in 9727 /// the loops: 9728 /// 9729 /// CHECK: Base offset: %A 9730 /// 9731 /// and then SCEV->delinearize determines the size of some of the dimensions of 9732 /// the array as these are the multiples by which the strides are happening: 9733 /// 9734 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9735 /// 9736 /// Note that the outermost dimension remains of UnknownSize because there are 9737 /// no strides that would help identifying the size of the last dimension: when 9738 /// the array has been statically allocated, one could compute the size of that 9739 /// dimension by dividing the overall size of the array by the size of the known 9740 /// dimensions: %m * %o * 8. 9741 /// 9742 /// Finally delinearize provides the access functions for the array reference 9743 /// that does correspond to A[i][j][k] of the above C testcase: 9744 /// 9745 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9746 /// 9747 /// The testcases are checking the output of a function pass: 9748 /// DelinearizationPass that walks through all loads and stores of a function 9749 /// asking for the SCEV of the memory access with respect to all enclosing 9750 /// loops, calling SCEV->delinearize on that and printing the results. 9751 9752 void ScalarEvolution::delinearize(const SCEV *Expr, 9753 SmallVectorImpl<const SCEV *> &Subscripts, 9754 SmallVectorImpl<const SCEV *> &Sizes, 9755 const SCEV *ElementSize) { 9756 // First step: collect parametric terms. 9757 SmallVector<const SCEV *, 4> Terms; 9758 collectParametricTerms(Expr, Terms); 9759 9760 if (Terms.empty()) 9761 return; 9762 9763 // Second step: find subscript sizes. 9764 findArrayDimensions(Terms, Sizes, ElementSize); 9765 9766 if (Sizes.empty()) 9767 return; 9768 9769 // Third step: compute the access functions for each subscript. 9770 computeAccessFunctions(Expr, Subscripts, Sizes); 9771 9772 if (Subscripts.empty()) 9773 return; 9774 9775 DEBUG({ 9776 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9777 dbgs() << "ArrayDecl[UnknownSize]"; 9778 for (const SCEV *S : Sizes) 9779 dbgs() << "[" << *S << "]"; 9780 9781 dbgs() << "\nArrayRef"; 9782 for (const SCEV *S : Subscripts) 9783 dbgs() << "[" << *S << "]"; 9784 dbgs() << "\n"; 9785 }); 9786 } 9787 9788 //===----------------------------------------------------------------------===// 9789 // SCEVCallbackVH Class Implementation 9790 //===----------------------------------------------------------------------===// 9791 9792 void ScalarEvolution::SCEVCallbackVH::deleted() { 9793 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9794 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9795 SE->ConstantEvolutionLoopExitValue.erase(PN); 9796 SE->eraseValueFromMap(getValPtr()); 9797 // this now dangles! 9798 } 9799 9800 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9801 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9802 9803 // Forget all the expressions associated with users of the old value, 9804 // so that future queries will recompute the expressions using the new 9805 // value. 9806 Value *Old = getValPtr(); 9807 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9808 SmallPtrSet<User *, 8> Visited; 9809 while (!Worklist.empty()) { 9810 User *U = Worklist.pop_back_val(); 9811 // Deleting the Old value will cause this to dangle. Postpone 9812 // that until everything else is done. 9813 if (U == Old) 9814 continue; 9815 if (!Visited.insert(U).second) 9816 continue; 9817 if (PHINode *PN = dyn_cast<PHINode>(U)) 9818 SE->ConstantEvolutionLoopExitValue.erase(PN); 9819 SE->eraseValueFromMap(U); 9820 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9821 } 9822 // Delete the Old value. 9823 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9824 SE->ConstantEvolutionLoopExitValue.erase(PN); 9825 SE->eraseValueFromMap(Old); 9826 // this now dangles! 9827 } 9828 9829 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9830 : CallbackVH(V), SE(se) {} 9831 9832 //===----------------------------------------------------------------------===// 9833 // ScalarEvolution Class Implementation 9834 //===----------------------------------------------------------------------===// 9835 9836 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9837 AssumptionCache &AC, DominatorTree &DT, 9838 LoopInfo &LI) 9839 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9840 CouldNotCompute(new SCEVCouldNotCompute()), 9841 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9842 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9843 FirstUnknown(nullptr) { 9844 9845 // To use guards for proving predicates, we need to scan every instruction in 9846 // relevant basic blocks, and not just terminators. Doing this is a waste of 9847 // time if the IR does not actually contain any calls to 9848 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9849 // 9850 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9851 // to _add_ guards to the module when there weren't any before, and wants 9852 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9853 // efficient in lieu of being smart in that rather obscure case. 9854 9855 auto *GuardDecl = F.getParent()->getFunction( 9856 Intrinsic::getName(Intrinsic::experimental_guard)); 9857 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9858 } 9859 9860 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9861 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9862 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9863 ValueExprMap(std::move(Arg.ValueExprMap)), 9864 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9865 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9866 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 9867 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9868 PredicatedBackedgeTakenCounts( 9869 std::move(Arg.PredicatedBackedgeTakenCounts)), 9870 ConstantEvolutionLoopExitValue( 9871 std::move(Arg.ConstantEvolutionLoopExitValue)), 9872 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9873 LoopDispositions(std::move(Arg.LoopDispositions)), 9874 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9875 BlockDispositions(std::move(Arg.BlockDispositions)), 9876 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9877 SignedRanges(std::move(Arg.SignedRanges)), 9878 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9879 UniquePreds(std::move(Arg.UniquePreds)), 9880 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9881 FirstUnknown(Arg.FirstUnknown) { 9882 Arg.FirstUnknown = nullptr; 9883 } 9884 9885 ScalarEvolution::~ScalarEvolution() { 9886 // Iterate through all the SCEVUnknown instances and call their 9887 // destructors, so that they release their references to their values. 9888 for (SCEVUnknown *U = FirstUnknown; U;) { 9889 SCEVUnknown *Tmp = U; 9890 U = U->Next; 9891 Tmp->~SCEVUnknown(); 9892 } 9893 FirstUnknown = nullptr; 9894 9895 ExprValueMap.clear(); 9896 ValueExprMap.clear(); 9897 HasRecMap.clear(); 9898 9899 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9900 // that a loop had multiple computable exits. 9901 for (auto &BTCI : BackedgeTakenCounts) 9902 BTCI.second.clear(); 9903 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9904 BTCI.second.clear(); 9905 9906 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9907 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9908 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9909 } 9910 9911 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9912 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9913 } 9914 9915 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9916 const Loop *L) { 9917 // Print all inner loops first 9918 for (Loop *I : *L) 9919 PrintLoopInfo(OS, SE, I); 9920 9921 OS << "Loop "; 9922 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9923 OS << ": "; 9924 9925 SmallVector<BasicBlock *, 8> ExitBlocks; 9926 L->getExitBlocks(ExitBlocks); 9927 if (ExitBlocks.size() != 1) 9928 OS << "<multiple exits> "; 9929 9930 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9931 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9932 } else { 9933 OS << "Unpredictable backedge-taken count. "; 9934 } 9935 9936 OS << "\n" 9937 "Loop "; 9938 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9939 OS << ": "; 9940 9941 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9942 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9943 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9944 OS << ", actual taken count either this or zero."; 9945 } else { 9946 OS << "Unpredictable max backedge-taken count. "; 9947 } 9948 9949 OS << "\n" 9950 "Loop "; 9951 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9952 OS << ": "; 9953 9954 SCEVUnionPredicate Pred; 9955 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9956 if (!isa<SCEVCouldNotCompute>(PBT)) { 9957 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9958 OS << " Predicates:\n"; 9959 Pred.print(OS, 4); 9960 } else { 9961 OS << "Unpredictable predicated backedge-taken count. "; 9962 } 9963 OS << "\n"; 9964 9965 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9966 OS << "Loop "; 9967 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9968 OS << ": "; 9969 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 9970 } 9971 } 9972 9973 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9974 switch (LD) { 9975 case ScalarEvolution::LoopVariant: 9976 return "Variant"; 9977 case ScalarEvolution::LoopInvariant: 9978 return "Invariant"; 9979 case ScalarEvolution::LoopComputable: 9980 return "Computable"; 9981 } 9982 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9983 } 9984 9985 void ScalarEvolution::print(raw_ostream &OS) const { 9986 // ScalarEvolution's implementation of the print method is to print 9987 // out SCEV values of all instructions that are interesting. Doing 9988 // this potentially causes it to create new SCEV objects though, 9989 // which technically conflicts with the const qualifier. This isn't 9990 // observable from outside the class though, so casting away the 9991 // const isn't dangerous. 9992 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9993 9994 OS << "Classifying expressions for: "; 9995 F.printAsOperand(OS, /*PrintType=*/false); 9996 OS << "\n"; 9997 for (Instruction &I : instructions(F)) 9998 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9999 OS << I << '\n'; 10000 OS << " --> "; 10001 const SCEV *SV = SE.getSCEV(&I); 10002 SV->print(OS); 10003 if (!isa<SCEVCouldNotCompute>(SV)) { 10004 OS << " U: "; 10005 SE.getUnsignedRange(SV).print(OS); 10006 OS << " S: "; 10007 SE.getSignedRange(SV).print(OS); 10008 } 10009 10010 const Loop *L = LI.getLoopFor(I.getParent()); 10011 10012 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10013 if (AtUse != SV) { 10014 OS << " --> "; 10015 AtUse->print(OS); 10016 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10017 OS << " U: "; 10018 SE.getUnsignedRange(AtUse).print(OS); 10019 OS << " S: "; 10020 SE.getSignedRange(AtUse).print(OS); 10021 } 10022 } 10023 10024 if (L) { 10025 OS << "\t\t" "Exits: "; 10026 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10027 if (!SE.isLoopInvariant(ExitValue, L)) { 10028 OS << "<<Unknown>>"; 10029 } else { 10030 OS << *ExitValue; 10031 } 10032 10033 bool First = true; 10034 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10035 if (First) { 10036 OS << "\t\t" "LoopDispositions: { "; 10037 First = false; 10038 } else { 10039 OS << ", "; 10040 } 10041 10042 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10043 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10044 } 10045 10046 for (auto *InnerL : depth_first(L)) { 10047 if (InnerL == L) 10048 continue; 10049 if (First) { 10050 OS << "\t\t" "LoopDispositions: { "; 10051 First = false; 10052 } else { 10053 OS << ", "; 10054 } 10055 10056 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10057 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10058 } 10059 10060 OS << " }"; 10061 } 10062 10063 OS << "\n"; 10064 } 10065 10066 OS << "Determining loop execution counts for: "; 10067 F.printAsOperand(OS, /*PrintType=*/false); 10068 OS << "\n"; 10069 for (Loop *I : LI) 10070 PrintLoopInfo(OS, &SE, I); 10071 } 10072 10073 ScalarEvolution::LoopDisposition 10074 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10075 auto &Values = LoopDispositions[S]; 10076 for (auto &V : Values) { 10077 if (V.getPointer() == L) 10078 return V.getInt(); 10079 } 10080 Values.emplace_back(L, LoopVariant); 10081 LoopDisposition D = computeLoopDisposition(S, L); 10082 auto &Values2 = LoopDispositions[S]; 10083 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10084 if (V.getPointer() == L) { 10085 V.setInt(D); 10086 break; 10087 } 10088 } 10089 return D; 10090 } 10091 10092 ScalarEvolution::LoopDisposition 10093 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10094 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10095 case scConstant: 10096 return LoopInvariant; 10097 case scTruncate: 10098 case scZeroExtend: 10099 case scSignExtend: 10100 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10101 case scAddRecExpr: { 10102 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10103 10104 // If L is the addrec's loop, it's computable. 10105 if (AR->getLoop() == L) 10106 return LoopComputable; 10107 10108 // Add recurrences are never invariant in the function-body (null loop). 10109 if (!L) 10110 return LoopVariant; 10111 10112 // This recurrence is variant w.r.t. L if L contains AR's loop. 10113 if (L->contains(AR->getLoop())) 10114 return LoopVariant; 10115 10116 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10117 if (AR->getLoop()->contains(L)) 10118 return LoopInvariant; 10119 10120 // This recurrence is variant w.r.t. L if any of its operands 10121 // are variant. 10122 for (auto *Op : AR->operands()) 10123 if (!isLoopInvariant(Op, L)) 10124 return LoopVariant; 10125 10126 // Otherwise it's loop-invariant. 10127 return LoopInvariant; 10128 } 10129 case scAddExpr: 10130 case scMulExpr: 10131 case scUMaxExpr: 10132 case scSMaxExpr: { 10133 bool HasVarying = false; 10134 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10135 LoopDisposition D = getLoopDisposition(Op, L); 10136 if (D == LoopVariant) 10137 return LoopVariant; 10138 if (D == LoopComputable) 10139 HasVarying = true; 10140 } 10141 return HasVarying ? LoopComputable : LoopInvariant; 10142 } 10143 case scUDivExpr: { 10144 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10145 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10146 if (LD == LoopVariant) 10147 return LoopVariant; 10148 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10149 if (RD == LoopVariant) 10150 return LoopVariant; 10151 return (LD == LoopInvariant && RD == LoopInvariant) ? 10152 LoopInvariant : LoopComputable; 10153 } 10154 case scUnknown: 10155 // All non-instruction values are loop invariant. All instructions are loop 10156 // invariant if they are not contained in the specified loop. 10157 // Instructions are never considered invariant in the function body 10158 // (null loop) because they are defined within the "loop". 10159 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10160 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10161 return LoopInvariant; 10162 case scCouldNotCompute: 10163 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10164 } 10165 llvm_unreachable("Unknown SCEV kind!"); 10166 } 10167 10168 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10169 return getLoopDisposition(S, L) == LoopInvariant; 10170 } 10171 10172 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10173 return getLoopDisposition(S, L) == LoopComputable; 10174 } 10175 10176 ScalarEvolution::BlockDisposition 10177 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10178 auto &Values = BlockDispositions[S]; 10179 for (auto &V : Values) { 10180 if (V.getPointer() == BB) 10181 return V.getInt(); 10182 } 10183 Values.emplace_back(BB, DoesNotDominateBlock); 10184 BlockDisposition D = computeBlockDisposition(S, BB); 10185 auto &Values2 = BlockDispositions[S]; 10186 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10187 if (V.getPointer() == BB) { 10188 V.setInt(D); 10189 break; 10190 } 10191 } 10192 return D; 10193 } 10194 10195 ScalarEvolution::BlockDisposition 10196 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10197 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10198 case scConstant: 10199 return ProperlyDominatesBlock; 10200 case scTruncate: 10201 case scZeroExtend: 10202 case scSignExtend: 10203 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10204 case scAddRecExpr: { 10205 // This uses a "dominates" query instead of "properly dominates" query 10206 // to test for proper dominance too, because the instruction which 10207 // produces the addrec's value is a PHI, and a PHI effectively properly 10208 // dominates its entire containing block. 10209 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10210 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10211 return DoesNotDominateBlock; 10212 10213 // Fall through into SCEVNAryExpr handling. 10214 LLVM_FALLTHROUGH; 10215 } 10216 case scAddExpr: 10217 case scMulExpr: 10218 case scUMaxExpr: 10219 case scSMaxExpr: { 10220 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10221 bool Proper = true; 10222 for (const SCEV *NAryOp : NAry->operands()) { 10223 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10224 if (D == DoesNotDominateBlock) 10225 return DoesNotDominateBlock; 10226 if (D == DominatesBlock) 10227 Proper = false; 10228 } 10229 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10230 } 10231 case scUDivExpr: { 10232 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10233 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10234 BlockDisposition LD = getBlockDisposition(LHS, BB); 10235 if (LD == DoesNotDominateBlock) 10236 return DoesNotDominateBlock; 10237 BlockDisposition RD = getBlockDisposition(RHS, BB); 10238 if (RD == DoesNotDominateBlock) 10239 return DoesNotDominateBlock; 10240 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10241 ProperlyDominatesBlock : DominatesBlock; 10242 } 10243 case scUnknown: 10244 if (Instruction *I = 10245 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10246 if (I->getParent() == BB) 10247 return DominatesBlock; 10248 if (DT.properlyDominates(I->getParent(), BB)) 10249 return ProperlyDominatesBlock; 10250 return DoesNotDominateBlock; 10251 } 10252 return ProperlyDominatesBlock; 10253 case scCouldNotCompute: 10254 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10255 } 10256 llvm_unreachable("Unknown SCEV kind!"); 10257 } 10258 10259 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10260 return getBlockDisposition(S, BB) >= DominatesBlock; 10261 } 10262 10263 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10264 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10265 } 10266 10267 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10268 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10269 } 10270 10271 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10272 ValuesAtScopes.erase(S); 10273 LoopDispositions.erase(S); 10274 BlockDispositions.erase(S); 10275 UnsignedRanges.erase(S); 10276 SignedRanges.erase(S); 10277 ExprValueMap.erase(S); 10278 HasRecMap.erase(S); 10279 MinTrailingZerosCache.erase(S); 10280 10281 auto RemoveSCEVFromBackedgeMap = 10282 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10283 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10284 BackedgeTakenInfo &BEInfo = I->second; 10285 if (BEInfo.hasOperand(S, this)) { 10286 BEInfo.clear(); 10287 Map.erase(I++); 10288 } else 10289 ++I; 10290 } 10291 }; 10292 10293 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10294 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10295 } 10296 10297 void ScalarEvolution::verify() const { 10298 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10299 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10300 10301 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 10302 10303 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 10304 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 10305 const SCEV *visitConstant(const SCEVConstant *Constant) { 10306 return SE.getConstant(Constant->getAPInt()); 10307 } 10308 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10309 return SE.getUnknown(Expr->getValue()); 10310 } 10311 10312 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 10313 return SE.getCouldNotCompute(); 10314 } 10315 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 10316 }; 10317 10318 SCEVMapper SCM(SE2); 10319 10320 while (!LoopStack.empty()) { 10321 auto *L = LoopStack.pop_back_val(); 10322 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 10323 10324 auto *CurBECount = SCM.visit( 10325 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 10326 auto *NewBECount = SE2.getBackedgeTakenCount(L); 10327 10328 if (CurBECount == SE2.getCouldNotCompute() || 10329 NewBECount == SE2.getCouldNotCompute()) { 10330 // NB! This situation is legal, but is very suspicious -- whatever pass 10331 // change the loop to make a trip count go from could not compute to 10332 // computable or vice-versa *should have* invalidated SCEV. However, we 10333 // choose not to assert here (for now) since we don't want false 10334 // positives. 10335 continue; 10336 } 10337 10338 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 10339 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 10340 // not propagate undef aggressively). This means we can (and do) fail 10341 // verification in cases where a transform makes the trip count of a loop 10342 // go from "undef" to "undef+1" (say). The transform is fine, since in 10343 // both cases the loop iterates "undef" times, but SCEV thinks we 10344 // increased the trip count of the loop by 1 incorrectly. 10345 continue; 10346 } 10347 10348 if (SE.getTypeSizeInBits(CurBECount->getType()) > 10349 SE.getTypeSizeInBits(NewBECount->getType())) 10350 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 10351 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 10352 SE.getTypeSizeInBits(NewBECount->getType())) 10353 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 10354 10355 auto *ConstantDelta = 10356 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 10357 10358 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 10359 dbgs() << "Trip Count Changed!\n"; 10360 dbgs() << "Old: " << *CurBECount << "\n"; 10361 dbgs() << "New: " << *NewBECount << "\n"; 10362 dbgs() << "Delta: " << *ConstantDelta << "\n"; 10363 std::abort(); 10364 } 10365 } 10366 } 10367 10368 bool ScalarEvolution::invalidate( 10369 Function &F, const PreservedAnalyses &PA, 10370 FunctionAnalysisManager::Invalidator &Inv) { 10371 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10372 // of its dependencies is invalidated. 10373 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10374 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10375 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10376 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10377 Inv.invalidate<LoopAnalysis>(F, PA); 10378 } 10379 10380 AnalysisKey ScalarEvolutionAnalysis::Key; 10381 10382 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10383 FunctionAnalysisManager &AM) { 10384 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10385 AM.getResult<AssumptionAnalysis>(F), 10386 AM.getResult<DominatorTreeAnalysis>(F), 10387 AM.getResult<LoopAnalysis>(F)); 10388 } 10389 10390 PreservedAnalyses 10391 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10392 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10393 return PreservedAnalyses::all(); 10394 } 10395 10396 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10397 "Scalar Evolution Analysis", false, true) 10398 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10399 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10400 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10401 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10402 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10403 "Scalar Evolution Analysis", false, true) 10404 char ScalarEvolutionWrapperPass::ID = 0; 10405 10406 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10407 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10408 } 10409 10410 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10411 SE.reset(new ScalarEvolution( 10412 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10413 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10414 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10415 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10416 return false; 10417 } 10418 10419 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10420 10421 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10422 SE->print(OS); 10423 } 10424 10425 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10426 if (!VerifySCEV) 10427 return; 10428 10429 SE->verify(); 10430 } 10431 10432 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10433 AU.setPreservesAll(); 10434 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10435 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10436 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10437 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10438 } 10439 10440 const SCEVPredicate * 10441 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10442 const SCEVConstant *RHS) { 10443 FoldingSetNodeID ID; 10444 // Unique this node based on the arguments 10445 ID.AddInteger(SCEVPredicate::P_Equal); 10446 ID.AddPointer(LHS); 10447 ID.AddPointer(RHS); 10448 void *IP = nullptr; 10449 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10450 return S; 10451 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10452 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10453 UniquePreds.InsertNode(Eq, IP); 10454 return Eq; 10455 } 10456 10457 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10458 const SCEVAddRecExpr *AR, 10459 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10460 FoldingSetNodeID ID; 10461 // Unique this node based on the arguments 10462 ID.AddInteger(SCEVPredicate::P_Wrap); 10463 ID.AddPointer(AR); 10464 ID.AddInteger(AddedFlags); 10465 void *IP = nullptr; 10466 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10467 return S; 10468 auto *OF = new (SCEVAllocator) 10469 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10470 UniquePreds.InsertNode(OF, IP); 10471 return OF; 10472 } 10473 10474 namespace { 10475 10476 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10477 public: 10478 /// Rewrites \p S in the context of a loop L and the SCEV predication 10479 /// infrastructure. 10480 /// 10481 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10482 /// equivalences present in \p Pred. 10483 /// 10484 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10485 /// \p NewPreds such that the result will be an AddRecExpr. 10486 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10487 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10488 SCEVUnionPredicate *Pred) { 10489 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10490 return Rewriter.visit(S); 10491 } 10492 10493 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10494 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10495 SCEVUnionPredicate *Pred) 10496 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10497 10498 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10499 if (Pred) { 10500 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10501 for (auto *Pred : ExprPreds) 10502 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10503 if (IPred->getLHS() == Expr) 10504 return IPred->getRHS(); 10505 } 10506 10507 return Expr; 10508 } 10509 10510 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10511 const SCEV *Operand = visit(Expr->getOperand()); 10512 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10513 if (AR && AR->getLoop() == L && AR->isAffine()) { 10514 // This couldn't be folded because the operand didn't have the nuw 10515 // flag. Add the nusw flag as an assumption that we could make. 10516 const SCEV *Step = AR->getStepRecurrence(SE); 10517 Type *Ty = Expr->getType(); 10518 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10519 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10520 SE.getSignExtendExpr(Step, Ty), L, 10521 AR->getNoWrapFlags()); 10522 } 10523 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10524 } 10525 10526 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10527 const SCEV *Operand = visit(Expr->getOperand()); 10528 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10529 if (AR && AR->getLoop() == L && AR->isAffine()) { 10530 // This couldn't be folded because the operand didn't have the nsw 10531 // flag. Add the nssw flag as an assumption that we could make. 10532 const SCEV *Step = AR->getStepRecurrence(SE); 10533 Type *Ty = Expr->getType(); 10534 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10535 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10536 SE.getSignExtendExpr(Step, Ty), L, 10537 AR->getNoWrapFlags()); 10538 } 10539 return SE.getSignExtendExpr(Operand, Expr->getType()); 10540 } 10541 10542 private: 10543 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10544 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10545 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10546 if (!NewPreds) { 10547 // Check if we've already made this assumption. 10548 return Pred && Pred->implies(A); 10549 } 10550 NewPreds->insert(A); 10551 return true; 10552 } 10553 10554 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10555 SCEVUnionPredicate *Pred; 10556 const Loop *L; 10557 }; 10558 } // end anonymous namespace 10559 10560 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10561 SCEVUnionPredicate &Preds) { 10562 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10563 } 10564 10565 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10566 const SCEV *S, const Loop *L, 10567 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10568 10569 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10570 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10571 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10572 10573 if (!AddRec) 10574 return nullptr; 10575 10576 // Since the transformation was successful, we can now transfer the SCEV 10577 // predicates. 10578 for (auto *P : TransformPreds) 10579 Preds.insert(P); 10580 10581 return AddRec; 10582 } 10583 10584 /// SCEV predicates 10585 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10586 SCEVPredicateKind Kind) 10587 : FastID(ID), Kind(Kind) {} 10588 10589 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10590 const SCEVUnknown *LHS, 10591 const SCEVConstant *RHS) 10592 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10593 10594 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10595 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10596 10597 if (!Op) 10598 return false; 10599 10600 return Op->LHS == LHS && Op->RHS == RHS; 10601 } 10602 10603 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10604 10605 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10606 10607 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10608 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10609 } 10610 10611 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10612 const SCEVAddRecExpr *AR, 10613 IncrementWrapFlags Flags) 10614 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10615 10616 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10617 10618 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10619 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10620 10621 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10622 } 10623 10624 bool SCEVWrapPredicate::isAlwaysTrue() const { 10625 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10626 IncrementWrapFlags IFlags = Flags; 10627 10628 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10629 IFlags = clearFlags(IFlags, IncrementNSSW); 10630 10631 return IFlags == IncrementAnyWrap; 10632 } 10633 10634 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10635 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10636 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10637 OS << "<nusw>"; 10638 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10639 OS << "<nssw>"; 10640 OS << "\n"; 10641 } 10642 10643 SCEVWrapPredicate::IncrementWrapFlags 10644 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10645 ScalarEvolution &SE) { 10646 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10647 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10648 10649 // We can safely transfer the NSW flag as NSSW. 10650 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10651 ImpliedFlags = IncrementNSSW; 10652 10653 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10654 // If the increment is positive, the SCEV NUW flag will also imply the 10655 // WrapPredicate NUSW flag. 10656 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10657 if (Step->getValue()->getValue().isNonNegative()) 10658 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10659 } 10660 10661 return ImpliedFlags; 10662 } 10663 10664 /// Union predicates don't get cached so create a dummy set ID for it. 10665 SCEVUnionPredicate::SCEVUnionPredicate() 10666 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10667 10668 bool SCEVUnionPredicate::isAlwaysTrue() const { 10669 return all_of(Preds, 10670 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10671 } 10672 10673 ArrayRef<const SCEVPredicate *> 10674 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10675 auto I = SCEVToPreds.find(Expr); 10676 if (I == SCEVToPreds.end()) 10677 return ArrayRef<const SCEVPredicate *>(); 10678 return I->second; 10679 } 10680 10681 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10682 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10683 return all_of(Set->Preds, 10684 [this](const SCEVPredicate *I) { return this->implies(I); }); 10685 10686 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10687 if (ScevPredsIt == SCEVToPreds.end()) 10688 return false; 10689 auto &SCEVPreds = ScevPredsIt->second; 10690 10691 return any_of(SCEVPreds, 10692 [N](const SCEVPredicate *I) { return I->implies(N); }); 10693 } 10694 10695 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10696 10697 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10698 for (auto Pred : Preds) 10699 Pred->print(OS, Depth); 10700 } 10701 10702 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10703 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10704 for (auto Pred : Set->Preds) 10705 add(Pred); 10706 return; 10707 } 10708 10709 if (implies(N)) 10710 return; 10711 10712 const SCEV *Key = N->getExpr(); 10713 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10714 " associated expression!"); 10715 10716 SCEVToPreds[Key].push_back(N); 10717 Preds.push_back(N); 10718 } 10719 10720 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10721 Loop &L) 10722 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10723 10724 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10725 const SCEV *Expr = SE.getSCEV(V); 10726 RewriteEntry &Entry = RewriteMap[Expr]; 10727 10728 // If we already have an entry and the version matches, return it. 10729 if (Entry.second && Generation == Entry.first) 10730 return Entry.second; 10731 10732 // We found an entry but it's stale. Rewrite the stale entry 10733 // according to the current predicate. 10734 if (Entry.second) 10735 Expr = Entry.second; 10736 10737 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10738 Entry = {Generation, NewSCEV}; 10739 10740 return NewSCEV; 10741 } 10742 10743 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10744 if (!BackedgeCount) { 10745 SCEVUnionPredicate BackedgePred; 10746 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10747 addPredicate(BackedgePred); 10748 } 10749 return BackedgeCount; 10750 } 10751 10752 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10753 if (Preds.implies(&Pred)) 10754 return; 10755 Preds.add(&Pred); 10756 updateGeneration(); 10757 } 10758 10759 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10760 return Preds; 10761 } 10762 10763 void PredicatedScalarEvolution::updateGeneration() { 10764 // If the generation number wrapped recompute everything. 10765 if (++Generation == 0) { 10766 for (auto &II : RewriteMap) { 10767 const SCEV *Rewritten = II.second.second; 10768 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10769 } 10770 } 10771 } 10772 10773 void PredicatedScalarEvolution::setNoOverflow( 10774 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10775 const SCEV *Expr = getSCEV(V); 10776 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10777 10778 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10779 10780 // Clear the statically implied flags. 10781 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10782 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10783 10784 auto II = FlagsMap.insert({V, Flags}); 10785 if (!II.second) 10786 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10787 } 10788 10789 bool PredicatedScalarEvolution::hasNoOverflow( 10790 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10791 const SCEV *Expr = getSCEV(V); 10792 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10793 10794 Flags = SCEVWrapPredicate::clearFlags( 10795 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10796 10797 auto II = FlagsMap.find(V); 10798 10799 if (II != FlagsMap.end()) 10800 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10801 10802 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10803 } 10804 10805 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10806 const SCEV *Expr = this->getSCEV(V); 10807 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10808 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10809 10810 if (!New) 10811 return nullptr; 10812 10813 for (auto *P : NewPreds) 10814 Preds.add(P); 10815 10816 updateGeneration(); 10817 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10818 return New; 10819 } 10820 10821 PredicatedScalarEvolution::PredicatedScalarEvolution( 10822 const PredicatedScalarEvolution &Init) 10823 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10824 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10825 for (const auto &I : Init.FlagsMap) 10826 FlagsMap.insert(I); 10827 } 10828 10829 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10830 // For each block. 10831 for (auto *BB : L.getBlocks()) 10832 for (auto &I : *BB) { 10833 if (!SE.isSCEVable(I.getType())) 10834 continue; 10835 10836 auto *Expr = SE.getSCEV(&I); 10837 auto II = RewriteMap.find(Expr); 10838 10839 if (II == RewriteMap.end()) 10840 continue; 10841 10842 // Don't print things that are not interesting. 10843 if (II->second.second == Expr) 10844 continue; 10845 10846 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10847 OS.indent(Depth + 2) << *Expr << "\n"; 10848 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10849 } 10850 } 10851