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/KnownBits.h" 93 #include "llvm/Support/MathExtras.h" 94 #include "llvm/Support/raw_ostream.h" 95 #include "llvm/Support/SaveAndRestore.h" 96 #include <algorithm> 97 using namespace llvm; 98 99 #define DEBUG_TYPE "scalar-evolution" 100 101 STATISTIC(NumArrayLenItCounts, 102 "Number of trip counts computed with array length"); 103 STATISTIC(NumTripCountsComputed, 104 "Number of loops with predictable loop counts"); 105 STATISTIC(NumTripCountsNotComputed, 106 "Number of loops without predictable loop counts"); 107 STATISTIC(NumBruteForceTripCountsComputed, 108 "Number of loops with trip counts computed by force"); 109 110 static cl::opt<unsigned> 111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 112 cl::desc("Maximum number of iterations SCEV will " 113 "symbolically execute a constant " 114 "derived loop"), 115 cl::init(100)); 116 117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 118 static cl::opt<bool> 119 VerifySCEV("verify-scev", 120 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 121 static cl::opt<bool> 122 VerifySCEVMap("verify-scev-maps", 123 cl::desc("Verify no dangling value in ScalarEvolution's " 124 "ExprValueMap (slow)")); 125 126 static cl::opt<unsigned> MulOpsInlineThreshold( 127 "scev-mulops-inline-threshold", cl::Hidden, 128 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 129 cl::init(1000)); 130 131 static cl::opt<unsigned> AddOpsInlineThreshold( 132 "scev-addops-inline-threshold", cl::Hidden, 133 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 134 cl::init(500)); 135 136 static cl::opt<unsigned> MaxSCEVCompareDepth( 137 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 138 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 139 cl::init(32)); 140 141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 142 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 143 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 144 cl::init(2)); 145 146 static cl::opt<unsigned> MaxValueCompareDepth( 147 "scalar-evolution-max-value-compare-depth", cl::Hidden, 148 cl::desc("Maximum depth of recursive value complexity comparisons"), 149 cl::init(2)); 150 151 static cl::opt<unsigned> 152 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden, 153 cl::desc("Maximum depth of recursive AddExpr"), 154 cl::init(32)); 155 156 static cl::opt<unsigned> MaxConstantEvolvingDepth( 157 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 158 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 159 160 //===----------------------------------------------------------------------===// 161 // SCEV class definitions 162 //===----------------------------------------------------------------------===// 163 164 //===----------------------------------------------------------------------===// 165 // Implementation of the SCEV class. 166 // 167 168 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 169 LLVM_DUMP_METHOD void SCEV::dump() const { 170 print(dbgs()); 171 dbgs() << '\n'; 172 } 173 #endif 174 175 void SCEV::print(raw_ostream &OS) const { 176 switch (static_cast<SCEVTypes>(getSCEVType())) { 177 case scConstant: 178 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 179 return; 180 case scTruncate: { 181 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 182 const SCEV *Op = Trunc->getOperand(); 183 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 184 << *Trunc->getType() << ")"; 185 return; 186 } 187 case scZeroExtend: { 188 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 189 const SCEV *Op = ZExt->getOperand(); 190 OS << "(zext " << *Op->getType() << " " << *Op << " to " 191 << *ZExt->getType() << ")"; 192 return; 193 } 194 case scSignExtend: { 195 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 196 const SCEV *Op = SExt->getOperand(); 197 OS << "(sext " << *Op->getType() << " " << *Op << " to " 198 << *SExt->getType() << ")"; 199 return; 200 } 201 case scAddRecExpr: { 202 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 203 OS << "{" << *AR->getOperand(0); 204 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 205 OS << ",+," << *AR->getOperand(i); 206 OS << "}<"; 207 if (AR->hasNoUnsignedWrap()) 208 OS << "nuw><"; 209 if (AR->hasNoSignedWrap()) 210 OS << "nsw><"; 211 if (AR->hasNoSelfWrap() && 212 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 213 OS << "nw><"; 214 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 215 OS << ">"; 216 return; 217 } 218 case scAddExpr: 219 case scMulExpr: 220 case scUMaxExpr: 221 case scSMaxExpr: { 222 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 223 const char *OpStr = nullptr; 224 switch (NAry->getSCEVType()) { 225 case scAddExpr: OpStr = " + "; break; 226 case scMulExpr: OpStr = " * "; break; 227 case scUMaxExpr: OpStr = " umax "; break; 228 case scSMaxExpr: OpStr = " smax "; break; 229 } 230 OS << "("; 231 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 232 I != E; ++I) { 233 OS << **I; 234 if (std::next(I) != E) 235 OS << OpStr; 236 } 237 OS << ")"; 238 switch (NAry->getSCEVType()) { 239 case scAddExpr: 240 case scMulExpr: 241 if (NAry->hasNoUnsignedWrap()) 242 OS << "<nuw>"; 243 if (NAry->hasNoSignedWrap()) 244 OS << "<nsw>"; 245 } 246 return; 247 } 248 case scUDivExpr: { 249 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 250 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 251 return; 252 } 253 case scUnknown: { 254 const SCEVUnknown *U = cast<SCEVUnknown>(this); 255 Type *AllocTy; 256 if (U->isSizeOf(AllocTy)) { 257 OS << "sizeof(" << *AllocTy << ")"; 258 return; 259 } 260 if (U->isAlignOf(AllocTy)) { 261 OS << "alignof(" << *AllocTy << ")"; 262 return; 263 } 264 265 Type *CTy; 266 Constant *FieldNo; 267 if (U->isOffsetOf(CTy, FieldNo)) { 268 OS << "offsetof(" << *CTy << ", "; 269 FieldNo->printAsOperand(OS, false); 270 OS << ")"; 271 return; 272 } 273 274 // Otherwise just print it normally. 275 U->getValue()->printAsOperand(OS, false); 276 return; 277 } 278 case scCouldNotCompute: 279 OS << "***COULDNOTCOMPUTE***"; 280 return; 281 } 282 llvm_unreachable("Unknown SCEV kind!"); 283 } 284 285 Type *SCEV::getType() const { 286 switch (static_cast<SCEVTypes>(getSCEVType())) { 287 case scConstant: 288 return cast<SCEVConstant>(this)->getType(); 289 case scTruncate: 290 case scZeroExtend: 291 case scSignExtend: 292 return cast<SCEVCastExpr>(this)->getType(); 293 case scAddRecExpr: 294 case scMulExpr: 295 case scUMaxExpr: 296 case scSMaxExpr: 297 return cast<SCEVNAryExpr>(this)->getType(); 298 case scAddExpr: 299 return cast<SCEVAddExpr>(this)->getType(); 300 case scUDivExpr: 301 return cast<SCEVUDivExpr>(this)->getType(); 302 case scUnknown: 303 return cast<SCEVUnknown>(this)->getType(); 304 case scCouldNotCompute: 305 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 306 } 307 llvm_unreachable("Unknown SCEV kind!"); 308 } 309 310 bool SCEV::isZero() const { 311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 312 return SC->getValue()->isZero(); 313 return false; 314 } 315 316 bool SCEV::isOne() const { 317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 318 return SC->getValue()->isOne(); 319 return false; 320 } 321 322 bool SCEV::isAllOnesValue() const { 323 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 324 return SC->getValue()->isAllOnesValue(); 325 return false; 326 } 327 328 bool SCEV::isNonConstantNegative() const { 329 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 330 if (!Mul) return false; 331 332 // If there is a constant factor, it will be first. 333 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 334 if (!SC) return false; 335 336 // Return true if the value is negative, this matches things like (-42 * V). 337 return SC->getAPInt().isNegative(); 338 } 339 340 SCEVCouldNotCompute::SCEVCouldNotCompute() : 341 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 342 343 bool SCEVCouldNotCompute::classof(const SCEV *S) { 344 return S->getSCEVType() == scCouldNotCompute; 345 } 346 347 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 348 FoldingSetNodeID ID; 349 ID.AddInteger(scConstant); 350 ID.AddPointer(V); 351 void *IP = nullptr; 352 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 353 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 354 UniqueSCEVs.InsertNode(S, IP); 355 return S; 356 } 357 358 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 359 return getConstant(ConstantInt::get(getContext(), Val)); 360 } 361 362 const SCEV * 363 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 364 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 365 return getConstant(ConstantInt::get(ITy, V, isSigned)); 366 } 367 368 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 369 unsigned SCEVTy, const SCEV *op, Type *ty) 370 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 371 372 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 373 const SCEV *op, Type *ty) 374 : SCEVCastExpr(ID, scTruncate, op, ty) { 375 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 376 (Ty->isIntegerTy() || Ty->isPointerTy()) && 377 "Cannot truncate non-integer value!"); 378 } 379 380 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 381 const SCEV *op, Type *ty) 382 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 383 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 384 (Ty->isIntegerTy() || Ty->isPointerTy()) && 385 "Cannot zero extend non-integer value!"); 386 } 387 388 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 389 const SCEV *op, Type *ty) 390 : SCEVCastExpr(ID, scSignExtend, op, ty) { 391 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 392 (Ty->isIntegerTy() || Ty->isPointerTy()) && 393 "Cannot sign extend non-integer value!"); 394 } 395 396 void SCEVUnknown::deleted() { 397 // Clear this SCEVUnknown from various maps. 398 SE->forgetMemoizedResults(this); 399 400 // Remove this SCEVUnknown from the uniquing map. 401 SE->UniqueSCEVs.RemoveNode(this); 402 403 // Release the value. 404 setValPtr(nullptr); 405 } 406 407 void SCEVUnknown::allUsesReplacedWith(Value *New) { 408 // Clear this SCEVUnknown from various maps. 409 SE->forgetMemoizedResults(this); 410 411 // Remove this SCEVUnknown from the uniquing map. 412 SE->UniqueSCEVs.RemoveNode(this); 413 414 // Update this SCEVUnknown to point to the new value. This is needed 415 // because there may still be outstanding SCEVs which still point to 416 // this SCEVUnknown. 417 setValPtr(New); 418 } 419 420 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 421 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 422 if (VCE->getOpcode() == Instruction::PtrToInt) 423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 424 if (CE->getOpcode() == Instruction::GetElementPtr && 425 CE->getOperand(0)->isNullValue() && 426 CE->getNumOperands() == 2) 427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 428 if (CI->isOne()) { 429 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 430 ->getElementType(); 431 return true; 432 } 433 434 return false; 435 } 436 437 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 438 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 439 if (VCE->getOpcode() == Instruction::PtrToInt) 440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 441 if (CE->getOpcode() == Instruction::GetElementPtr && 442 CE->getOperand(0)->isNullValue()) { 443 Type *Ty = 444 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 445 if (StructType *STy = dyn_cast<StructType>(Ty)) 446 if (!STy->isPacked() && 447 CE->getNumOperands() == 3 && 448 CE->getOperand(1)->isNullValue()) { 449 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 450 if (CI->isOne() && 451 STy->getNumElements() == 2 && 452 STy->getElementType(0)->isIntegerTy(1)) { 453 AllocTy = STy->getElementType(1); 454 return true; 455 } 456 } 457 } 458 459 return false; 460 } 461 462 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 463 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 464 if (VCE->getOpcode() == Instruction::PtrToInt) 465 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 466 if (CE->getOpcode() == Instruction::GetElementPtr && 467 CE->getNumOperands() == 3 && 468 CE->getOperand(0)->isNullValue() && 469 CE->getOperand(1)->isNullValue()) { 470 Type *Ty = 471 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 472 // Ignore vector types here so that ScalarEvolutionExpander doesn't 473 // emit getelementptrs that index into vectors. 474 if (Ty->isStructTy() || Ty->isArrayTy()) { 475 CTy = Ty; 476 FieldNo = CE->getOperand(2); 477 return true; 478 } 479 } 480 481 return false; 482 } 483 484 //===----------------------------------------------------------------------===// 485 // SCEV Utilities 486 //===----------------------------------------------------------------------===// 487 488 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 489 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 490 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 491 /// have been previously deemed to be "equally complex" by this routine. It is 492 /// intended to avoid exponential time complexity in cases like: 493 /// 494 /// %a = f(%x, %y) 495 /// %b = f(%a, %a) 496 /// %c = f(%b, %b) 497 /// 498 /// %d = f(%x, %y) 499 /// %e = f(%d, %d) 500 /// %f = f(%e, %e) 501 /// 502 /// CompareValueComplexity(%f, %c) 503 /// 504 /// Since we do not continue running this routine on expression trees once we 505 /// have seen unequal values, there is no need to track them in the cache. 506 static int 507 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 508 const LoopInfo *const LI, Value *LV, Value *RV, 509 unsigned Depth) { 510 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV})) 511 return 0; 512 513 // Order pointer values after integer values. This helps SCEVExpander form 514 // GEPs. 515 bool LIsPointer = LV->getType()->isPointerTy(), 516 RIsPointer = RV->getType()->isPointerTy(); 517 if (LIsPointer != RIsPointer) 518 return (int)LIsPointer - (int)RIsPointer; 519 520 // Compare getValueID values. 521 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 522 if (LID != RID) 523 return (int)LID - (int)RID; 524 525 // Sort arguments by their position. 526 if (const auto *LA = dyn_cast<Argument>(LV)) { 527 const auto *RA = cast<Argument>(RV); 528 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 529 return (int)LArgNo - (int)RArgNo; 530 } 531 532 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 533 const auto *RGV = cast<GlobalValue>(RV); 534 535 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 536 auto LT = GV->getLinkage(); 537 return !(GlobalValue::isPrivateLinkage(LT) || 538 GlobalValue::isInternalLinkage(LT)); 539 }; 540 541 // Use the names to distinguish the two values, but only if the 542 // names are semantically important. 543 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 544 return LGV->getName().compare(RGV->getName()); 545 } 546 547 // For instructions, compare their loop depth, and their operand count. This 548 // is pretty loose. 549 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 550 const auto *RInst = cast<Instruction>(RV); 551 552 // Compare loop depths. 553 const BasicBlock *LParent = LInst->getParent(), 554 *RParent = RInst->getParent(); 555 if (LParent != RParent) { 556 unsigned LDepth = LI->getLoopDepth(LParent), 557 RDepth = LI->getLoopDepth(RParent); 558 if (LDepth != RDepth) 559 return (int)LDepth - (int)RDepth; 560 } 561 562 // Compare the number of operands. 563 unsigned LNumOps = LInst->getNumOperands(), 564 RNumOps = RInst->getNumOperands(); 565 if (LNumOps != RNumOps) 566 return (int)LNumOps - (int)RNumOps; 567 568 for (unsigned Idx : seq(0u, LNumOps)) { 569 int Result = 570 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 571 RInst->getOperand(Idx), Depth + 1); 572 if (Result != 0) 573 return Result; 574 } 575 } 576 577 EqCache.insert({LV, RV}); 578 return 0; 579 } 580 581 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 582 // than RHS, respectively. A three-way result allows recursive comparisons to be 583 // more efficient. 584 static int CompareSCEVComplexity( 585 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 586 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 587 DominatorTree &DT, unsigned Depth = 0) { 588 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 589 if (LHS == RHS) 590 return 0; 591 592 // Primarily, sort the SCEVs by their getSCEVType(). 593 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 594 if (LType != RType) 595 return (int)LType - (int)RType; 596 597 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS})) 598 return 0; 599 // Aside from the getSCEVType() ordering, the particular ordering 600 // isn't very important except that it's beneficial to be consistent, 601 // so that (a + b) and (b + a) don't end up as different expressions. 602 switch (static_cast<SCEVTypes>(LType)) { 603 case scUnknown: { 604 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 605 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 606 607 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 608 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 609 Depth + 1); 610 if (X == 0) 611 EqCacheSCEV.insert({LHS, RHS}); 612 return X; 613 } 614 615 case scConstant: { 616 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 617 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 618 619 // Compare constant values. 620 const APInt &LA = LC->getAPInt(); 621 const APInt &RA = RC->getAPInt(); 622 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 623 if (LBitWidth != RBitWidth) 624 return (int)LBitWidth - (int)RBitWidth; 625 return LA.ult(RA) ? -1 : 1; 626 } 627 628 case scAddRecExpr: { 629 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 630 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 631 632 // There is always a dominance between two recs that are used by one SCEV, 633 // so we can safely sort recs by loop header dominance. We require such 634 // order in getAddExpr. 635 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 636 if (LLoop != RLoop) { 637 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 638 assert(LHead != RHead && "Two loops share the same header?"); 639 if (DT.dominates(LHead, RHead)) 640 return 1; 641 else 642 assert(DT.dominates(RHead, LHead) && 643 "No dominance between recurrences used by one SCEV?"); 644 return -1; 645 } 646 647 // Addrec complexity grows with operand count. 648 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 649 if (LNumOps != RNumOps) 650 return (int)LNumOps - (int)RNumOps; 651 652 // Lexicographically compare. 653 for (unsigned i = 0; i != LNumOps; ++i) { 654 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 655 RA->getOperand(i), DT, Depth + 1); 656 if (X != 0) 657 return X; 658 } 659 EqCacheSCEV.insert({LHS, RHS}); 660 return 0; 661 } 662 663 case scAddExpr: 664 case scMulExpr: 665 case scSMaxExpr: 666 case scUMaxExpr: { 667 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 668 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 669 670 // Lexicographically compare n-ary expressions. 671 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 672 if (LNumOps != RNumOps) 673 return (int)LNumOps - (int)RNumOps; 674 675 for (unsigned i = 0; i != LNumOps; ++i) { 676 if (i >= RNumOps) 677 return 1; 678 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 679 RC->getOperand(i), DT, Depth + 1); 680 if (X != 0) 681 return X; 682 } 683 EqCacheSCEV.insert({LHS, RHS}); 684 return 0; 685 } 686 687 case scUDivExpr: { 688 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 689 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 690 691 // Lexicographically compare udiv expressions. 692 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 693 DT, Depth + 1); 694 if (X != 0) 695 return X; 696 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT, 697 Depth + 1); 698 if (X == 0) 699 EqCacheSCEV.insert({LHS, RHS}); 700 return X; 701 } 702 703 case scTruncate: 704 case scZeroExtend: 705 case scSignExtend: { 706 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 707 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 708 709 // Compare cast expressions by operand. 710 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 711 RC->getOperand(), DT, Depth + 1); 712 if (X == 0) 713 EqCacheSCEV.insert({LHS, RHS}); 714 return X; 715 } 716 717 case scCouldNotCompute: 718 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 719 } 720 llvm_unreachable("Unknown SCEV kind!"); 721 } 722 723 /// Given a list of SCEV objects, order them by their complexity, and group 724 /// objects of the same complexity together by value. When this routine is 725 /// finished, we know that any duplicates in the vector are consecutive and that 726 /// complexity is monotonically increasing. 727 /// 728 /// Note that we go take special precautions to ensure that we get deterministic 729 /// results from this routine. In other words, we don't want the results of 730 /// this to depend on where the addresses of various SCEV objects happened to 731 /// land in memory. 732 /// 733 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 734 LoopInfo *LI, DominatorTree &DT) { 735 if (Ops.size() < 2) return; // Noop 736 737 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 738 if (Ops.size() == 2) { 739 // This is the common case, which also happens to be trivially simple. 740 // Special case it. 741 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 742 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0) 743 std::swap(LHS, RHS); 744 return; 745 } 746 747 // Do the rough sort by complexity. 748 std::stable_sort(Ops.begin(), Ops.end(), 749 [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) { 750 return 751 CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0; 752 }); 753 754 // Now that we are sorted by complexity, group elements of the same 755 // complexity. Note that this is, at worst, N^2, but the vector is likely to 756 // be extremely short in practice. Note that we take this approach because we 757 // do not want to depend on the addresses of the objects we are grouping. 758 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 759 const SCEV *S = Ops[i]; 760 unsigned Complexity = S->getSCEVType(); 761 762 // If there are any objects of the same complexity and same value as this 763 // one, group them. 764 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 765 if (Ops[j] == S) { // Found a duplicate. 766 // Move it to immediately after i'th element. 767 std::swap(Ops[i+1], Ops[j]); 768 ++i; // no need to rescan it. 769 if (i == e-2) return; // Done! 770 } 771 } 772 } 773 } 774 775 // Returns the size of the SCEV S. 776 static inline int sizeOfSCEV(const SCEV *S) { 777 struct FindSCEVSize { 778 int Size; 779 FindSCEVSize() : Size(0) {} 780 781 bool follow(const SCEV *S) { 782 ++Size; 783 // Keep looking at all operands of S. 784 return true; 785 } 786 bool isDone() const { 787 return false; 788 } 789 }; 790 791 FindSCEVSize F; 792 SCEVTraversal<FindSCEVSize> ST(F); 793 ST.visitAll(S); 794 return F.Size; 795 } 796 797 namespace { 798 799 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 800 public: 801 // Computes the Quotient and Remainder of the division of Numerator by 802 // Denominator. 803 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 804 const SCEV *Denominator, const SCEV **Quotient, 805 const SCEV **Remainder) { 806 assert(Numerator && Denominator && "Uninitialized SCEV"); 807 808 SCEVDivision D(SE, Numerator, Denominator); 809 810 // Check for the trivial case here to avoid having to check for it in the 811 // rest of the code. 812 if (Numerator == Denominator) { 813 *Quotient = D.One; 814 *Remainder = D.Zero; 815 return; 816 } 817 818 if (Numerator->isZero()) { 819 *Quotient = D.Zero; 820 *Remainder = D.Zero; 821 return; 822 } 823 824 // A simple case when N/1. The quotient is N. 825 if (Denominator->isOne()) { 826 *Quotient = Numerator; 827 *Remainder = D.Zero; 828 return; 829 } 830 831 // Split the Denominator when it is a product. 832 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 833 const SCEV *Q, *R; 834 *Quotient = Numerator; 835 for (const SCEV *Op : T->operands()) { 836 divide(SE, *Quotient, Op, &Q, &R); 837 *Quotient = Q; 838 839 // Bail out when the Numerator is not divisible by one of the terms of 840 // the Denominator. 841 if (!R->isZero()) { 842 *Quotient = D.Zero; 843 *Remainder = Numerator; 844 return; 845 } 846 } 847 *Remainder = D.Zero; 848 return; 849 } 850 851 D.visit(Numerator); 852 *Quotient = D.Quotient; 853 *Remainder = D.Remainder; 854 } 855 856 // Except in the trivial case described above, we do not know how to divide 857 // Expr by Denominator for the following functions with empty implementation. 858 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 859 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 860 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 861 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 862 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 863 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 864 void visitUnknown(const SCEVUnknown *Numerator) {} 865 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 866 867 void visitConstant(const SCEVConstant *Numerator) { 868 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 869 APInt NumeratorVal = Numerator->getAPInt(); 870 APInt DenominatorVal = D->getAPInt(); 871 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 872 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 873 874 if (NumeratorBW > DenominatorBW) 875 DenominatorVal = DenominatorVal.sext(NumeratorBW); 876 else if (NumeratorBW < DenominatorBW) 877 NumeratorVal = NumeratorVal.sext(DenominatorBW); 878 879 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 880 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 881 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 882 Quotient = SE.getConstant(QuotientVal); 883 Remainder = SE.getConstant(RemainderVal); 884 return; 885 } 886 } 887 888 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 889 const SCEV *StartQ, *StartR, *StepQ, *StepR; 890 if (!Numerator->isAffine()) 891 return cannotDivide(Numerator); 892 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 893 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 894 // Bail out if the types do not match. 895 Type *Ty = Denominator->getType(); 896 if (Ty != StartQ->getType() || Ty != StartR->getType() || 897 Ty != StepQ->getType() || Ty != StepR->getType()) 898 return cannotDivide(Numerator); 899 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 900 Numerator->getNoWrapFlags()); 901 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 902 Numerator->getNoWrapFlags()); 903 } 904 905 void visitAddExpr(const SCEVAddExpr *Numerator) { 906 SmallVector<const SCEV *, 2> Qs, Rs; 907 Type *Ty = Denominator->getType(); 908 909 for (const SCEV *Op : Numerator->operands()) { 910 const SCEV *Q, *R; 911 divide(SE, Op, Denominator, &Q, &R); 912 913 // Bail out if types do not match. 914 if (Ty != Q->getType() || Ty != R->getType()) 915 return cannotDivide(Numerator); 916 917 Qs.push_back(Q); 918 Rs.push_back(R); 919 } 920 921 if (Qs.size() == 1) { 922 Quotient = Qs[0]; 923 Remainder = Rs[0]; 924 return; 925 } 926 927 Quotient = SE.getAddExpr(Qs); 928 Remainder = SE.getAddExpr(Rs); 929 } 930 931 void visitMulExpr(const SCEVMulExpr *Numerator) { 932 SmallVector<const SCEV *, 2> Qs; 933 Type *Ty = Denominator->getType(); 934 935 bool FoundDenominatorTerm = false; 936 for (const SCEV *Op : Numerator->operands()) { 937 // Bail out if types do not match. 938 if (Ty != Op->getType()) 939 return cannotDivide(Numerator); 940 941 if (FoundDenominatorTerm) { 942 Qs.push_back(Op); 943 continue; 944 } 945 946 // Check whether Denominator divides one of the product operands. 947 const SCEV *Q, *R; 948 divide(SE, Op, Denominator, &Q, &R); 949 if (!R->isZero()) { 950 Qs.push_back(Op); 951 continue; 952 } 953 954 // Bail out if types do not match. 955 if (Ty != Q->getType()) 956 return cannotDivide(Numerator); 957 958 FoundDenominatorTerm = true; 959 Qs.push_back(Q); 960 } 961 962 if (FoundDenominatorTerm) { 963 Remainder = Zero; 964 if (Qs.size() == 1) 965 Quotient = Qs[0]; 966 else 967 Quotient = SE.getMulExpr(Qs); 968 return; 969 } 970 971 if (!isa<SCEVUnknown>(Denominator)) 972 return cannotDivide(Numerator); 973 974 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 975 ValueToValueMap RewriteMap; 976 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 977 cast<SCEVConstant>(Zero)->getValue(); 978 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 979 980 if (Remainder->isZero()) { 981 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 982 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 983 cast<SCEVConstant>(One)->getValue(); 984 Quotient = 985 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 986 return; 987 } 988 989 // Quotient is (Numerator - Remainder) divided by Denominator. 990 const SCEV *Q, *R; 991 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 992 // This SCEV does not seem to simplify: fail the division here. 993 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 994 return cannotDivide(Numerator); 995 divide(SE, Diff, Denominator, &Q, &R); 996 if (R != Zero) 997 return cannotDivide(Numerator); 998 Quotient = Q; 999 } 1000 1001 private: 1002 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1003 const SCEV *Denominator) 1004 : SE(S), Denominator(Denominator) { 1005 Zero = SE.getZero(Denominator->getType()); 1006 One = SE.getOne(Denominator->getType()); 1007 1008 // We generally do not know how to divide Expr by Denominator. We 1009 // initialize the division to a "cannot divide" state to simplify the rest 1010 // of the code. 1011 cannotDivide(Numerator); 1012 } 1013 1014 // Convenience function for giving up on the division. We set the quotient to 1015 // be equal to zero and the remainder to be equal to the numerator. 1016 void cannotDivide(const SCEV *Numerator) { 1017 Quotient = Zero; 1018 Remainder = Numerator; 1019 } 1020 1021 ScalarEvolution &SE; 1022 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1023 }; 1024 1025 } 1026 1027 //===----------------------------------------------------------------------===// 1028 // Simple SCEV method implementations 1029 //===----------------------------------------------------------------------===// 1030 1031 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1032 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1033 ScalarEvolution &SE, 1034 Type *ResultTy) { 1035 // Handle the simplest case efficiently. 1036 if (K == 1) 1037 return SE.getTruncateOrZeroExtend(It, ResultTy); 1038 1039 // We are using the following formula for BC(It, K): 1040 // 1041 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1042 // 1043 // Suppose, W is the bitwidth of the return value. We must be prepared for 1044 // overflow. Hence, we must assure that the result of our computation is 1045 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1046 // safe in modular arithmetic. 1047 // 1048 // However, this code doesn't use exactly that formula; the formula it uses 1049 // is something like the following, where T is the number of factors of 2 in 1050 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1051 // exponentiation: 1052 // 1053 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1054 // 1055 // This formula is trivially equivalent to the previous formula. However, 1056 // this formula can be implemented much more efficiently. The trick is that 1057 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1058 // arithmetic. To do exact division in modular arithmetic, all we have 1059 // to do is multiply by the inverse. Therefore, this step can be done at 1060 // width W. 1061 // 1062 // The next issue is how to safely do the division by 2^T. The way this 1063 // is done is by doing the multiplication step at a width of at least W + T 1064 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1065 // when we perform the division by 2^T (which is equivalent to a right shift 1066 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1067 // truncated out after the division by 2^T. 1068 // 1069 // In comparison to just directly using the first formula, this technique 1070 // is much more efficient; using the first formula requires W * K bits, 1071 // but this formula less than W + K bits. Also, the first formula requires 1072 // a division step, whereas this formula only requires multiplies and shifts. 1073 // 1074 // It doesn't matter whether the subtraction step is done in the calculation 1075 // width or the input iteration count's width; if the subtraction overflows, 1076 // the result must be zero anyway. We prefer here to do it in the width of 1077 // the induction variable because it helps a lot for certain cases; CodeGen 1078 // isn't smart enough to ignore the overflow, which leads to much less 1079 // efficient code if the width of the subtraction is wider than the native 1080 // register width. 1081 // 1082 // (It's possible to not widen at all by pulling out factors of 2 before 1083 // the multiplication; for example, K=2 can be calculated as 1084 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1085 // extra arithmetic, so it's not an obvious win, and it gets 1086 // much more complicated for K > 3.) 1087 1088 // Protection from insane SCEVs; this bound is conservative, 1089 // but it probably doesn't matter. 1090 if (K > 1000) 1091 return SE.getCouldNotCompute(); 1092 1093 unsigned W = SE.getTypeSizeInBits(ResultTy); 1094 1095 // Calculate K! / 2^T and T; we divide out the factors of two before 1096 // multiplying for calculating K! / 2^T to avoid overflow. 1097 // Other overflow doesn't matter because we only care about the bottom 1098 // W bits of the result. 1099 APInt OddFactorial(W, 1); 1100 unsigned T = 1; 1101 for (unsigned i = 3; i <= K; ++i) { 1102 APInt Mult(W, i); 1103 unsigned TwoFactors = Mult.countTrailingZeros(); 1104 T += TwoFactors; 1105 Mult.lshrInPlace(TwoFactors); 1106 OddFactorial *= Mult; 1107 } 1108 1109 // We need at least W + T bits for the multiplication step 1110 unsigned CalculationBits = W + T; 1111 1112 // Calculate 2^T, at width T+W. 1113 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1114 1115 // Calculate the multiplicative inverse of K! / 2^T; 1116 // this multiplication factor will perform the exact division by 1117 // K! / 2^T. 1118 APInt Mod = APInt::getSignedMinValue(W+1); 1119 APInt MultiplyFactor = OddFactorial.zext(W+1); 1120 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1121 MultiplyFactor = MultiplyFactor.trunc(W); 1122 1123 // Calculate the product, at width T+W 1124 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1125 CalculationBits); 1126 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1127 for (unsigned i = 1; i != K; ++i) { 1128 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1129 Dividend = SE.getMulExpr(Dividend, 1130 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1131 } 1132 1133 // Divide by 2^T 1134 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1135 1136 // Truncate the result, and divide by K! / 2^T. 1137 1138 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1139 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1140 } 1141 1142 /// Return the value of this chain of recurrences at the specified iteration 1143 /// number. We can evaluate this recurrence by multiplying each element in the 1144 /// chain by the binomial coefficient corresponding to it. In other words, we 1145 /// can evaluate {A,+,B,+,C,+,D} as: 1146 /// 1147 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1148 /// 1149 /// where BC(It, k) stands for binomial coefficient. 1150 /// 1151 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1152 ScalarEvolution &SE) const { 1153 const SCEV *Result = getStart(); 1154 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1155 // The computation is correct in the face of overflow provided that the 1156 // multiplication is performed _after_ the evaluation of the binomial 1157 // coefficient. 1158 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1159 if (isa<SCEVCouldNotCompute>(Coeff)) 1160 return Coeff; 1161 1162 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1163 } 1164 return Result; 1165 } 1166 1167 //===----------------------------------------------------------------------===// 1168 // SCEV Expression folder implementations 1169 //===----------------------------------------------------------------------===// 1170 1171 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1172 Type *Ty) { 1173 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1174 "This is not a truncating conversion!"); 1175 assert(isSCEVable(Ty) && 1176 "This is not a conversion to a SCEVable type!"); 1177 Ty = getEffectiveSCEVType(Ty); 1178 1179 FoldingSetNodeID ID; 1180 ID.AddInteger(scTruncate); 1181 ID.AddPointer(Op); 1182 ID.AddPointer(Ty); 1183 void *IP = nullptr; 1184 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1185 1186 // Fold if the operand is constant. 1187 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1188 return getConstant( 1189 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1190 1191 // trunc(trunc(x)) --> trunc(x) 1192 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1193 return getTruncateExpr(ST->getOperand(), Ty); 1194 1195 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1196 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1197 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1198 1199 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1200 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1201 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1202 1203 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1204 // eliminate all the truncates, or we replace other casts with truncates. 1205 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1206 SmallVector<const SCEV *, 4> Operands; 1207 bool hasTrunc = false; 1208 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1209 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1210 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1211 hasTrunc = isa<SCEVTruncateExpr>(S); 1212 Operands.push_back(S); 1213 } 1214 if (!hasTrunc) 1215 return getAddExpr(Operands); 1216 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1217 } 1218 1219 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1220 // eliminate all the truncates, or we replace other casts with truncates. 1221 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1222 SmallVector<const SCEV *, 4> Operands; 1223 bool hasTrunc = false; 1224 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1225 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1226 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1227 hasTrunc = isa<SCEVTruncateExpr>(S); 1228 Operands.push_back(S); 1229 } 1230 if (!hasTrunc) 1231 return getMulExpr(Operands); 1232 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1233 } 1234 1235 // If the input value is a chrec scev, truncate the chrec's operands. 1236 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1237 SmallVector<const SCEV *, 4> Operands; 1238 for (const SCEV *Op : AddRec->operands()) 1239 Operands.push_back(getTruncateExpr(Op, Ty)); 1240 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1241 } 1242 1243 // The cast wasn't folded; create an explicit cast node. We can reuse 1244 // the existing insert position since if we get here, we won't have 1245 // made any changes which would invalidate it. 1246 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1247 Op, Ty); 1248 UniqueSCEVs.InsertNode(S, IP); 1249 return S; 1250 } 1251 1252 // Get the limit of a recurrence such that incrementing by Step cannot cause 1253 // signed overflow as long as the value of the recurrence within the 1254 // loop does not exceed this limit before incrementing. 1255 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1256 ICmpInst::Predicate *Pred, 1257 ScalarEvolution *SE) { 1258 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1259 if (SE->isKnownPositive(Step)) { 1260 *Pred = ICmpInst::ICMP_SLT; 1261 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1262 SE->getSignedRange(Step).getSignedMax()); 1263 } 1264 if (SE->isKnownNegative(Step)) { 1265 *Pred = ICmpInst::ICMP_SGT; 1266 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1267 SE->getSignedRange(Step).getSignedMin()); 1268 } 1269 return nullptr; 1270 } 1271 1272 // Get the limit of a recurrence such that incrementing by Step cannot cause 1273 // unsigned overflow as long as the value of the recurrence within the loop does 1274 // not exceed this limit before incrementing. 1275 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1276 ICmpInst::Predicate *Pred, 1277 ScalarEvolution *SE) { 1278 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1279 *Pred = ICmpInst::ICMP_ULT; 1280 1281 return SE->getConstant(APInt::getMinValue(BitWidth) - 1282 SE->getUnsignedRange(Step).getUnsignedMax()); 1283 } 1284 1285 namespace { 1286 1287 struct ExtendOpTraitsBase { 1288 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)( 1289 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache); 1290 }; 1291 1292 // Used to make code generic over signed and unsigned overflow. 1293 template <typename ExtendOp> struct ExtendOpTraits { 1294 // Members present: 1295 // 1296 // static const SCEV::NoWrapFlags WrapType; 1297 // 1298 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1299 // 1300 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1301 // ICmpInst::Predicate *Pred, 1302 // ScalarEvolution *SE); 1303 }; 1304 1305 template <> 1306 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1307 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1308 1309 static const GetExtendExprTy GetExtendExpr; 1310 1311 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1312 ICmpInst::Predicate *Pred, 1313 ScalarEvolution *SE) { 1314 return getSignedOverflowLimitForStep(Step, Pred, SE); 1315 } 1316 }; 1317 1318 const ExtendOpTraitsBase::GetExtendExprTy 1319 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr = 1320 &ScalarEvolution::getSignExtendExprCached; 1321 1322 template <> 1323 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1324 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1325 1326 static const GetExtendExprTy GetExtendExpr; 1327 1328 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1329 ICmpInst::Predicate *Pred, 1330 ScalarEvolution *SE) { 1331 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1332 } 1333 }; 1334 1335 const ExtendOpTraitsBase::GetExtendExprTy 1336 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr = 1337 &ScalarEvolution::getZeroExtendExprCached; 1338 } 1339 1340 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1341 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1342 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1343 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1344 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1345 // expression "Step + sext/zext(PreIncAR)" is congruent with 1346 // "sext/zext(PostIncAR)" 1347 template <typename ExtendOpTy> 1348 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1349 ScalarEvolution *SE, 1350 ScalarEvolution::ExtendCacheTy &Cache) { 1351 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1352 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1353 1354 const Loop *L = AR->getLoop(); 1355 const SCEV *Start = AR->getStart(); 1356 const SCEV *Step = AR->getStepRecurrence(*SE); 1357 1358 // Check for a simple looking step prior to loop entry. 1359 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1360 if (!SA) 1361 return nullptr; 1362 1363 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1364 // subtraction is expensive. For this purpose, perform a quick and dirty 1365 // difference, by checking for Step in the operand list. 1366 SmallVector<const SCEV *, 4> DiffOps; 1367 for (const SCEV *Op : SA->operands()) 1368 if (Op != Step) 1369 DiffOps.push_back(Op); 1370 1371 if (DiffOps.size() == SA->getNumOperands()) 1372 return nullptr; 1373 1374 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1375 // `Step`: 1376 1377 // 1. NSW/NUW flags on the step increment. 1378 auto PreStartFlags = 1379 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1380 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1381 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1382 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1383 1384 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1385 // "S+X does not sign/unsign-overflow". 1386 // 1387 1388 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1389 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1390 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1391 return PreStart; 1392 1393 // 2. Direct overflow check on the step operation's expression. 1394 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1395 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1396 const SCEV *OperandExtendedStart = 1397 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache), 1398 (SE->*GetExtendExpr)(Step, WideTy, Cache)); 1399 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) { 1400 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1401 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1402 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1403 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1404 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1405 } 1406 return PreStart; 1407 } 1408 1409 // 3. Loop precondition. 1410 ICmpInst::Predicate Pred; 1411 const SCEV *OverflowLimit = 1412 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1413 1414 if (OverflowLimit && 1415 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1416 return PreStart; 1417 1418 return nullptr; 1419 } 1420 1421 // Get the normalized zero or sign extended expression for this AddRec's Start. 1422 template <typename ExtendOpTy> 1423 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1424 ScalarEvolution *SE, 1425 ScalarEvolution::ExtendCacheTy &Cache) { 1426 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1427 1428 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache); 1429 if (!PreStart) 1430 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache); 1431 1432 return SE->getAddExpr( 1433 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache), 1434 (SE->*GetExtendExpr)(PreStart, Ty, Cache)); 1435 } 1436 1437 // Try to prove away overflow by looking at "nearby" add recurrences. A 1438 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1439 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1440 // 1441 // Formally: 1442 // 1443 // {S,+,X} == {S-T,+,X} + T 1444 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1445 // 1446 // If ({S-T,+,X} + T) does not overflow ... (1) 1447 // 1448 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1449 // 1450 // If {S-T,+,X} does not overflow ... (2) 1451 // 1452 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1453 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1454 // 1455 // If (S-T)+T does not overflow ... (3) 1456 // 1457 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1458 // == {Ext(S),+,Ext(X)} == LHS 1459 // 1460 // Thus, if (1), (2) and (3) are true for some T, then 1461 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1462 // 1463 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1464 // does not overflow" restricted to the 0th iteration. Therefore we only need 1465 // to check for (1) and (2). 1466 // 1467 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1468 // is `Delta` (defined below). 1469 // 1470 template <typename ExtendOpTy> 1471 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1472 const SCEV *Step, 1473 const Loop *L) { 1474 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1475 1476 // We restrict `Start` to a constant to prevent SCEV from spending too much 1477 // time here. It is correct (but more expensive) to continue with a 1478 // non-constant `Start` and do a general SCEV subtraction to compute 1479 // `PreStart` below. 1480 // 1481 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1482 if (!StartC) 1483 return false; 1484 1485 APInt StartAI = StartC->getAPInt(); 1486 1487 for (unsigned Delta : {-2, -1, 1, 2}) { 1488 const SCEV *PreStart = getConstant(StartAI - Delta); 1489 1490 FoldingSetNodeID ID; 1491 ID.AddInteger(scAddRecExpr); 1492 ID.AddPointer(PreStart); 1493 ID.AddPointer(Step); 1494 ID.AddPointer(L); 1495 void *IP = nullptr; 1496 const auto *PreAR = 1497 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1498 1499 // Give up if we don't already have the add recurrence we need because 1500 // actually constructing an add recurrence is relatively expensive. 1501 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1502 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1503 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1504 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1505 DeltaS, &Pred, this); 1506 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1507 return true; 1508 } 1509 } 1510 1511 return false; 1512 } 1513 1514 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) { 1515 // Use the local cache to prevent exponential behavior of 1516 // getZeroExtendExprImpl. 1517 ExtendCacheTy Cache; 1518 return getZeroExtendExprCached(Op, Ty, Cache); 1519 } 1520 1521 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no 1522 /// related entry in the \p Cache, call getZeroExtendExprImpl and save 1523 /// the result in the \p Cache. 1524 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty, 1525 ExtendCacheTy &Cache) { 1526 auto It = Cache.find({Op, Ty}); 1527 if (It != Cache.end()) 1528 return It->second; 1529 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache); 1530 auto InsertResult = Cache.insert({{Op, Ty}, ZExt}); 1531 assert(InsertResult.second && "Expect the key was not in the cache"); 1532 (void)InsertResult; 1533 return ZExt; 1534 } 1535 1536 /// The real implementation of getZeroExtendExpr. 1537 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty, 1538 ExtendCacheTy &Cache) { 1539 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1540 "This is not an extending conversion!"); 1541 assert(isSCEVable(Ty) && 1542 "This is not a conversion to a SCEVable type!"); 1543 Ty = getEffectiveSCEVType(Ty); 1544 1545 // Fold if the operand is constant. 1546 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1547 return getConstant( 1548 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1549 1550 // zext(zext(x)) --> zext(x) 1551 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1552 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache); 1553 1554 // Before doing any expensive analysis, check to see if we've already 1555 // computed a SCEV for this Op and Ty. 1556 FoldingSetNodeID ID; 1557 ID.AddInteger(scZeroExtend); 1558 ID.AddPointer(Op); 1559 ID.AddPointer(Ty); 1560 void *IP = nullptr; 1561 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1562 1563 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1564 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1565 // It's possible the bits taken off by the truncate were all zero bits. If 1566 // so, we should be able to simplify this further. 1567 const SCEV *X = ST->getOperand(); 1568 ConstantRange CR = getUnsignedRange(X); 1569 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1570 unsigned NewBits = getTypeSizeInBits(Ty); 1571 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1572 CR.zextOrTrunc(NewBits))) 1573 return getTruncateOrZeroExtend(X, Ty); 1574 } 1575 1576 // If the input value is a chrec scev, and we can prove that the value 1577 // did not overflow the old, smaller, value, we can zero extend all of the 1578 // operands (often constants). This allows analysis of something like 1579 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1580 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1581 if (AR->isAffine()) { 1582 const SCEV *Start = AR->getStart(); 1583 const SCEV *Step = AR->getStepRecurrence(*this); 1584 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1585 const Loop *L = AR->getLoop(); 1586 1587 if (!AR->hasNoUnsignedWrap()) { 1588 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1590 } 1591 1592 // If we have special knowledge that this addrec won't overflow, 1593 // we don't need to do any further analysis. 1594 if (AR->hasNoUnsignedWrap()) 1595 return getAddRecExpr( 1596 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1597 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1598 1599 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1600 // Note that this serves two purposes: It filters out loops that are 1601 // simply not analyzable, and it covers the case where this code is 1602 // being called from within backedge-taken count analysis, such that 1603 // attempting to ask for the backedge-taken count would likely result 1604 // in infinite recursion. In the later case, the analysis code will 1605 // cope with a conservative value, and it will take care to purge 1606 // that value once it has finished. 1607 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1608 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1609 // Manually compute the final value for AR, checking for 1610 // overflow. 1611 1612 // Check whether the backedge-taken count can be losslessly casted to 1613 // the addrec's type. The count is always unsigned. 1614 const SCEV *CastedMaxBECount = 1615 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1616 const SCEV *RecastedMaxBECount = 1617 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1618 if (MaxBECount == RecastedMaxBECount) { 1619 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1620 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1621 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1622 const SCEV *ZAdd = 1623 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache); 1624 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache); 1625 const SCEV *WideMaxBECount = 1626 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache); 1627 const SCEV *OperandExtendedAdd = getAddExpr( 1628 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached( 1629 Step, WideTy, Cache))); 1630 if (ZAdd == OperandExtendedAdd) { 1631 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1632 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1633 // Return the expression with the addrec on the outside. 1634 return getAddRecExpr( 1635 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1636 getZeroExtendExprCached(Step, Ty, Cache), L, 1637 AR->getNoWrapFlags()); 1638 } 1639 // Similar to above, only this time treat the step value as signed. 1640 // This covers loops that count down. 1641 OperandExtendedAdd = 1642 getAddExpr(WideStart, 1643 getMulExpr(WideMaxBECount, 1644 getSignExtendExpr(Step, WideTy))); 1645 if (ZAdd == OperandExtendedAdd) { 1646 // Cache knowledge of AR NW, which is propagated to this AddRec. 1647 // Negative step causes unsigned wrap, but it still can't self-wrap. 1648 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1649 // Return the expression with the addrec on the outside. 1650 return getAddRecExpr( 1651 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1652 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1653 } 1654 } 1655 } 1656 1657 // Normally, in the cases we can prove no-overflow via a 1658 // backedge guarding condition, we can also compute a backedge 1659 // taken count for the loop. The exceptions are assumptions and 1660 // guards present in the loop -- SCEV is not great at exploiting 1661 // these to compute max backedge taken counts, but can still use 1662 // these to prove lack of overflow. Use this fact to avoid 1663 // doing extra work that may not pay off. 1664 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1665 !AC.assumptions().empty()) { 1666 // If the backedge is guarded by a comparison with the pre-inc 1667 // value the addrec is safe. Also, if the entry is guarded by 1668 // a comparison with the start value and the backedge is 1669 // guarded by a comparison with the post-inc value, the addrec 1670 // is safe. 1671 if (isKnownPositive(Step)) { 1672 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1673 getUnsignedRange(Step).getUnsignedMax()); 1674 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1675 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1676 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1677 AR->getPostIncExpr(*this), N))) { 1678 // Cache knowledge of AR NUW, which is propagated to this 1679 // AddRec. 1680 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1681 // Return the expression with the addrec on the outside. 1682 return getAddRecExpr( 1683 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1684 getZeroExtendExprCached(Step, Ty, Cache), L, 1685 AR->getNoWrapFlags()); 1686 } 1687 } else if (isKnownNegative(Step)) { 1688 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1689 getSignedRange(Step).getSignedMin()); 1690 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1691 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1692 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1693 AR->getPostIncExpr(*this), N))) { 1694 // Cache knowledge of AR NW, which is propagated to this 1695 // AddRec. Negative step causes unsigned wrap, but it 1696 // still can't self-wrap. 1697 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1698 // Return the expression with the addrec on the outside. 1699 return getAddRecExpr( 1700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1701 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1702 } 1703 } 1704 } 1705 1706 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1707 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1708 return getAddRecExpr( 1709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1710 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1711 } 1712 } 1713 1714 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1715 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1716 if (SA->hasNoUnsignedWrap()) { 1717 // If the addition does not unsign overflow then we can, by definition, 1718 // commute the zero extension with the addition operation. 1719 SmallVector<const SCEV *, 4> Ops; 1720 for (const auto *Op : SA->operands()) 1721 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache)); 1722 return getAddExpr(Ops, SCEV::FlagNUW); 1723 } 1724 } 1725 1726 // The cast wasn't folded; create an explicit cast node. 1727 // Recompute the insert position, as it may have been invalidated. 1728 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1729 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1730 Op, Ty); 1731 UniqueSCEVs.InsertNode(S, IP); 1732 return S; 1733 } 1734 1735 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) { 1736 // Use the local cache to prevent exponential behavior of 1737 // getSignExtendExprImpl. 1738 ExtendCacheTy Cache; 1739 return getSignExtendExprCached(Op, Ty, Cache); 1740 } 1741 1742 /// Query \p Cache before calling getSignExtendExprImpl. If there is no 1743 /// related entry in the \p Cache, call getSignExtendExprImpl and save 1744 /// the result in the \p Cache. 1745 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty, 1746 ExtendCacheTy &Cache) { 1747 auto It = Cache.find({Op, Ty}); 1748 if (It != Cache.end()) 1749 return It->second; 1750 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache); 1751 auto InsertResult = Cache.insert({{Op, Ty}, SExt}); 1752 assert(InsertResult.second && "Expect the key was not in the cache"); 1753 (void)InsertResult; 1754 return SExt; 1755 } 1756 1757 /// The real implementation of getSignExtendExpr. 1758 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty, 1759 ExtendCacheTy &Cache) { 1760 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1761 "This is not an extending conversion!"); 1762 assert(isSCEVable(Ty) && 1763 "This is not a conversion to a SCEVable type!"); 1764 Ty = getEffectiveSCEVType(Ty); 1765 1766 // Fold if the operand is constant. 1767 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1768 return getConstant( 1769 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1770 1771 // sext(sext(x)) --> sext(x) 1772 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1773 return getSignExtendExprCached(SS->getOperand(), Ty, Cache); 1774 1775 // sext(zext(x)) --> zext(x) 1776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1777 return getZeroExtendExpr(SZ->getOperand(), Ty); 1778 1779 // Before doing any expensive analysis, check to see if we've already 1780 // computed a SCEV for this Op and Ty. 1781 FoldingSetNodeID ID; 1782 ID.AddInteger(scSignExtend); 1783 ID.AddPointer(Op); 1784 ID.AddPointer(Ty); 1785 void *IP = nullptr; 1786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1787 1788 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1789 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1790 // It's possible the bits taken off by the truncate were all sign bits. If 1791 // so, we should be able to simplify this further. 1792 const SCEV *X = ST->getOperand(); 1793 ConstantRange CR = getSignedRange(X); 1794 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1795 unsigned NewBits = getTypeSizeInBits(Ty); 1796 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1797 CR.sextOrTrunc(NewBits))) 1798 return getTruncateOrSignExtend(X, Ty); 1799 } 1800 1801 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1802 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1803 if (SA->getNumOperands() == 2) { 1804 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1805 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1806 if (SMul && SC1) { 1807 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1808 const APInt &C1 = SC1->getAPInt(); 1809 const APInt &C2 = SC2->getAPInt(); 1810 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1811 C2.ugt(C1) && C2.isPowerOf2()) 1812 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache), 1813 getSignExtendExprCached(SMul, Ty, Cache)); 1814 } 1815 } 1816 } 1817 1818 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1819 if (SA->hasNoSignedWrap()) { 1820 // If the addition does not sign overflow then we can, by definition, 1821 // commute the sign extension with the addition operation. 1822 SmallVector<const SCEV *, 4> Ops; 1823 for (const auto *Op : SA->operands()) 1824 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache)); 1825 return getAddExpr(Ops, SCEV::FlagNSW); 1826 } 1827 } 1828 // If the input value is a chrec scev, and we can prove that the value 1829 // did not overflow the old, smaller, value, we can sign extend all of the 1830 // operands (often constants). This allows analysis of something like 1831 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1832 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1833 if (AR->isAffine()) { 1834 const SCEV *Start = AR->getStart(); 1835 const SCEV *Step = AR->getStepRecurrence(*this); 1836 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1837 const Loop *L = AR->getLoop(); 1838 1839 if (!AR->hasNoSignedWrap()) { 1840 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1842 } 1843 1844 // If we have special knowledge that this addrec won't overflow, 1845 // we don't need to do any further analysis. 1846 if (AR->hasNoSignedWrap()) 1847 return getAddRecExpr( 1848 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1849 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW); 1850 1851 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1852 // Note that this serves two purposes: It filters out loops that are 1853 // simply not analyzable, and it covers the case where this code is 1854 // being called from within backedge-taken count analysis, such that 1855 // attempting to ask for the backedge-taken count would likely result 1856 // in infinite recursion. In the later case, the analysis code will 1857 // cope with a conservative value, and it will take care to purge 1858 // that value once it has finished. 1859 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1860 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1861 // Manually compute the final value for AR, checking for 1862 // overflow. 1863 1864 // Check whether the backedge-taken count can be losslessly casted to 1865 // the addrec's type. The count is always unsigned. 1866 const SCEV *CastedMaxBECount = 1867 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1868 const SCEV *RecastedMaxBECount = 1869 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1870 if (MaxBECount == RecastedMaxBECount) { 1871 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1872 // Check whether Start+Step*MaxBECount has no signed overflow. 1873 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1874 const SCEV *SAdd = 1875 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache); 1876 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache); 1877 const SCEV *WideMaxBECount = 1878 getZeroExtendExpr(CastedMaxBECount, WideTy); 1879 const SCEV *OperandExtendedAdd = getAddExpr( 1880 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached( 1881 Step, WideTy, Cache))); 1882 if (SAdd == OperandExtendedAdd) { 1883 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1884 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1885 // Return the expression with the addrec on the outside. 1886 return getAddRecExpr( 1887 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1888 getSignExtendExprCached(Step, Ty, Cache), L, 1889 AR->getNoWrapFlags()); 1890 } 1891 // Similar to above, only this time treat the step value as unsigned. 1892 // This covers loops that count up with an unsigned step. 1893 OperandExtendedAdd = 1894 getAddExpr(WideStart, 1895 getMulExpr(WideMaxBECount, 1896 getZeroExtendExpr(Step, WideTy))); 1897 if (SAdd == OperandExtendedAdd) { 1898 // If AR wraps around then 1899 // 1900 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1901 // => SAdd != OperandExtendedAdd 1902 // 1903 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1904 // (SAdd == OperandExtendedAdd => AR is NW) 1905 1906 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1907 1908 // Return the expression with the addrec on the outside. 1909 return getAddRecExpr( 1910 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1911 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1912 } 1913 } 1914 } 1915 1916 // Normally, in the cases we can prove no-overflow via a 1917 // backedge guarding condition, we can also compute a backedge 1918 // taken count for the loop. The exceptions are assumptions and 1919 // guards present in the loop -- SCEV is not great at exploiting 1920 // these to compute max backedge taken counts, but can still use 1921 // these to prove lack of overflow. Use this fact to avoid 1922 // doing extra work that may not pay off. 1923 1924 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1925 !AC.assumptions().empty()) { 1926 // If the backedge is guarded by a comparison with the pre-inc 1927 // value the addrec is safe. Also, if the entry is guarded by 1928 // a comparison with the start value and the backedge is 1929 // guarded by a comparison with the post-inc value, the addrec 1930 // is safe. 1931 ICmpInst::Predicate Pred; 1932 const SCEV *OverflowLimit = 1933 getSignedOverflowLimitForStep(Step, &Pred, this); 1934 if (OverflowLimit && 1935 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1936 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1937 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1938 OverflowLimit)))) { 1939 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1940 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1941 return getAddRecExpr( 1942 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1943 getSignExtendExprCached(Step, Ty, Cache), L, 1944 AR->getNoWrapFlags()); 1945 } 1946 } 1947 1948 // If Start and Step are constants, check if we can apply this 1949 // transformation: 1950 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1951 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1952 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1953 if (SC1 && SC2) { 1954 const APInt &C1 = SC1->getAPInt(); 1955 const APInt &C2 = SC2->getAPInt(); 1956 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1957 C2.isPowerOf2()) { 1958 Start = getSignExtendExprCached(Start, Ty, Cache); 1959 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1960 AR->getNoWrapFlags()); 1961 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache)); 1962 } 1963 } 1964 1965 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1966 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1967 return getAddRecExpr( 1968 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1969 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1970 } 1971 } 1972 1973 // If the input value is provably positive and we could not simplify 1974 // away the sext build a zext instead. 1975 if (isKnownNonNegative(Op)) 1976 return getZeroExtendExpr(Op, Ty); 1977 1978 // The cast wasn't folded; create an explicit cast node. 1979 // Recompute the insert position, as it may have been invalidated. 1980 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1981 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1982 Op, Ty); 1983 UniqueSCEVs.InsertNode(S, IP); 1984 return S; 1985 } 1986 1987 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1988 /// unspecified bits out to the given type. 1989 /// 1990 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1991 Type *Ty) { 1992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1993 "This is not an extending conversion!"); 1994 assert(isSCEVable(Ty) && 1995 "This is not a conversion to a SCEVable type!"); 1996 Ty = getEffectiveSCEVType(Ty); 1997 1998 // Sign-extend negative constants. 1999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2000 if (SC->getAPInt().isNegative()) 2001 return getSignExtendExpr(Op, Ty); 2002 2003 // Peel off a truncate cast. 2004 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2005 const SCEV *NewOp = T->getOperand(); 2006 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2007 return getAnyExtendExpr(NewOp, Ty); 2008 return getTruncateOrNoop(NewOp, Ty); 2009 } 2010 2011 // Next try a zext cast. If the cast is folded, use it. 2012 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2013 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2014 return ZExt; 2015 2016 // Next try a sext cast. If the cast is folded, use it. 2017 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2018 if (!isa<SCEVSignExtendExpr>(SExt)) 2019 return SExt; 2020 2021 // Force the cast to be folded into the operands of an addrec. 2022 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2023 SmallVector<const SCEV *, 4> Ops; 2024 for (const SCEV *Op : AR->operands()) 2025 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2026 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2027 } 2028 2029 // If the expression is obviously signed, use the sext cast value. 2030 if (isa<SCEVSMaxExpr>(Op)) 2031 return SExt; 2032 2033 // Absent any other information, use the zext cast value. 2034 return ZExt; 2035 } 2036 2037 /// Process the given Ops list, which is a list of operands to be added under 2038 /// the given scale, update the given map. This is a helper function for 2039 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2040 /// that would form an add expression like this: 2041 /// 2042 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2043 /// 2044 /// where A and B are constants, update the map with these values: 2045 /// 2046 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2047 /// 2048 /// and add 13 + A*B*29 to AccumulatedConstant. 2049 /// This will allow getAddRecExpr to produce this: 2050 /// 2051 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2052 /// 2053 /// This form often exposes folding opportunities that are hidden in 2054 /// the original operand list. 2055 /// 2056 /// Return true iff it appears that any interesting folding opportunities 2057 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2058 /// the common case where no interesting opportunities are present, and 2059 /// is also used as a check to avoid infinite recursion. 2060 /// 2061 static bool 2062 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2063 SmallVectorImpl<const SCEV *> &NewOps, 2064 APInt &AccumulatedConstant, 2065 const SCEV *const *Ops, size_t NumOperands, 2066 const APInt &Scale, 2067 ScalarEvolution &SE) { 2068 bool Interesting = false; 2069 2070 // Iterate over the add operands. They are sorted, with constants first. 2071 unsigned i = 0; 2072 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2073 ++i; 2074 // Pull a buried constant out to the outside. 2075 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2076 Interesting = true; 2077 AccumulatedConstant += Scale * C->getAPInt(); 2078 } 2079 2080 // Next comes everything else. We're especially interested in multiplies 2081 // here, but they're in the middle, so just visit the rest with one loop. 2082 for (; i != NumOperands; ++i) { 2083 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2084 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2085 APInt NewScale = 2086 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2087 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2088 // A multiplication of a constant with another add; recurse. 2089 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2090 Interesting |= 2091 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2092 Add->op_begin(), Add->getNumOperands(), 2093 NewScale, SE); 2094 } else { 2095 // A multiplication of a constant with some other value. Update 2096 // the map. 2097 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2098 const SCEV *Key = SE.getMulExpr(MulOps); 2099 auto Pair = M.insert({Key, NewScale}); 2100 if (Pair.second) { 2101 NewOps.push_back(Pair.first->first); 2102 } else { 2103 Pair.first->second += NewScale; 2104 // The map already had an entry for this value, which may indicate 2105 // a folding opportunity. 2106 Interesting = true; 2107 } 2108 } 2109 } else { 2110 // An ordinary operand. Update the map. 2111 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2112 M.insert({Ops[i], Scale}); 2113 if (Pair.second) { 2114 NewOps.push_back(Pair.first->first); 2115 } else { 2116 Pair.first->second += Scale; 2117 // The map already had an entry for this value, which may indicate 2118 // a folding opportunity. 2119 Interesting = true; 2120 } 2121 } 2122 } 2123 2124 return Interesting; 2125 } 2126 2127 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2128 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2129 // can't-overflow flags for the operation if possible. 2130 static SCEV::NoWrapFlags 2131 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2132 const SmallVectorImpl<const SCEV *> &Ops, 2133 SCEV::NoWrapFlags Flags) { 2134 using namespace std::placeholders; 2135 typedef OverflowingBinaryOperator OBO; 2136 2137 bool CanAnalyze = 2138 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2139 (void)CanAnalyze; 2140 assert(CanAnalyze && "don't call from other places!"); 2141 2142 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2143 SCEV::NoWrapFlags SignOrUnsignWrap = 2144 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2145 2146 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2147 auto IsKnownNonNegative = [&](const SCEV *S) { 2148 return SE->isKnownNonNegative(S); 2149 }; 2150 2151 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2152 Flags = 2153 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2154 2155 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2156 2157 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2158 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2159 2160 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2161 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2162 2163 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2164 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2165 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2166 Instruction::Add, C, OBO::NoSignedWrap); 2167 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2168 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2169 } 2170 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2171 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2172 Instruction::Add, C, OBO::NoUnsignedWrap); 2173 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2174 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2175 } 2176 } 2177 2178 return Flags; 2179 } 2180 2181 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L, 2182 DominatorTree &DT, LoopInfo &LI) { 2183 if (!isLoopInvariant(S, L)) 2184 return false; 2185 // If a value depends on a SCEVUnknown which is defined after the loop, we 2186 // conservatively assume that we cannot calculate it at the loop's entry. 2187 struct FindDominatedSCEVUnknown { 2188 bool Found = false; 2189 const Loop *L; 2190 DominatorTree &DT; 2191 LoopInfo &LI; 2192 2193 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI) 2194 : L(L), DT(DT), LI(LI) {} 2195 2196 bool checkSCEVUnknown(const SCEVUnknown *SU) { 2197 if (auto *I = dyn_cast<Instruction>(SU->getValue())) { 2198 if (DT.dominates(L->getHeader(), I->getParent())) 2199 Found = true; 2200 else 2201 assert(DT.dominates(I->getParent(), L->getHeader()) && 2202 "No dominance relationship between SCEV and loop?"); 2203 } 2204 return false; 2205 } 2206 2207 bool follow(const SCEV *S) { 2208 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 2209 case scConstant: 2210 return false; 2211 case scAddRecExpr: 2212 case scTruncate: 2213 case scZeroExtend: 2214 case scSignExtend: 2215 case scAddExpr: 2216 case scMulExpr: 2217 case scUMaxExpr: 2218 case scSMaxExpr: 2219 case scUDivExpr: 2220 return true; 2221 case scUnknown: 2222 return checkSCEVUnknown(cast<SCEVUnknown>(S)); 2223 case scCouldNotCompute: 2224 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 2225 } 2226 return false; 2227 } 2228 2229 bool isDone() { return Found; } 2230 }; 2231 2232 FindDominatedSCEVUnknown FSU(L, DT, LI); 2233 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU); 2234 ST.visitAll(S); 2235 return !FSU.Found; 2236 } 2237 2238 /// Get a canonical add expression, or something simpler if possible. 2239 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2240 SCEV::NoWrapFlags Flags, 2241 unsigned Depth) { 2242 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2243 "only nuw or nsw allowed"); 2244 assert(!Ops.empty() && "Cannot get empty add!"); 2245 if (Ops.size() == 1) return Ops[0]; 2246 #ifndef NDEBUG 2247 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2248 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2249 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2250 "SCEVAddExpr operand types don't match!"); 2251 #endif 2252 2253 // Sort by complexity, this groups all similar expression types together. 2254 GroupByComplexity(Ops, &LI, DT); 2255 2256 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2257 2258 // If there are any constants, fold them together. 2259 unsigned Idx = 0; 2260 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2261 ++Idx; 2262 assert(Idx < Ops.size()); 2263 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2264 // We found two constants, fold them together! 2265 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2266 if (Ops.size() == 2) return Ops[0]; 2267 Ops.erase(Ops.begin()+1); // Erase the folded element 2268 LHSC = cast<SCEVConstant>(Ops[0]); 2269 } 2270 2271 // If we are left with a constant zero being added, strip it off. 2272 if (LHSC->getValue()->isZero()) { 2273 Ops.erase(Ops.begin()); 2274 --Idx; 2275 } 2276 2277 if (Ops.size() == 1) return Ops[0]; 2278 } 2279 2280 // Limit recursion calls depth 2281 if (Depth > MaxAddExprDepth) 2282 return getOrCreateAddExpr(Ops, Flags); 2283 2284 // Okay, check to see if the same value occurs in the operand list more than 2285 // once. If so, merge them together into an multiply expression. Since we 2286 // sorted the list, these values are required to be adjacent. 2287 Type *Ty = Ops[0]->getType(); 2288 bool FoundMatch = false; 2289 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2290 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2291 // Scan ahead to count how many equal operands there are. 2292 unsigned Count = 2; 2293 while (i+Count != e && Ops[i+Count] == Ops[i]) 2294 ++Count; 2295 // Merge the values into a multiply. 2296 const SCEV *Scale = getConstant(Ty, Count); 2297 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2298 if (Ops.size() == Count) 2299 return Mul; 2300 Ops[i] = Mul; 2301 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2302 --i; e -= Count - 1; 2303 FoundMatch = true; 2304 } 2305 if (FoundMatch) 2306 return getAddExpr(Ops, Flags); 2307 2308 // Check for truncates. If all the operands are truncated from the same 2309 // type, see if factoring out the truncate would permit the result to be 2310 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2311 // if the contents of the resulting outer trunc fold to something simple. 2312 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2313 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2314 Type *DstType = Trunc->getType(); 2315 Type *SrcType = Trunc->getOperand()->getType(); 2316 SmallVector<const SCEV *, 8> LargeOps; 2317 bool Ok = true; 2318 // Check all the operands to see if they can be represented in the 2319 // source type of the truncate. 2320 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2321 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2322 if (T->getOperand()->getType() != SrcType) { 2323 Ok = false; 2324 break; 2325 } 2326 LargeOps.push_back(T->getOperand()); 2327 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2328 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2329 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2330 SmallVector<const SCEV *, 8> LargeMulOps; 2331 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2332 if (const SCEVTruncateExpr *T = 2333 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2334 if (T->getOperand()->getType() != SrcType) { 2335 Ok = false; 2336 break; 2337 } 2338 LargeMulOps.push_back(T->getOperand()); 2339 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2340 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2341 } else { 2342 Ok = false; 2343 break; 2344 } 2345 } 2346 if (Ok) 2347 LargeOps.push_back(getMulExpr(LargeMulOps)); 2348 } else { 2349 Ok = false; 2350 break; 2351 } 2352 } 2353 if (Ok) { 2354 // Evaluate the expression in the larger type. 2355 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2356 // If it folds to something simple, use it. Otherwise, don't. 2357 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2358 return getTruncateExpr(Fold, DstType); 2359 } 2360 } 2361 2362 // Skip past any other cast SCEVs. 2363 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2364 ++Idx; 2365 2366 // If there are add operands they would be next. 2367 if (Idx < Ops.size()) { 2368 bool DeletedAdd = false; 2369 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2370 if (Ops.size() > AddOpsInlineThreshold || 2371 Add->getNumOperands() > AddOpsInlineThreshold) 2372 break; 2373 // If we have an add, expand the add operands onto the end of the operands 2374 // list. 2375 Ops.erase(Ops.begin()+Idx); 2376 Ops.append(Add->op_begin(), Add->op_end()); 2377 DeletedAdd = true; 2378 } 2379 2380 // If we deleted at least one add, we added operands to the end of the list, 2381 // and they are not necessarily sorted. Recurse to resort and resimplify 2382 // any operands we just acquired. 2383 if (DeletedAdd) 2384 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2385 } 2386 2387 // Skip over the add expression until we get to a multiply. 2388 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2389 ++Idx; 2390 2391 // Check to see if there are any folding opportunities present with 2392 // operands multiplied by constant values. 2393 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2394 uint64_t BitWidth = getTypeSizeInBits(Ty); 2395 DenseMap<const SCEV *, APInt> M; 2396 SmallVector<const SCEV *, 8> NewOps; 2397 APInt AccumulatedConstant(BitWidth, 0); 2398 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2399 Ops.data(), Ops.size(), 2400 APInt(BitWidth, 1), *this)) { 2401 struct APIntCompare { 2402 bool operator()(const APInt &LHS, const APInt &RHS) const { 2403 return LHS.ult(RHS); 2404 } 2405 }; 2406 2407 // Some interesting folding opportunity is present, so its worthwhile to 2408 // re-generate the operands list. Group the operands by constant scale, 2409 // to avoid multiplying by the same constant scale multiple times. 2410 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2411 for (const SCEV *NewOp : NewOps) 2412 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2413 // Re-generate the operands list. 2414 Ops.clear(); 2415 if (AccumulatedConstant != 0) 2416 Ops.push_back(getConstant(AccumulatedConstant)); 2417 for (auto &MulOp : MulOpLists) 2418 if (MulOp.first != 0) 2419 Ops.push_back(getMulExpr( 2420 getConstant(MulOp.first), 2421 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1))); 2422 if (Ops.empty()) 2423 return getZero(Ty); 2424 if (Ops.size() == 1) 2425 return Ops[0]; 2426 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2427 } 2428 } 2429 2430 // If we are adding something to a multiply expression, make sure the 2431 // something is not already an operand of the multiply. If so, merge it into 2432 // the multiply. 2433 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2434 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2435 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2436 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2437 if (isa<SCEVConstant>(MulOpSCEV)) 2438 continue; 2439 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2440 if (MulOpSCEV == Ops[AddOp]) { 2441 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2442 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2443 if (Mul->getNumOperands() != 2) { 2444 // If the multiply has more than two operands, we must get the 2445 // Y*Z term. 2446 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2447 Mul->op_begin()+MulOp); 2448 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2449 InnerMul = getMulExpr(MulOps); 2450 } 2451 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2452 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2453 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2454 if (Ops.size() == 2) return OuterMul; 2455 if (AddOp < Idx) { 2456 Ops.erase(Ops.begin()+AddOp); 2457 Ops.erase(Ops.begin()+Idx-1); 2458 } else { 2459 Ops.erase(Ops.begin()+Idx); 2460 Ops.erase(Ops.begin()+AddOp-1); 2461 } 2462 Ops.push_back(OuterMul); 2463 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2464 } 2465 2466 // Check this multiply against other multiplies being added together. 2467 for (unsigned OtherMulIdx = Idx+1; 2468 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2469 ++OtherMulIdx) { 2470 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2471 // If MulOp occurs in OtherMul, we can fold the two multiplies 2472 // together. 2473 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2474 OMulOp != e; ++OMulOp) 2475 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2476 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2477 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2478 if (Mul->getNumOperands() != 2) { 2479 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2480 Mul->op_begin()+MulOp); 2481 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2482 InnerMul1 = getMulExpr(MulOps); 2483 } 2484 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2485 if (OtherMul->getNumOperands() != 2) { 2486 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2487 OtherMul->op_begin()+OMulOp); 2488 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2489 InnerMul2 = getMulExpr(MulOps); 2490 } 2491 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2492 const SCEV *InnerMulSum = 2493 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2494 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2495 if (Ops.size() == 2) return OuterMul; 2496 Ops.erase(Ops.begin()+Idx); 2497 Ops.erase(Ops.begin()+OtherMulIdx-1); 2498 Ops.push_back(OuterMul); 2499 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2500 } 2501 } 2502 } 2503 } 2504 2505 // If there are any add recurrences in the operands list, see if any other 2506 // added values are loop invariant. If so, we can fold them into the 2507 // recurrence. 2508 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2509 ++Idx; 2510 2511 // Scan over all recurrences, trying to fold loop invariants into them. 2512 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2513 // Scan all of the other operands to this add and add them to the vector if 2514 // they are loop invariant w.r.t. the recurrence. 2515 SmallVector<const SCEV *, 8> LIOps; 2516 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2517 const Loop *AddRecLoop = AddRec->getLoop(); 2518 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2519 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop, DT, LI)) { 2520 LIOps.push_back(Ops[i]); 2521 Ops.erase(Ops.begin()+i); 2522 --i; --e; 2523 } 2524 2525 // If we found some loop invariants, fold them into the recurrence. 2526 if (!LIOps.empty()) { 2527 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2528 LIOps.push_back(AddRec->getStart()); 2529 2530 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2531 AddRec->op_end()); 2532 // This follows from the fact that the no-wrap flags on the outer add 2533 // expression are applicable on the 0th iteration, when the add recurrence 2534 // will be equal to its start value. 2535 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2536 2537 // Build the new addrec. Propagate the NUW and NSW flags if both the 2538 // outer add and the inner addrec are guaranteed to have no overflow. 2539 // Always propagate NW. 2540 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2541 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2542 2543 // If all of the other operands were loop invariant, we are done. 2544 if (Ops.size() == 1) return NewRec; 2545 2546 // Otherwise, add the folded AddRec by the non-invariant parts. 2547 for (unsigned i = 0;; ++i) 2548 if (Ops[i] == AddRec) { 2549 Ops[i] = NewRec; 2550 break; 2551 } 2552 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2553 } 2554 2555 // Okay, if there weren't any loop invariants to be folded, check to see if 2556 // there are multiple AddRec's with the same loop induction variable being 2557 // added together. If so, we can fold them. 2558 for (unsigned OtherIdx = Idx+1; 2559 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2560 ++OtherIdx) { 2561 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2562 // so that the 1st found AddRecExpr is dominated by all others. 2563 assert(DT.dominates( 2564 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2565 AddRec->getLoop()->getHeader()) && 2566 "AddRecExprs are not sorted in reverse dominance order?"); 2567 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2568 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2569 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2570 AddRec->op_end()); 2571 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2572 ++OtherIdx) { 2573 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2574 if (OtherAddRec->getLoop() == AddRecLoop) { 2575 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2576 i != e; ++i) { 2577 if (i >= AddRecOps.size()) { 2578 AddRecOps.append(OtherAddRec->op_begin()+i, 2579 OtherAddRec->op_end()); 2580 break; 2581 } 2582 SmallVector<const SCEV *, 2> TwoOps = { 2583 AddRecOps[i], OtherAddRec->getOperand(i)}; 2584 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2585 } 2586 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2587 } 2588 } 2589 // Step size has changed, so we cannot guarantee no self-wraparound. 2590 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2591 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2592 } 2593 } 2594 2595 // Otherwise couldn't fold anything into this recurrence. Move onto the 2596 // next one. 2597 } 2598 2599 // Okay, it looks like we really DO need an add expr. Check to see if we 2600 // already have one, otherwise create a new one. 2601 return getOrCreateAddExpr(Ops, Flags); 2602 } 2603 2604 const SCEV * 2605 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2606 SCEV::NoWrapFlags Flags) { 2607 FoldingSetNodeID ID; 2608 ID.AddInteger(scAddExpr); 2609 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2610 ID.AddPointer(Ops[i]); 2611 void *IP = nullptr; 2612 SCEVAddExpr *S = 2613 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2614 if (!S) { 2615 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2616 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2617 S = new (SCEVAllocator) 2618 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2619 UniqueSCEVs.InsertNode(S, IP); 2620 } 2621 S->setNoWrapFlags(Flags); 2622 return S; 2623 } 2624 2625 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2626 uint64_t k = i*j; 2627 if (j > 1 && k / j != i) Overflow = true; 2628 return k; 2629 } 2630 2631 /// Compute the result of "n choose k", the binomial coefficient. If an 2632 /// intermediate computation overflows, Overflow will be set and the return will 2633 /// be garbage. Overflow is not cleared on absence of overflow. 2634 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2635 // We use the multiplicative formula: 2636 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2637 // At each iteration, we take the n-th term of the numeral and divide by the 2638 // (k-n)th term of the denominator. This division will always produce an 2639 // integral result, and helps reduce the chance of overflow in the 2640 // intermediate computations. However, we can still overflow even when the 2641 // final result would fit. 2642 2643 if (n == 0 || n == k) return 1; 2644 if (k > n) return 0; 2645 2646 if (k > n/2) 2647 k = n-k; 2648 2649 uint64_t r = 1; 2650 for (uint64_t i = 1; i <= k; ++i) { 2651 r = umul_ov(r, n-(i-1), Overflow); 2652 r /= i; 2653 } 2654 return r; 2655 } 2656 2657 /// Determine if any of the operands in this SCEV are a constant or if 2658 /// any of the add or multiply expressions in this SCEV contain a constant. 2659 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2660 SmallVector<const SCEV *, 4> Ops; 2661 Ops.push_back(StartExpr); 2662 while (!Ops.empty()) { 2663 const SCEV *CurrentExpr = Ops.pop_back_val(); 2664 if (isa<SCEVConstant>(*CurrentExpr)) 2665 return true; 2666 2667 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2668 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2669 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2670 } 2671 } 2672 return false; 2673 } 2674 2675 /// Get a canonical multiply expression, or something simpler if possible. 2676 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2677 SCEV::NoWrapFlags Flags) { 2678 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2679 "only nuw or nsw allowed"); 2680 assert(!Ops.empty() && "Cannot get empty mul!"); 2681 if (Ops.size() == 1) return Ops[0]; 2682 #ifndef NDEBUG 2683 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2684 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2685 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2686 "SCEVMulExpr operand types don't match!"); 2687 #endif 2688 2689 // Sort by complexity, this groups all similar expression types together. 2690 GroupByComplexity(Ops, &LI, DT); 2691 2692 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2693 2694 // If there are any constants, fold them together. 2695 unsigned Idx = 0; 2696 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2697 2698 // C1*(C2+V) -> C1*C2 + C1*V 2699 if (Ops.size() == 2) 2700 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2701 // If any of Add's ops are Adds or Muls with a constant, 2702 // apply this transformation as well. 2703 if (Add->getNumOperands() == 2) 2704 if (containsConstantSomewhere(Add)) 2705 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2706 getMulExpr(LHSC, Add->getOperand(1))); 2707 2708 ++Idx; 2709 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2710 // We found two constants, fold them together! 2711 ConstantInt *Fold = 2712 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2713 Ops[0] = getConstant(Fold); 2714 Ops.erase(Ops.begin()+1); // Erase the folded element 2715 if (Ops.size() == 1) return Ops[0]; 2716 LHSC = cast<SCEVConstant>(Ops[0]); 2717 } 2718 2719 // If we are left with a constant one being multiplied, strip it off. 2720 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2721 Ops.erase(Ops.begin()); 2722 --Idx; 2723 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2724 // If we have a multiply of zero, it will always be zero. 2725 return Ops[0]; 2726 } else if (Ops[0]->isAllOnesValue()) { 2727 // If we have a mul by -1 of an add, try distributing the -1 among the 2728 // add operands. 2729 if (Ops.size() == 2) { 2730 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2731 SmallVector<const SCEV *, 4> NewOps; 2732 bool AnyFolded = false; 2733 for (const SCEV *AddOp : Add->operands()) { 2734 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2735 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2736 NewOps.push_back(Mul); 2737 } 2738 if (AnyFolded) 2739 return getAddExpr(NewOps); 2740 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2741 // Negation preserves a recurrence's no self-wrap property. 2742 SmallVector<const SCEV *, 4> Operands; 2743 for (const SCEV *AddRecOp : AddRec->operands()) 2744 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2745 2746 return getAddRecExpr(Operands, AddRec->getLoop(), 2747 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2748 } 2749 } 2750 } 2751 2752 if (Ops.size() == 1) 2753 return Ops[0]; 2754 } 2755 2756 // Skip over the add expression until we get to a multiply. 2757 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2758 ++Idx; 2759 2760 // If there are mul operands inline them all into this expression. 2761 if (Idx < Ops.size()) { 2762 bool DeletedMul = false; 2763 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2764 if (Ops.size() > MulOpsInlineThreshold) 2765 break; 2766 // If we have an mul, expand the mul operands onto the end of the operands 2767 // list. 2768 Ops.erase(Ops.begin()+Idx); 2769 Ops.append(Mul->op_begin(), Mul->op_end()); 2770 DeletedMul = true; 2771 } 2772 2773 // If we deleted at least one mul, we added operands to the end of the list, 2774 // and they are not necessarily sorted. Recurse to resort and resimplify 2775 // any operands we just acquired. 2776 if (DeletedMul) 2777 return getMulExpr(Ops); 2778 } 2779 2780 // If there are any add recurrences in the operands list, see if any other 2781 // added values are loop invariant. If so, we can fold them into the 2782 // recurrence. 2783 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2784 ++Idx; 2785 2786 // Scan over all recurrences, trying to fold loop invariants into them. 2787 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2788 // Scan all of the other operands to this mul and add them to the vector if 2789 // they are loop invariant w.r.t. the recurrence. 2790 SmallVector<const SCEV *, 8> LIOps; 2791 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2792 const Loop *AddRecLoop = AddRec->getLoop(); 2793 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2794 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop, DT, LI)) { 2795 LIOps.push_back(Ops[i]); 2796 Ops.erase(Ops.begin()+i); 2797 --i; --e; 2798 } 2799 2800 // If we found some loop invariants, fold them into the recurrence. 2801 if (!LIOps.empty()) { 2802 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2803 SmallVector<const SCEV *, 4> NewOps; 2804 NewOps.reserve(AddRec->getNumOperands()); 2805 const SCEV *Scale = getMulExpr(LIOps); 2806 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2807 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2808 2809 // Build the new addrec. Propagate the NUW and NSW flags if both the 2810 // outer mul and the inner addrec are guaranteed to have no overflow. 2811 // 2812 // No self-wrap cannot be guaranteed after changing the step size, but 2813 // will be inferred if either NUW or NSW is true. 2814 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2815 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2816 2817 // If all of the other operands were loop invariant, we are done. 2818 if (Ops.size() == 1) return NewRec; 2819 2820 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2821 for (unsigned i = 0;; ++i) 2822 if (Ops[i] == AddRec) { 2823 Ops[i] = NewRec; 2824 break; 2825 } 2826 return getMulExpr(Ops); 2827 } 2828 2829 // Okay, if there weren't any loop invariants to be folded, check to see if 2830 // there are multiple AddRec's with the same loop induction variable being 2831 // multiplied together. If so, we can fold them. 2832 2833 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2834 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2835 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2836 // ]]],+,...up to x=2n}. 2837 // Note that the arguments to choose() are always integers with values 2838 // known at compile time, never SCEV objects. 2839 // 2840 // The implementation avoids pointless extra computations when the two 2841 // addrec's are of different length (mathematically, it's equivalent to 2842 // an infinite stream of zeros on the right). 2843 bool OpsModified = false; 2844 for (unsigned OtherIdx = Idx+1; 2845 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2846 ++OtherIdx) { 2847 const SCEVAddRecExpr *OtherAddRec = 2848 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2849 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2850 continue; 2851 2852 bool Overflow = false; 2853 Type *Ty = AddRec->getType(); 2854 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2855 SmallVector<const SCEV*, 7> AddRecOps; 2856 for (int x = 0, xe = AddRec->getNumOperands() + 2857 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2858 const SCEV *Term = getZero(Ty); 2859 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2860 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2861 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2862 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2863 z < ze && !Overflow; ++z) { 2864 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2865 uint64_t Coeff; 2866 if (LargerThan64Bits) 2867 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2868 else 2869 Coeff = Coeff1*Coeff2; 2870 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2871 const SCEV *Term1 = AddRec->getOperand(y-z); 2872 const SCEV *Term2 = OtherAddRec->getOperand(z); 2873 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2874 } 2875 } 2876 AddRecOps.push_back(Term); 2877 } 2878 if (!Overflow) { 2879 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2880 SCEV::FlagAnyWrap); 2881 if (Ops.size() == 2) return NewAddRec; 2882 Ops[Idx] = NewAddRec; 2883 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2884 OpsModified = true; 2885 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2886 if (!AddRec) 2887 break; 2888 } 2889 } 2890 if (OpsModified) 2891 return getMulExpr(Ops); 2892 2893 // Otherwise couldn't fold anything into this recurrence. Move onto the 2894 // next one. 2895 } 2896 2897 // Okay, it looks like we really DO need an mul expr. Check to see if we 2898 // already have one, otherwise create a new one. 2899 FoldingSetNodeID ID; 2900 ID.AddInteger(scMulExpr); 2901 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2902 ID.AddPointer(Ops[i]); 2903 void *IP = nullptr; 2904 SCEVMulExpr *S = 2905 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2906 if (!S) { 2907 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2908 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2909 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2910 O, Ops.size()); 2911 UniqueSCEVs.InsertNode(S, IP); 2912 } 2913 S->setNoWrapFlags(Flags); 2914 return S; 2915 } 2916 2917 /// Get a canonical unsigned division expression, or something simpler if 2918 /// possible. 2919 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2920 const SCEV *RHS) { 2921 assert(getEffectiveSCEVType(LHS->getType()) == 2922 getEffectiveSCEVType(RHS->getType()) && 2923 "SCEVUDivExpr operand types don't match!"); 2924 2925 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2926 if (RHSC->getValue()->equalsInt(1)) 2927 return LHS; // X udiv 1 --> x 2928 // If the denominator is zero, the result of the udiv is undefined. Don't 2929 // try to analyze it, because the resolution chosen here may differ from 2930 // the resolution chosen in other parts of the compiler. 2931 if (!RHSC->getValue()->isZero()) { 2932 // Determine if the division can be folded into the operands of 2933 // its operands. 2934 // TODO: Generalize this to non-constants by using known-bits information. 2935 Type *Ty = LHS->getType(); 2936 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2937 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2938 // For non-power-of-two values, effectively round the value up to the 2939 // nearest power of two. 2940 if (!RHSC->getAPInt().isPowerOf2()) 2941 ++MaxShiftAmt; 2942 IntegerType *ExtTy = 2943 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2944 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2945 if (const SCEVConstant *Step = 2946 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2947 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2948 const APInt &StepInt = Step->getAPInt(); 2949 const APInt &DivInt = RHSC->getAPInt(); 2950 if (!StepInt.urem(DivInt) && 2951 getZeroExtendExpr(AR, ExtTy) == 2952 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2953 getZeroExtendExpr(Step, ExtTy), 2954 AR->getLoop(), SCEV::FlagAnyWrap)) { 2955 SmallVector<const SCEV *, 4> Operands; 2956 for (const SCEV *Op : AR->operands()) 2957 Operands.push_back(getUDivExpr(Op, RHS)); 2958 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2959 } 2960 /// Get a canonical UDivExpr for a recurrence. 2961 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2962 // We can currently only fold X%N if X is constant. 2963 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2964 if (StartC && !DivInt.urem(StepInt) && 2965 getZeroExtendExpr(AR, ExtTy) == 2966 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2967 getZeroExtendExpr(Step, ExtTy), 2968 AR->getLoop(), SCEV::FlagAnyWrap)) { 2969 const APInt &StartInt = StartC->getAPInt(); 2970 const APInt &StartRem = StartInt.urem(StepInt); 2971 if (StartRem != 0) 2972 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2973 AR->getLoop(), SCEV::FlagNW); 2974 } 2975 } 2976 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2977 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2978 SmallVector<const SCEV *, 4> Operands; 2979 for (const SCEV *Op : M->operands()) 2980 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2981 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2982 // Find an operand that's safely divisible. 2983 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2984 const SCEV *Op = M->getOperand(i); 2985 const SCEV *Div = getUDivExpr(Op, RHSC); 2986 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2987 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2988 M->op_end()); 2989 Operands[i] = Div; 2990 return getMulExpr(Operands); 2991 } 2992 } 2993 } 2994 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2995 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2996 SmallVector<const SCEV *, 4> Operands; 2997 for (const SCEV *Op : A->operands()) 2998 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2999 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3000 Operands.clear(); 3001 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3002 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3003 if (isa<SCEVUDivExpr>(Op) || 3004 getMulExpr(Op, RHS) != A->getOperand(i)) 3005 break; 3006 Operands.push_back(Op); 3007 } 3008 if (Operands.size() == A->getNumOperands()) 3009 return getAddExpr(Operands); 3010 } 3011 } 3012 3013 // Fold if both operands are constant. 3014 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3015 Constant *LHSCV = LHSC->getValue(); 3016 Constant *RHSCV = RHSC->getValue(); 3017 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3018 RHSCV))); 3019 } 3020 } 3021 } 3022 3023 FoldingSetNodeID ID; 3024 ID.AddInteger(scUDivExpr); 3025 ID.AddPointer(LHS); 3026 ID.AddPointer(RHS); 3027 void *IP = nullptr; 3028 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3029 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3030 LHS, RHS); 3031 UniqueSCEVs.InsertNode(S, IP); 3032 return S; 3033 } 3034 3035 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3036 APInt A = C1->getAPInt().abs(); 3037 APInt B = C2->getAPInt().abs(); 3038 uint32_t ABW = A.getBitWidth(); 3039 uint32_t BBW = B.getBitWidth(); 3040 3041 if (ABW > BBW) 3042 B = B.zext(ABW); 3043 else if (ABW < BBW) 3044 A = A.zext(BBW); 3045 3046 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3047 } 3048 3049 /// Get a canonical unsigned division expression, or something simpler if 3050 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3051 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3052 /// it's not exact because the udiv may be clearing bits. 3053 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3054 const SCEV *RHS) { 3055 // TODO: we could try to find factors in all sorts of things, but for now we 3056 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3057 // end of this file for inspiration. 3058 3059 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3060 if (!Mul || !Mul->hasNoUnsignedWrap()) 3061 return getUDivExpr(LHS, RHS); 3062 3063 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3064 // If the mulexpr multiplies by a constant, then that constant must be the 3065 // first element of the mulexpr. 3066 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3067 if (LHSCst == RHSCst) { 3068 SmallVector<const SCEV *, 2> Operands; 3069 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3070 return getMulExpr(Operands); 3071 } 3072 3073 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3074 // that there's a factor provided by one of the other terms. We need to 3075 // check. 3076 APInt Factor = gcd(LHSCst, RHSCst); 3077 if (!Factor.isIntN(1)) { 3078 LHSCst = 3079 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3080 RHSCst = 3081 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3082 SmallVector<const SCEV *, 2> Operands; 3083 Operands.push_back(LHSCst); 3084 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3085 LHS = getMulExpr(Operands); 3086 RHS = RHSCst; 3087 Mul = dyn_cast<SCEVMulExpr>(LHS); 3088 if (!Mul) 3089 return getUDivExactExpr(LHS, RHS); 3090 } 3091 } 3092 } 3093 3094 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3095 if (Mul->getOperand(i) == RHS) { 3096 SmallVector<const SCEV *, 2> Operands; 3097 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3098 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3099 return getMulExpr(Operands); 3100 } 3101 } 3102 3103 return getUDivExpr(LHS, RHS); 3104 } 3105 3106 /// Get an add recurrence expression for the specified loop. Simplify the 3107 /// expression as much as possible. 3108 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3109 const Loop *L, 3110 SCEV::NoWrapFlags Flags) { 3111 SmallVector<const SCEV *, 4> Operands; 3112 Operands.push_back(Start); 3113 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3114 if (StepChrec->getLoop() == L) { 3115 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3116 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3117 } 3118 3119 Operands.push_back(Step); 3120 return getAddRecExpr(Operands, L, Flags); 3121 } 3122 3123 /// Get an add recurrence expression for the specified loop. Simplify the 3124 /// expression as much as possible. 3125 const SCEV * 3126 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3127 const Loop *L, SCEV::NoWrapFlags Flags) { 3128 if (Operands.size() == 1) return Operands[0]; 3129 #ifndef NDEBUG 3130 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3131 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3132 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3133 "SCEVAddRecExpr operand types don't match!"); 3134 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3135 assert(isLoopInvariant(Operands[i], L) && 3136 "SCEVAddRecExpr operand is not loop-invariant!"); 3137 #endif 3138 3139 if (Operands.back()->isZero()) { 3140 Operands.pop_back(); 3141 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3142 } 3143 3144 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3145 // use that information to infer NUW and NSW flags. However, computing a 3146 // BE count requires calling getAddRecExpr, so we may not yet have a 3147 // meaningful BE count at this point (and if we don't, we'd be stuck 3148 // with a SCEVCouldNotCompute as the cached BE count). 3149 3150 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3151 3152 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3153 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3154 const Loop *NestedLoop = NestedAR->getLoop(); 3155 if (L->contains(NestedLoop) 3156 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3157 : (!NestedLoop->contains(L) && 3158 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3159 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3160 NestedAR->op_end()); 3161 Operands[0] = NestedAR->getStart(); 3162 // AddRecs require their operands be loop-invariant with respect to their 3163 // loops. Don't perform this transformation if it would break this 3164 // requirement. 3165 bool AllInvariant = all_of( 3166 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3167 3168 if (AllInvariant) { 3169 // Create a recurrence for the outer loop with the same step size. 3170 // 3171 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3172 // inner recurrence has the same property. 3173 SCEV::NoWrapFlags OuterFlags = 3174 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3175 3176 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3177 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3178 return isLoopInvariant(Op, NestedLoop); 3179 }); 3180 3181 if (AllInvariant) { 3182 // Ok, both add recurrences are valid after the transformation. 3183 // 3184 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3185 // the outer recurrence has the same property. 3186 SCEV::NoWrapFlags InnerFlags = 3187 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3188 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3189 } 3190 } 3191 // Reset Operands to its original state. 3192 Operands[0] = NestedAR; 3193 } 3194 } 3195 3196 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3197 // already have one, otherwise create a new one. 3198 FoldingSetNodeID ID; 3199 ID.AddInteger(scAddRecExpr); 3200 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3201 ID.AddPointer(Operands[i]); 3202 ID.AddPointer(L); 3203 void *IP = nullptr; 3204 SCEVAddRecExpr *S = 3205 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3206 if (!S) { 3207 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3208 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3209 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3210 O, Operands.size(), L); 3211 UniqueSCEVs.InsertNode(S, IP); 3212 } 3213 S->setNoWrapFlags(Flags); 3214 return S; 3215 } 3216 3217 const SCEV * 3218 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3219 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3220 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3221 // getSCEV(Base)->getType() has the same address space as Base->getType() 3222 // because SCEV::getType() preserves the address space. 3223 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3224 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3225 // instruction to its SCEV, because the Instruction may be guarded by control 3226 // flow and the no-overflow bits may not be valid for the expression in any 3227 // context. This can be fixed similarly to how these flags are handled for 3228 // adds. 3229 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3230 : SCEV::FlagAnyWrap; 3231 3232 const SCEV *TotalOffset = getZero(IntPtrTy); 3233 // The array size is unimportant. The first thing we do on CurTy is getting 3234 // its element type. 3235 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3236 for (const SCEV *IndexExpr : IndexExprs) { 3237 // Compute the (potentially symbolic) offset in bytes for this index. 3238 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3239 // For a struct, add the member offset. 3240 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3241 unsigned FieldNo = Index->getZExtValue(); 3242 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3243 3244 // Add the field offset to the running total offset. 3245 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3246 3247 // Update CurTy to the type of the field at Index. 3248 CurTy = STy->getTypeAtIndex(Index); 3249 } else { 3250 // Update CurTy to its element type. 3251 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3252 // For an array, add the element offset, explicitly scaled. 3253 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3254 // Getelementptr indices are signed. 3255 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3256 3257 // Multiply the index by the element size to compute the element offset. 3258 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3259 3260 // Add the element offset to the running total offset. 3261 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3262 } 3263 } 3264 3265 // Add the total offset from all the GEP indices to the base. 3266 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3267 } 3268 3269 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3270 const SCEV *RHS) { 3271 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3272 return getSMaxExpr(Ops); 3273 } 3274 3275 const SCEV * 3276 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3277 assert(!Ops.empty() && "Cannot get empty smax!"); 3278 if (Ops.size() == 1) return Ops[0]; 3279 #ifndef NDEBUG 3280 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3281 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3282 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3283 "SCEVSMaxExpr operand types don't match!"); 3284 #endif 3285 3286 // Sort by complexity, this groups all similar expression types together. 3287 GroupByComplexity(Ops, &LI, DT); 3288 3289 // If there are any constants, fold them together. 3290 unsigned Idx = 0; 3291 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3292 ++Idx; 3293 assert(Idx < Ops.size()); 3294 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3295 // We found two constants, fold them together! 3296 ConstantInt *Fold = ConstantInt::get( 3297 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3298 Ops[0] = getConstant(Fold); 3299 Ops.erase(Ops.begin()+1); // Erase the folded element 3300 if (Ops.size() == 1) return Ops[0]; 3301 LHSC = cast<SCEVConstant>(Ops[0]); 3302 } 3303 3304 // If we are left with a constant minimum-int, strip it off. 3305 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3306 Ops.erase(Ops.begin()); 3307 --Idx; 3308 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3309 // If we have an smax with a constant maximum-int, it will always be 3310 // maximum-int. 3311 return Ops[0]; 3312 } 3313 3314 if (Ops.size() == 1) return Ops[0]; 3315 } 3316 3317 // Find the first SMax 3318 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3319 ++Idx; 3320 3321 // Check to see if one of the operands is an SMax. If so, expand its operands 3322 // onto our operand list, and recurse to simplify. 3323 if (Idx < Ops.size()) { 3324 bool DeletedSMax = false; 3325 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3326 Ops.erase(Ops.begin()+Idx); 3327 Ops.append(SMax->op_begin(), SMax->op_end()); 3328 DeletedSMax = true; 3329 } 3330 3331 if (DeletedSMax) 3332 return getSMaxExpr(Ops); 3333 } 3334 3335 // Okay, check to see if the same value occurs in the operand list twice. If 3336 // so, delete one. Since we sorted the list, these values are required to 3337 // be adjacent. 3338 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3339 // X smax Y smax Y --> X smax Y 3340 // X smax Y --> X, if X is always greater than Y 3341 if (Ops[i] == Ops[i+1] || 3342 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3343 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3344 --i; --e; 3345 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3346 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3347 --i; --e; 3348 } 3349 3350 if (Ops.size() == 1) return Ops[0]; 3351 3352 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3353 3354 // Okay, it looks like we really DO need an smax expr. Check to see if we 3355 // already have one, otherwise create a new one. 3356 FoldingSetNodeID ID; 3357 ID.AddInteger(scSMaxExpr); 3358 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3359 ID.AddPointer(Ops[i]); 3360 void *IP = nullptr; 3361 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3362 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3363 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3364 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3365 O, Ops.size()); 3366 UniqueSCEVs.InsertNode(S, IP); 3367 return S; 3368 } 3369 3370 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3371 const SCEV *RHS) { 3372 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3373 return getUMaxExpr(Ops); 3374 } 3375 3376 const SCEV * 3377 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3378 assert(!Ops.empty() && "Cannot get empty umax!"); 3379 if (Ops.size() == 1) return Ops[0]; 3380 #ifndef NDEBUG 3381 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3382 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3383 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3384 "SCEVUMaxExpr operand types don't match!"); 3385 #endif 3386 3387 // Sort by complexity, this groups all similar expression types together. 3388 GroupByComplexity(Ops, &LI, DT); 3389 3390 // If there are any constants, fold them together. 3391 unsigned Idx = 0; 3392 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3393 ++Idx; 3394 assert(Idx < Ops.size()); 3395 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3396 // We found two constants, fold them together! 3397 ConstantInt *Fold = ConstantInt::get( 3398 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3399 Ops[0] = getConstant(Fold); 3400 Ops.erase(Ops.begin()+1); // Erase the folded element 3401 if (Ops.size() == 1) return Ops[0]; 3402 LHSC = cast<SCEVConstant>(Ops[0]); 3403 } 3404 3405 // If we are left with a constant minimum-int, strip it off. 3406 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3407 Ops.erase(Ops.begin()); 3408 --Idx; 3409 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3410 // If we have an umax with a constant maximum-int, it will always be 3411 // maximum-int. 3412 return Ops[0]; 3413 } 3414 3415 if (Ops.size() == 1) return Ops[0]; 3416 } 3417 3418 // Find the first UMax 3419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3420 ++Idx; 3421 3422 // Check to see if one of the operands is a UMax. If so, expand its operands 3423 // onto our operand list, and recurse to simplify. 3424 if (Idx < Ops.size()) { 3425 bool DeletedUMax = false; 3426 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3427 Ops.erase(Ops.begin()+Idx); 3428 Ops.append(UMax->op_begin(), UMax->op_end()); 3429 DeletedUMax = true; 3430 } 3431 3432 if (DeletedUMax) 3433 return getUMaxExpr(Ops); 3434 } 3435 3436 // Okay, check to see if the same value occurs in the operand list twice. If 3437 // so, delete one. Since we sorted the list, these values are required to 3438 // be adjacent. 3439 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3440 // X umax Y umax Y --> X umax Y 3441 // X umax Y --> X, if X is always greater than Y 3442 if (Ops[i] == Ops[i+1] || 3443 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3444 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3445 --i; --e; 3446 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3447 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3448 --i; --e; 3449 } 3450 3451 if (Ops.size() == 1) return Ops[0]; 3452 3453 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3454 3455 // Okay, it looks like we really DO need a umax expr. Check to see if we 3456 // already have one, otherwise create a new one. 3457 FoldingSetNodeID ID; 3458 ID.AddInteger(scUMaxExpr); 3459 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3460 ID.AddPointer(Ops[i]); 3461 void *IP = nullptr; 3462 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3463 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3464 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3465 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3466 O, Ops.size()); 3467 UniqueSCEVs.InsertNode(S, IP); 3468 return S; 3469 } 3470 3471 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3472 const SCEV *RHS) { 3473 // ~smax(~x, ~y) == smin(x, y). 3474 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3475 } 3476 3477 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3478 const SCEV *RHS) { 3479 // ~umax(~x, ~y) == umin(x, y) 3480 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3481 } 3482 3483 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3484 // We can bypass creating a target-independent 3485 // constant expression and then folding it back into a ConstantInt. 3486 // This is just a compile-time optimization. 3487 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3488 } 3489 3490 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3491 StructType *STy, 3492 unsigned FieldNo) { 3493 // We can bypass creating a target-independent 3494 // constant expression and then folding it back into a ConstantInt. 3495 // This is just a compile-time optimization. 3496 return getConstant( 3497 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3498 } 3499 3500 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3501 // Don't attempt to do anything other than create a SCEVUnknown object 3502 // here. createSCEV only calls getUnknown after checking for all other 3503 // interesting possibilities, and any other code that calls getUnknown 3504 // is doing so in order to hide a value from SCEV canonicalization. 3505 3506 FoldingSetNodeID ID; 3507 ID.AddInteger(scUnknown); 3508 ID.AddPointer(V); 3509 void *IP = nullptr; 3510 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3511 assert(cast<SCEVUnknown>(S)->getValue() == V && 3512 "Stale SCEVUnknown in uniquing map!"); 3513 return S; 3514 } 3515 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3516 FirstUnknown); 3517 FirstUnknown = cast<SCEVUnknown>(S); 3518 UniqueSCEVs.InsertNode(S, IP); 3519 return S; 3520 } 3521 3522 //===----------------------------------------------------------------------===// 3523 // Basic SCEV Analysis and PHI Idiom Recognition Code 3524 // 3525 3526 /// Test if values of the given type are analyzable within the SCEV 3527 /// framework. This primarily includes integer types, and it can optionally 3528 /// include pointer types if the ScalarEvolution class has access to 3529 /// target-specific information. 3530 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3531 // Integers and pointers are always SCEVable. 3532 return Ty->isIntegerTy() || Ty->isPointerTy(); 3533 } 3534 3535 /// Return the size in bits of the specified type, for which isSCEVable must 3536 /// return true. 3537 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3538 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3539 return getDataLayout().getTypeSizeInBits(Ty); 3540 } 3541 3542 /// Return a type with the same bitwidth as the given type and which represents 3543 /// how SCEV will treat the given type, for which isSCEVable must return 3544 /// true. For pointer types, this is the pointer-sized integer type. 3545 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3546 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3547 3548 if (Ty->isIntegerTy()) 3549 return Ty; 3550 3551 // The only other support type is pointer. 3552 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3553 return getDataLayout().getIntPtrType(Ty); 3554 } 3555 3556 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3557 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3558 } 3559 3560 const SCEV *ScalarEvolution::getCouldNotCompute() { 3561 return CouldNotCompute.get(); 3562 } 3563 3564 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3565 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3566 auto *SU = dyn_cast<SCEVUnknown>(S); 3567 return SU && SU->getValue() == nullptr; 3568 }); 3569 3570 return !ContainsNulls; 3571 } 3572 3573 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3574 HasRecMapType::iterator I = HasRecMap.find(S); 3575 if (I != HasRecMap.end()) 3576 return I->second; 3577 3578 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3579 HasRecMap.insert({S, FoundAddRec}); 3580 return FoundAddRec; 3581 } 3582 3583 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3584 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3585 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3586 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3587 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3588 if (!Add) 3589 return {S, nullptr}; 3590 3591 if (Add->getNumOperands() != 2) 3592 return {S, nullptr}; 3593 3594 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3595 if (!ConstOp) 3596 return {S, nullptr}; 3597 3598 return {Add->getOperand(1), ConstOp->getValue()}; 3599 } 3600 3601 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3602 /// by the value and offset from any ValueOffsetPair in the set. 3603 SetVector<ScalarEvolution::ValueOffsetPair> * 3604 ScalarEvolution::getSCEVValues(const SCEV *S) { 3605 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3606 if (SI == ExprValueMap.end()) 3607 return nullptr; 3608 #ifndef NDEBUG 3609 if (VerifySCEVMap) { 3610 // Check there is no dangling Value in the set returned. 3611 for (const auto &VE : SI->second) 3612 assert(ValueExprMap.count(VE.first)); 3613 } 3614 #endif 3615 return &SI->second; 3616 } 3617 3618 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3619 /// cannot be used separately. eraseValueFromMap should be used to remove 3620 /// V from ValueExprMap and ExprValueMap at the same time. 3621 void ScalarEvolution::eraseValueFromMap(Value *V) { 3622 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3623 if (I != ValueExprMap.end()) { 3624 const SCEV *S = I->second; 3625 // Remove {V, 0} from the set of ExprValueMap[S] 3626 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3627 SV->remove({V, nullptr}); 3628 3629 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3630 const SCEV *Stripped; 3631 ConstantInt *Offset; 3632 std::tie(Stripped, Offset) = splitAddExpr(S); 3633 if (Offset != nullptr) { 3634 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3635 SV->remove({V, Offset}); 3636 } 3637 ValueExprMap.erase(V); 3638 } 3639 } 3640 3641 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3642 /// create a new one. 3643 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3644 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3645 3646 const SCEV *S = getExistingSCEV(V); 3647 if (S == nullptr) { 3648 S = createSCEV(V); 3649 // During PHI resolution, it is possible to create two SCEVs for the same 3650 // V, so it is needed to double check whether V->S is inserted into 3651 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3652 std::pair<ValueExprMapType::iterator, bool> Pair = 3653 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3654 if (Pair.second) { 3655 ExprValueMap[S].insert({V, nullptr}); 3656 3657 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3658 // ExprValueMap. 3659 const SCEV *Stripped = S; 3660 ConstantInt *Offset = nullptr; 3661 std::tie(Stripped, Offset) = splitAddExpr(S); 3662 // If stripped is SCEVUnknown, don't bother to save 3663 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3664 // increase the complexity of the expansion code. 3665 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3666 // because it may generate add/sub instead of GEP in SCEV expansion. 3667 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3668 !isa<GetElementPtrInst>(V)) 3669 ExprValueMap[Stripped].insert({V, Offset}); 3670 } 3671 } 3672 return S; 3673 } 3674 3675 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3676 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3677 3678 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3679 if (I != ValueExprMap.end()) { 3680 const SCEV *S = I->second; 3681 if (checkValidity(S)) 3682 return S; 3683 eraseValueFromMap(V); 3684 forgetMemoizedResults(S); 3685 } 3686 return nullptr; 3687 } 3688 3689 /// Return a SCEV corresponding to -V = -1*V 3690 /// 3691 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3692 SCEV::NoWrapFlags Flags) { 3693 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3694 return getConstant( 3695 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3696 3697 Type *Ty = V->getType(); 3698 Ty = getEffectiveSCEVType(Ty); 3699 return getMulExpr( 3700 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3701 } 3702 3703 /// Return a SCEV corresponding to ~V = -1-V 3704 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3705 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3706 return getConstant( 3707 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3708 3709 Type *Ty = V->getType(); 3710 Ty = getEffectiveSCEVType(Ty); 3711 const SCEV *AllOnes = 3712 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3713 return getMinusSCEV(AllOnes, V); 3714 } 3715 3716 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3717 SCEV::NoWrapFlags Flags) { 3718 // Fast path: X - X --> 0. 3719 if (LHS == RHS) 3720 return getZero(LHS->getType()); 3721 3722 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3723 // makes it so that we cannot make much use of NUW. 3724 auto AddFlags = SCEV::FlagAnyWrap; 3725 const bool RHSIsNotMinSigned = 3726 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3727 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3728 // Let M be the minimum representable signed value. Then (-1)*RHS 3729 // signed-wraps if and only if RHS is M. That can happen even for 3730 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3731 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3732 // (-1)*RHS, we need to prove that RHS != M. 3733 // 3734 // If LHS is non-negative and we know that LHS - RHS does not 3735 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3736 // either by proving that RHS > M or that LHS >= 0. 3737 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3738 AddFlags = SCEV::FlagNSW; 3739 } 3740 } 3741 3742 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3743 // RHS is NSW and LHS >= 0. 3744 // 3745 // The difficulty here is that the NSW flag may have been proven 3746 // relative to a loop that is to be found in a recurrence in LHS and 3747 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3748 // larger scope than intended. 3749 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3750 3751 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3752 } 3753 3754 const SCEV * 3755 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3756 Type *SrcTy = V->getType(); 3757 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3758 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3759 "Cannot truncate or zero extend with non-integer arguments!"); 3760 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3761 return V; // No conversion 3762 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3763 return getTruncateExpr(V, Ty); 3764 return getZeroExtendExpr(V, Ty); 3765 } 3766 3767 const SCEV * 3768 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3769 Type *Ty) { 3770 Type *SrcTy = V->getType(); 3771 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3772 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3773 "Cannot truncate or zero extend with non-integer arguments!"); 3774 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3775 return V; // No conversion 3776 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3777 return getTruncateExpr(V, Ty); 3778 return getSignExtendExpr(V, Ty); 3779 } 3780 3781 const SCEV * 3782 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3783 Type *SrcTy = V->getType(); 3784 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3785 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3786 "Cannot noop or zero extend with non-integer arguments!"); 3787 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3788 "getNoopOrZeroExtend cannot truncate!"); 3789 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3790 return V; // No conversion 3791 return getZeroExtendExpr(V, Ty); 3792 } 3793 3794 const SCEV * 3795 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3796 Type *SrcTy = V->getType(); 3797 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3798 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3799 "Cannot noop or sign extend with non-integer arguments!"); 3800 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3801 "getNoopOrSignExtend cannot truncate!"); 3802 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3803 return V; // No conversion 3804 return getSignExtendExpr(V, Ty); 3805 } 3806 3807 const SCEV * 3808 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3809 Type *SrcTy = V->getType(); 3810 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3811 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3812 "Cannot noop or any extend with non-integer arguments!"); 3813 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3814 "getNoopOrAnyExtend cannot truncate!"); 3815 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3816 return V; // No conversion 3817 return getAnyExtendExpr(V, Ty); 3818 } 3819 3820 const SCEV * 3821 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3822 Type *SrcTy = V->getType(); 3823 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3824 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3825 "Cannot truncate or noop with non-integer arguments!"); 3826 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3827 "getTruncateOrNoop cannot extend!"); 3828 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3829 return V; // No conversion 3830 return getTruncateExpr(V, Ty); 3831 } 3832 3833 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3834 const SCEV *RHS) { 3835 const SCEV *PromotedLHS = LHS; 3836 const SCEV *PromotedRHS = RHS; 3837 3838 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3839 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3840 else 3841 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3842 3843 return getUMaxExpr(PromotedLHS, PromotedRHS); 3844 } 3845 3846 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3847 const SCEV *RHS) { 3848 const SCEV *PromotedLHS = LHS; 3849 const SCEV *PromotedRHS = RHS; 3850 3851 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3852 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3853 else 3854 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3855 3856 return getUMinExpr(PromotedLHS, PromotedRHS); 3857 } 3858 3859 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3860 // A pointer operand may evaluate to a nonpointer expression, such as null. 3861 if (!V->getType()->isPointerTy()) 3862 return V; 3863 3864 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3865 return getPointerBase(Cast->getOperand()); 3866 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3867 const SCEV *PtrOp = nullptr; 3868 for (const SCEV *NAryOp : NAry->operands()) { 3869 if (NAryOp->getType()->isPointerTy()) { 3870 // Cannot find the base of an expression with multiple pointer operands. 3871 if (PtrOp) 3872 return V; 3873 PtrOp = NAryOp; 3874 } 3875 } 3876 if (!PtrOp) 3877 return V; 3878 return getPointerBase(PtrOp); 3879 } 3880 return V; 3881 } 3882 3883 /// Push users of the given Instruction onto the given Worklist. 3884 static void 3885 PushDefUseChildren(Instruction *I, 3886 SmallVectorImpl<Instruction *> &Worklist) { 3887 // Push the def-use children onto the Worklist stack. 3888 for (User *U : I->users()) 3889 Worklist.push_back(cast<Instruction>(U)); 3890 } 3891 3892 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3893 SmallVector<Instruction *, 16> Worklist; 3894 PushDefUseChildren(PN, Worklist); 3895 3896 SmallPtrSet<Instruction *, 8> Visited; 3897 Visited.insert(PN); 3898 while (!Worklist.empty()) { 3899 Instruction *I = Worklist.pop_back_val(); 3900 if (!Visited.insert(I).second) 3901 continue; 3902 3903 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3904 if (It != ValueExprMap.end()) { 3905 const SCEV *Old = It->second; 3906 3907 // Short-circuit the def-use traversal if the symbolic name 3908 // ceases to appear in expressions. 3909 if (Old != SymName && !hasOperand(Old, SymName)) 3910 continue; 3911 3912 // SCEVUnknown for a PHI either means that it has an unrecognized 3913 // structure, it's a PHI that's in the progress of being computed 3914 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3915 // additional loop trip count information isn't going to change anything. 3916 // In the second case, createNodeForPHI will perform the necessary 3917 // updates on its own when it gets to that point. In the third, we do 3918 // want to forget the SCEVUnknown. 3919 if (!isa<PHINode>(I) || 3920 !isa<SCEVUnknown>(Old) || 3921 (I != PN && Old == SymName)) { 3922 eraseValueFromMap(It->first); 3923 forgetMemoizedResults(Old); 3924 } 3925 } 3926 3927 PushDefUseChildren(I, Worklist); 3928 } 3929 } 3930 3931 namespace { 3932 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3933 public: 3934 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3935 ScalarEvolution &SE) { 3936 SCEVInitRewriter Rewriter(L, SE); 3937 const SCEV *Result = Rewriter.visit(S); 3938 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3939 } 3940 3941 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3942 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3943 3944 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3945 if (!SE.isLoopInvariant(Expr, L)) 3946 Valid = false; 3947 return Expr; 3948 } 3949 3950 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3951 // Only allow AddRecExprs for this loop. 3952 if (Expr->getLoop() == L) 3953 return Expr->getStart(); 3954 Valid = false; 3955 return Expr; 3956 } 3957 3958 bool isValid() { return Valid; } 3959 3960 private: 3961 const Loop *L; 3962 bool Valid; 3963 }; 3964 3965 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3966 public: 3967 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3968 ScalarEvolution &SE) { 3969 SCEVShiftRewriter Rewriter(L, SE); 3970 const SCEV *Result = Rewriter.visit(S); 3971 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3972 } 3973 3974 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3975 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3976 3977 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3978 // Only allow AddRecExprs for this loop. 3979 if (!SE.isLoopInvariant(Expr, L)) 3980 Valid = false; 3981 return Expr; 3982 } 3983 3984 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3985 if (Expr->getLoop() == L && Expr->isAffine()) 3986 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3987 Valid = false; 3988 return Expr; 3989 } 3990 bool isValid() { return Valid; } 3991 3992 private: 3993 const Loop *L; 3994 bool Valid; 3995 }; 3996 } // end anonymous namespace 3997 3998 SCEV::NoWrapFlags 3999 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4000 if (!AR->isAffine()) 4001 return SCEV::FlagAnyWrap; 4002 4003 typedef OverflowingBinaryOperator OBO; 4004 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4005 4006 if (!AR->hasNoSignedWrap()) { 4007 ConstantRange AddRecRange = getSignedRange(AR); 4008 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4009 4010 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4011 Instruction::Add, IncRange, OBO::NoSignedWrap); 4012 if (NSWRegion.contains(AddRecRange)) 4013 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4014 } 4015 4016 if (!AR->hasNoUnsignedWrap()) { 4017 ConstantRange AddRecRange = getUnsignedRange(AR); 4018 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4019 4020 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4021 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4022 if (NUWRegion.contains(AddRecRange)) 4023 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4024 } 4025 4026 return Result; 4027 } 4028 4029 namespace { 4030 /// Represents an abstract binary operation. This may exist as a 4031 /// normal instruction or constant expression, or may have been 4032 /// derived from an expression tree. 4033 struct BinaryOp { 4034 unsigned Opcode; 4035 Value *LHS; 4036 Value *RHS; 4037 bool IsNSW; 4038 bool IsNUW; 4039 4040 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4041 /// constant expression. 4042 Operator *Op; 4043 4044 explicit BinaryOp(Operator *Op) 4045 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4046 IsNSW(false), IsNUW(false), Op(Op) { 4047 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4048 IsNSW = OBO->hasNoSignedWrap(); 4049 IsNUW = OBO->hasNoUnsignedWrap(); 4050 } 4051 } 4052 4053 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4054 bool IsNUW = false) 4055 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4056 Op(nullptr) {} 4057 }; 4058 } 4059 4060 4061 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4062 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4063 auto *Op = dyn_cast<Operator>(V); 4064 if (!Op) 4065 return None; 4066 4067 // Implementation detail: all the cleverness here should happen without 4068 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4069 // SCEV expressions when possible, and we should not break that. 4070 4071 switch (Op->getOpcode()) { 4072 case Instruction::Add: 4073 case Instruction::Sub: 4074 case Instruction::Mul: 4075 case Instruction::UDiv: 4076 case Instruction::And: 4077 case Instruction::Or: 4078 case Instruction::AShr: 4079 case Instruction::Shl: 4080 return BinaryOp(Op); 4081 4082 case Instruction::Xor: 4083 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4084 // If the RHS of the xor is a signmask, then this is just an add. 4085 // Instcombine turns add of signmask into xor as a strength reduction step. 4086 if (RHSC->getValue().isSignMask()) 4087 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4088 return BinaryOp(Op); 4089 4090 case Instruction::LShr: 4091 // Turn logical shift right of a constant into a unsigned divide. 4092 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4093 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4094 4095 // If the shift count is not less than the bitwidth, the result of 4096 // the shift is undefined. Don't try to analyze it, because the 4097 // resolution chosen here may differ from the resolution chosen in 4098 // other parts of the compiler. 4099 if (SA->getValue().ult(BitWidth)) { 4100 Constant *X = 4101 ConstantInt::get(SA->getContext(), 4102 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4103 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4104 } 4105 } 4106 return BinaryOp(Op); 4107 4108 case Instruction::ExtractValue: { 4109 auto *EVI = cast<ExtractValueInst>(Op); 4110 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4111 break; 4112 4113 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4114 if (!CI) 4115 break; 4116 4117 if (auto *F = CI->getCalledFunction()) 4118 switch (F->getIntrinsicID()) { 4119 case Intrinsic::sadd_with_overflow: 4120 case Intrinsic::uadd_with_overflow: { 4121 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4122 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4123 CI->getArgOperand(1)); 4124 4125 // Now that we know that all uses of the arithmetic-result component of 4126 // CI are guarded by the overflow check, we can go ahead and pretend 4127 // that the arithmetic is non-overflowing. 4128 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4129 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4130 CI->getArgOperand(1), /* IsNSW = */ true, 4131 /* IsNUW = */ false); 4132 else 4133 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4134 CI->getArgOperand(1), /* IsNSW = */ false, 4135 /* IsNUW*/ true); 4136 } 4137 4138 case Intrinsic::ssub_with_overflow: 4139 case Intrinsic::usub_with_overflow: 4140 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4141 CI->getArgOperand(1)); 4142 4143 case Intrinsic::smul_with_overflow: 4144 case Intrinsic::umul_with_overflow: 4145 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4146 CI->getArgOperand(1)); 4147 default: 4148 break; 4149 } 4150 } 4151 4152 default: 4153 break; 4154 } 4155 4156 return None; 4157 } 4158 4159 /// A helper function for createAddRecFromPHI to handle simple cases. 4160 /// 4161 /// This function tries to find an AddRec expression for the simplest (yet most 4162 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4163 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4164 /// technique for finding the AddRec expression. 4165 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4166 Value *BEValueV, 4167 Value *StartValueV) { 4168 const Loop *L = LI.getLoopFor(PN->getParent()); 4169 assert(L && L->getHeader() == PN->getParent()); 4170 assert(BEValueV && StartValueV); 4171 4172 auto BO = MatchBinaryOp(BEValueV, DT); 4173 if (!BO) 4174 return nullptr; 4175 4176 if (BO->Opcode != Instruction::Add) 4177 return nullptr; 4178 4179 const SCEV *Accum = nullptr; 4180 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4181 Accum = getSCEV(BO->RHS); 4182 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4183 Accum = getSCEV(BO->LHS); 4184 4185 if (!Accum) 4186 return nullptr; 4187 4188 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4189 if (BO->IsNUW) 4190 Flags = setFlags(Flags, SCEV::FlagNUW); 4191 if (BO->IsNSW) 4192 Flags = setFlags(Flags, SCEV::FlagNSW); 4193 4194 const SCEV *StartVal = getSCEV(StartValueV); 4195 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4196 4197 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4198 4199 // We can add Flags to the post-inc expression only if we 4200 // know that it is *undefined behavior* for BEValueV to 4201 // overflow. 4202 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4203 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4204 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4205 4206 return PHISCEV; 4207 } 4208 4209 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4210 const Loop *L = LI.getLoopFor(PN->getParent()); 4211 if (!L || L->getHeader() != PN->getParent()) 4212 return nullptr; 4213 4214 // The loop may have multiple entrances or multiple exits; we can analyze 4215 // this phi as an addrec if it has a unique entry value and a unique 4216 // backedge value. 4217 Value *BEValueV = nullptr, *StartValueV = nullptr; 4218 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4219 Value *V = PN->getIncomingValue(i); 4220 if (L->contains(PN->getIncomingBlock(i))) { 4221 if (!BEValueV) { 4222 BEValueV = V; 4223 } else if (BEValueV != V) { 4224 BEValueV = nullptr; 4225 break; 4226 } 4227 } else if (!StartValueV) { 4228 StartValueV = V; 4229 } else if (StartValueV != V) { 4230 StartValueV = nullptr; 4231 break; 4232 } 4233 } 4234 if (!BEValueV || !StartValueV) 4235 return nullptr; 4236 4237 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4238 "PHI node already processed?"); 4239 4240 // First, try to find AddRec expression without creating a fictituos symbolic 4241 // value for PN. 4242 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4243 return S; 4244 4245 // Handle PHI node value symbolically. 4246 const SCEV *SymbolicName = getUnknown(PN); 4247 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4248 4249 // Using this symbolic name for the PHI, analyze the value coming around 4250 // the back-edge. 4251 const SCEV *BEValue = getSCEV(BEValueV); 4252 4253 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4254 // has a special value for the first iteration of the loop. 4255 4256 // If the value coming around the backedge is an add with the symbolic 4257 // value we just inserted, then we found a simple induction variable! 4258 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4259 // If there is a single occurrence of the symbolic value, replace it 4260 // with a recurrence. 4261 unsigned FoundIndex = Add->getNumOperands(); 4262 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4263 if (Add->getOperand(i) == SymbolicName) 4264 if (FoundIndex == e) { 4265 FoundIndex = i; 4266 break; 4267 } 4268 4269 if (FoundIndex != Add->getNumOperands()) { 4270 // Create an add with everything but the specified operand. 4271 SmallVector<const SCEV *, 8> Ops; 4272 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4273 if (i != FoundIndex) 4274 Ops.push_back(Add->getOperand(i)); 4275 const SCEV *Accum = getAddExpr(Ops); 4276 4277 // This is not a valid addrec if the step amount is varying each 4278 // loop iteration, but is not itself an addrec in this loop. 4279 if (isLoopInvariant(Accum, L) || 4280 (isa<SCEVAddRecExpr>(Accum) && 4281 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4282 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4283 4284 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4285 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4286 if (BO->IsNUW) 4287 Flags = setFlags(Flags, SCEV::FlagNUW); 4288 if (BO->IsNSW) 4289 Flags = setFlags(Flags, SCEV::FlagNSW); 4290 } 4291 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4292 // If the increment is an inbounds GEP, then we know the address 4293 // space cannot be wrapped around. We cannot make any guarantee 4294 // about signed or unsigned overflow because pointers are 4295 // unsigned but we may have a negative index from the base 4296 // pointer. We can guarantee that no unsigned wrap occurs if the 4297 // indices form a positive value. 4298 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4299 Flags = setFlags(Flags, SCEV::FlagNW); 4300 4301 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4302 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4303 Flags = setFlags(Flags, SCEV::FlagNUW); 4304 } 4305 4306 // We cannot transfer nuw and nsw flags from subtraction 4307 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4308 // for instance. 4309 } 4310 4311 const SCEV *StartVal = getSCEV(StartValueV); 4312 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4313 4314 // Okay, for the entire analysis of this edge we assumed the PHI 4315 // to be symbolic. We now need to go back and purge all of the 4316 // entries for the scalars that use the symbolic expression. 4317 forgetSymbolicName(PN, SymbolicName); 4318 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4319 4320 // We can add Flags to the post-inc expression only if we 4321 // know that it is *undefined behavior* for BEValueV to 4322 // overflow. 4323 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4324 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4325 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4326 4327 return PHISCEV; 4328 } 4329 } 4330 } else { 4331 // Otherwise, this could be a loop like this: 4332 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4333 // In this case, j = {1,+,1} and BEValue is j. 4334 // Because the other in-value of i (0) fits the evolution of BEValue 4335 // i really is an addrec evolution. 4336 // 4337 // We can generalize this saying that i is the shifted value of BEValue 4338 // by one iteration: 4339 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4340 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4341 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4342 if (Shifted != getCouldNotCompute() && 4343 Start != getCouldNotCompute()) { 4344 const SCEV *StartVal = getSCEV(StartValueV); 4345 if (Start == StartVal) { 4346 // Okay, for the entire analysis of this edge we assumed the PHI 4347 // to be symbolic. We now need to go back and purge all of the 4348 // entries for the scalars that use the symbolic expression. 4349 forgetSymbolicName(PN, SymbolicName); 4350 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4351 return Shifted; 4352 } 4353 } 4354 } 4355 4356 // Remove the temporary PHI node SCEV that has been inserted while intending 4357 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4358 // as it will prevent later (possibly simpler) SCEV expressions to be added 4359 // to the ValueExprMap. 4360 eraseValueFromMap(PN); 4361 4362 return nullptr; 4363 } 4364 4365 // Checks if the SCEV S is available at BB. S is considered available at BB 4366 // if S can be materialized at BB without introducing a fault. 4367 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4368 BasicBlock *BB) { 4369 struct CheckAvailable { 4370 bool TraversalDone = false; 4371 bool Available = true; 4372 4373 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4374 BasicBlock *BB = nullptr; 4375 DominatorTree &DT; 4376 4377 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4378 : L(L), BB(BB), DT(DT) {} 4379 4380 bool setUnavailable() { 4381 TraversalDone = true; 4382 Available = false; 4383 return false; 4384 } 4385 4386 bool follow(const SCEV *S) { 4387 switch (S->getSCEVType()) { 4388 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4389 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4390 // These expressions are available if their operand(s) is/are. 4391 return true; 4392 4393 case scAddRecExpr: { 4394 // We allow add recurrences that are on the loop BB is in, or some 4395 // outer loop. This guarantees availability because the value of the 4396 // add recurrence at BB is simply the "current" value of the induction 4397 // variable. We can relax this in the future; for instance an add 4398 // recurrence on a sibling dominating loop is also available at BB. 4399 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4400 if (L && (ARLoop == L || ARLoop->contains(L))) 4401 return true; 4402 4403 return setUnavailable(); 4404 } 4405 4406 case scUnknown: { 4407 // For SCEVUnknown, we check for simple dominance. 4408 const auto *SU = cast<SCEVUnknown>(S); 4409 Value *V = SU->getValue(); 4410 4411 if (isa<Argument>(V)) 4412 return false; 4413 4414 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4415 return false; 4416 4417 return setUnavailable(); 4418 } 4419 4420 case scUDivExpr: 4421 case scCouldNotCompute: 4422 // We do not try to smart about these at all. 4423 return setUnavailable(); 4424 } 4425 llvm_unreachable("switch should be fully covered!"); 4426 } 4427 4428 bool isDone() { return TraversalDone; } 4429 }; 4430 4431 CheckAvailable CA(L, BB, DT); 4432 SCEVTraversal<CheckAvailable> ST(CA); 4433 4434 ST.visitAll(S); 4435 return CA.Available; 4436 } 4437 4438 // Try to match a control flow sequence that branches out at BI and merges back 4439 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4440 // match. 4441 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4442 Value *&C, Value *&LHS, Value *&RHS) { 4443 C = BI->getCondition(); 4444 4445 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4446 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4447 4448 if (!LeftEdge.isSingleEdge()) 4449 return false; 4450 4451 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4452 4453 Use &LeftUse = Merge->getOperandUse(0); 4454 Use &RightUse = Merge->getOperandUse(1); 4455 4456 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4457 LHS = LeftUse; 4458 RHS = RightUse; 4459 return true; 4460 } 4461 4462 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4463 LHS = RightUse; 4464 RHS = LeftUse; 4465 return true; 4466 } 4467 4468 return false; 4469 } 4470 4471 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4472 auto IsReachable = 4473 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4474 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4475 const Loop *L = LI.getLoopFor(PN->getParent()); 4476 4477 // We don't want to break LCSSA, even in a SCEV expression tree. 4478 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4479 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4480 return nullptr; 4481 4482 // Try to match 4483 // 4484 // br %cond, label %left, label %right 4485 // left: 4486 // br label %merge 4487 // right: 4488 // br label %merge 4489 // merge: 4490 // V = phi [ %x, %left ], [ %y, %right ] 4491 // 4492 // as "select %cond, %x, %y" 4493 4494 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4495 assert(IDom && "At least the entry block should dominate PN"); 4496 4497 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4498 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4499 4500 if (BI && BI->isConditional() && 4501 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4502 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4503 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4504 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4505 } 4506 4507 return nullptr; 4508 } 4509 4510 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4511 if (const SCEV *S = createAddRecFromPHI(PN)) 4512 return S; 4513 4514 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4515 return S; 4516 4517 // If the PHI has a single incoming value, follow that value, unless the 4518 // PHI's incoming blocks are in a different loop, in which case doing so 4519 // risks breaking LCSSA form. Instcombine would normally zap these, but 4520 // it doesn't have DominatorTree information, so it may miss cases. 4521 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 4522 if (LI.replacementPreservesLCSSAForm(PN, V)) 4523 return getSCEV(V); 4524 4525 // If it's not a loop phi, we can't handle it yet. 4526 return getUnknown(PN); 4527 } 4528 4529 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4530 Value *Cond, 4531 Value *TrueVal, 4532 Value *FalseVal) { 4533 // Handle "constant" branch or select. This can occur for instance when a 4534 // loop pass transforms an inner loop and moves on to process the outer loop. 4535 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4536 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4537 4538 // Try to match some simple smax or umax patterns. 4539 auto *ICI = dyn_cast<ICmpInst>(Cond); 4540 if (!ICI) 4541 return getUnknown(I); 4542 4543 Value *LHS = ICI->getOperand(0); 4544 Value *RHS = ICI->getOperand(1); 4545 4546 switch (ICI->getPredicate()) { 4547 case ICmpInst::ICMP_SLT: 4548 case ICmpInst::ICMP_SLE: 4549 std::swap(LHS, RHS); 4550 LLVM_FALLTHROUGH; 4551 case ICmpInst::ICMP_SGT: 4552 case ICmpInst::ICMP_SGE: 4553 // a >s b ? a+x : b+x -> smax(a, b)+x 4554 // a >s b ? b+x : a+x -> smin(a, b)+x 4555 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4556 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4557 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4558 const SCEV *LA = getSCEV(TrueVal); 4559 const SCEV *RA = getSCEV(FalseVal); 4560 const SCEV *LDiff = getMinusSCEV(LA, LS); 4561 const SCEV *RDiff = getMinusSCEV(RA, RS); 4562 if (LDiff == RDiff) 4563 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4564 LDiff = getMinusSCEV(LA, RS); 4565 RDiff = getMinusSCEV(RA, LS); 4566 if (LDiff == RDiff) 4567 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4568 } 4569 break; 4570 case ICmpInst::ICMP_ULT: 4571 case ICmpInst::ICMP_ULE: 4572 std::swap(LHS, RHS); 4573 LLVM_FALLTHROUGH; 4574 case ICmpInst::ICMP_UGT: 4575 case ICmpInst::ICMP_UGE: 4576 // a >u b ? a+x : b+x -> umax(a, b)+x 4577 // a >u b ? b+x : a+x -> umin(a, b)+x 4578 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4579 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4580 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4581 const SCEV *LA = getSCEV(TrueVal); 4582 const SCEV *RA = getSCEV(FalseVal); 4583 const SCEV *LDiff = getMinusSCEV(LA, LS); 4584 const SCEV *RDiff = getMinusSCEV(RA, RS); 4585 if (LDiff == RDiff) 4586 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4587 LDiff = getMinusSCEV(LA, RS); 4588 RDiff = getMinusSCEV(RA, LS); 4589 if (LDiff == RDiff) 4590 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4591 } 4592 break; 4593 case ICmpInst::ICMP_NE: 4594 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4595 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4596 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4597 const SCEV *One = getOne(I->getType()); 4598 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4599 const SCEV *LA = getSCEV(TrueVal); 4600 const SCEV *RA = getSCEV(FalseVal); 4601 const SCEV *LDiff = getMinusSCEV(LA, LS); 4602 const SCEV *RDiff = getMinusSCEV(RA, One); 4603 if (LDiff == RDiff) 4604 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4605 } 4606 break; 4607 case ICmpInst::ICMP_EQ: 4608 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4609 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4610 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4611 const SCEV *One = getOne(I->getType()); 4612 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4613 const SCEV *LA = getSCEV(TrueVal); 4614 const SCEV *RA = getSCEV(FalseVal); 4615 const SCEV *LDiff = getMinusSCEV(LA, One); 4616 const SCEV *RDiff = getMinusSCEV(RA, LS); 4617 if (LDiff == RDiff) 4618 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4619 } 4620 break; 4621 default: 4622 break; 4623 } 4624 4625 return getUnknown(I); 4626 } 4627 4628 /// Expand GEP instructions into add and multiply operations. This allows them 4629 /// to be analyzed by regular SCEV code. 4630 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4631 // Don't attempt to analyze GEPs over unsized objects. 4632 if (!GEP->getSourceElementType()->isSized()) 4633 return getUnknown(GEP); 4634 4635 SmallVector<const SCEV *, 4> IndexExprs; 4636 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4637 IndexExprs.push_back(getSCEV(*Index)); 4638 return getGEPExpr(GEP, IndexExprs); 4639 } 4640 4641 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 4642 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4643 return C->getAPInt().countTrailingZeros(); 4644 4645 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4646 return std::min(GetMinTrailingZeros(T->getOperand()), 4647 (uint32_t)getTypeSizeInBits(T->getType())); 4648 4649 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4650 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4651 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4652 ? getTypeSizeInBits(E->getType()) 4653 : OpRes; 4654 } 4655 4656 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4657 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4658 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4659 ? getTypeSizeInBits(E->getType()) 4660 : OpRes; 4661 } 4662 4663 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4664 // The result is the min of all operands results. 4665 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4666 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4667 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4668 return MinOpRes; 4669 } 4670 4671 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4672 // The result is the sum of all operands results. 4673 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4674 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4675 for (unsigned i = 1, e = M->getNumOperands(); 4676 SumOpRes != BitWidth && i != e; ++i) 4677 SumOpRes = 4678 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 4679 return SumOpRes; 4680 } 4681 4682 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4683 // The result is the min of all operands results. 4684 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4685 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4686 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4687 return MinOpRes; 4688 } 4689 4690 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4691 // The result is the min of all operands results. 4692 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4693 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4694 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4695 return MinOpRes; 4696 } 4697 4698 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4699 // The result is the min of all operands results. 4700 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4701 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4702 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4703 return MinOpRes; 4704 } 4705 4706 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4707 // For a SCEVUnknown, ask ValueTracking. 4708 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 4709 return Known.countMinTrailingZeros(); 4710 } 4711 4712 // SCEVUDivExpr 4713 return 0; 4714 } 4715 4716 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4717 auto I = MinTrailingZerosCache.find(S); 4718 if (I != MinTrailingZerosCache.end()) 4719 return I->second; 4720 4721 uint32_t Result = GetMinTrailingZerosImpl(S); 4722 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 4723 assert(InsertPair.second && "Should insert a new key"); 4724 return InsertPair.first->second; 4725 } 4726 4727 /// Helper method to assign a range to V from metadata present in the IR. 4728 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4729 if (Instruction *I = dyn_cast<Instruction>(V)) 4730 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4731 return getConstantRangeFromMetadata(*MD); 4732 4733 return None; 4734 } 4735 4736 /// Determine the range for a particular SCEV. If SignHint is 4737 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4738 /// with a "cleaner" unsigned (resp. signed) representation. 4739 ConstantRange 4740 ScalarEvolution::getRange(const SCEV *S, 4741 ScalarEvolution::RangeSignHint SignHint) { 4742 DenseMap<const SCEV *, ConstantRange> &Cache = 4743 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4744 : SignedRanges; 4745 4746 // See if we've computed this range already. 4747 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4748 if (I != Cache.end()) 4749 return I->second; 4750 4751 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4752 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4753 4754 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4755 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4756 4757 // If the value has known zeros, the maximum value will have those known zeros 4758 // as well. 4759 uint32_t TZ = GetMinTrailingZeros(S); 4760 if (TZ != 0) { 4761 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4762 ConservativeResult = 4763 ConstantRange(APInt::getMinValue(BitWidth), 4764 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4765 else 4766 ConservativeResult = ConstantRange( 4767 APInt::getSignedMinValue(BitWidth), 4768 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4769 } 4770 4771 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4772 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4773 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4774 X = X.add(getRange(Add->getOperand(i), SignHint)); 4775 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4776 } 4777 4778 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4779 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4780 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4781 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4782 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4783 } 4784 4785 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4786 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4787 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4788 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4789 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4790 } 4791 4792 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4793 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4794 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4795 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4796 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4797 } 4798 4799 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4800 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4801 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4802 return setRange(UDiv, SignHint, 4803 ConservativeResult.intersectWith(X.udiv(Y))); 4804 } 4805 4806 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4807 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4808 return setRange(ZExt, SignHint, 4809 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4810 } 4811 4812 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4813 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4814 return setRange(SExt, SignHint, 4815 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4816 } 4817 4818 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4819 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4820 return setRange(Trunc, SignHint, 4821 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4822 } 4823 4824 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4825 // If there's no unsigned wrap, the value will never be less than its 4826 // initial value. 4827 if (AddRec->hasNoUnsignedWrap()) 4828 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4829 if (!C->getValue()->isZero()) 4830 ConservativeResult = ConservativeResult.intersectWith( 4831 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4832 4833 // If there's no signed wrap, and all the operands have the same sign or 4834 // zero, the value won't ever change sign. 4835 if (AddRec->hasNoSignedWrap()) { 4836 bool AllNonNeg = true; 4837 bool AllNonPos = true; 4838 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4839 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4840 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4841 } 4842 if (AllNonNeg) 4843 ConservativeResult = ConservativeResult.intersectWith( 4844 ConstantRange(APInt(BitWidth, 0), 4845 APInt::getSignedMinValue(BitWidth))); 4846 else if (AllNonPos) 4847 ConservativeResult = ConservativeResult.intersectWith( 4848 ConstantRange(APInt::getSignedMinValue(BitWidth), 4849 APInt(BitWidth, 1))); 4850 } 4851 4852 // TODO: non-affine addrec 4853 if (AddRec->isAffine()) { 4854 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4855 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4856 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4857 auto RangeFromAffine = getRangeForAffineAR( 4858 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4859 BitWidth); 4860 if (!RangeFromAffine.isFullSet()) 4861 ConservativeResult = 4862 ConservativeResult.intersectWith(RangeFromAffine); 4863 4864 auto RangeFromFactoring = getRangeViaFactoring( 4865 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4866 BitWidth); 4867 if (!RangeFromFactoring.isFullSet()) 4868 ConservativeResult = 4869 ConservativeResult.intersectWith(RangeFromFactoring); 4870 } 4871 } 4872 4873 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 4874 } 4875 4876 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4877 // Check if the IR explicitly contains !range metadata. 4878 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4879 if (MDRange.hasValue()) 4880 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4881 4882 // Split here to avoid paying the compile-time cost of calling both 4883 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4884 // if needed. 4885 const DataLayout &DL = getDataLayout(); 4886 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4887 // For a SCEVUnknown, ask ValueTracking. 4888 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4889 if (Known.One != ~Known.Zero + 1) 4890 ConservativeResult = 4891 ConservativeResult.intersectWith(ConstantRange(Known.One, 4892 ~Known.Zero + 1)); 4893 } else { 4894 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4895 "generalize as needed!"); 4896 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4897 if (NS > 1) 4898 ConservativeResult = ConservativeResult.intersectWith( 4899 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4900 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4901 } 4902 4903 return setRange(U, SignHint, std::move(ConservativeResult)); 4904 } 4905 4906 return setRange(S, SignHint, std::move(ConservativeResult)); 4907 } 4908 4909 // Given a StartRange, Step and MaxBECount for an expression compute a range of 4910 // values that the expression can take. Initially, the expression has a value 4911 // from StartRange and then is changed by Step up to MaxBECount times. Signed 4912 // argument defines if we treat Step as signed or unsigned. 4913 static ConstantRange getRangeForAffineARHelper(APInt Step, 4914 const ConstantRange &StartRange, 4915 const APInt &MaxBECount, 4916 unsigned BitWidth, bool Signed) { 4917 // If either Step or MaxBECount is 0, then the expression won't change, and we 4918 // just need to return the initial range. 4919 if (Step == 0 || MaxBECount == 0) 4920 return StartRange; 4921 4922 // If we don't know anything about the initial value (i.e. StartRange is 4923 // FullRange), then we don't know anything about the final range either. 4924 // Return FullRange. 4925 if (StartRange.isFullSet()) 4926 return ConstantRange(BitWidth, /* isFullSet = */ true); 4927 4928 // If Step is signed and negative, then we use its absolute value, but we also 4929 // note that we're moving in the opposite direction. 4930 bool Descending = Signed && Step.isNegative(); 4931 4932 if (Signed) 4933 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 4934 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 4935 // This equations hold true due to the well-defined wrap-around behavior of 4936 // APInt. 4937 Step = Step.abs(); 4938 4939 // Check if Offset is more than full span of BitWidth. If it is, the 4940 // expression is guaranteed to overflow. 4941 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 4942 return ConstantRange(BitWidth, /* isFullSet = */ true); 4943 4944 // Offset is by how much the expression can change. Checks above guarantee no 4945 // overflow here. 4946 APInt Offset = Step * MaxBECount; 4947 4948 // Minimum value of the final range will match the minimal value of StartRange 4949 // if the expression is increasing and will be decreased by Offset otherwise. 4950 // Maximum value of the final range will match the maximal value of StartRange 4951 // if the expression is decreasing and will be increased by Offset otherwise. 4952 APInt StartLower = StartRange.getLower(); 4953 APInt StartUpper = StartRange.getUpper() - 1; 4954 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 4955 : (StartUpper + std::move(Offset)); 4956 4957 // It's possible that the new minimum/maximum value will fall into the initial 4958 // range (due to wrap around). This means that the expression can take any 4959 // value in this bitwidth, and we have to return full range. 4960 if (StartRange.contains(MovedBoundary)) 4961 return ConstantRange(BitWidth, /* isFullSet = */ true); 4962 4963 APInt NewLower = 4964 Descending ? std::move(MovedBoundary) : std::move(StartLower); 4965 APInt NewUpper = 4966 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 4967 NewUpper += 1; 4968 4969 // If we end up with full range, return a proper full range. 4970 if (NewLower == NewUpper) 4971 return ConstantRange(BitWidth, /* isFullSet = */ true); 4972 4973 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 4974 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 4975 } 4976 4977 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4978 const SCEV *Step, 4979 const SCEV *MaxBECount, 4980 unsigned BitWidth) { 4981 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4982 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4983 "Precondition!"); 4984 4985 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4986 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4987 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax(); 4988 4989 // First, consider step signed. 4990 ConstantRange StartSRange = getSignedRange(Start); 4991 ConstantRange StepSRange = getSignedRange(Step); 4992 4993 // If Step can be both positive and negative, we need to find ranges for the 4994 // maximum absolute step values in both directions and union them. 4995 ConstantRange SR = 4996 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 4997 MaxBECountValue, BitWidth, /* Signed = */ true); 4998 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 4999 StartSRange, MaxBECountValue, 5000 BitWidth, /* Signed = */ true)); 5001 5002 // Next, consider step unsigned. 5003 ConstantRange UR = getRangeForAffineARHelper( 5004 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start), 5005 MaxBECountValue, BitWidth, /* Signed = */ false); 5006 5007 // Finally, intersect signed and unsigned ranges. 5008 return SR.intersectWith(UR); 5009 } 5010 5011 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5012 const SCEV *Step, 5013 const SCEV *MaxBECount, 5014 unsigned BitWidth) { 5015 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5016 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5017 5018 struct SelectPattern { 5019 Value *Condition = nullptr; 5020 APInt TrueValue; 5021 APInt FalseValue; 5022 5023 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5024 const SCEV *S) { 5025 Optional<unsigned> CastOp; 5026 APInt Offset(BitWidth, 0); 5027 5028 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5029 "Should be!"); 5030 5031 // Peel off a constant offset: 5032 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5033 // In the future we could consider being smarter here and handle 5034 // {Start+Step,+,Step} too. 5035 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5036 return; 5037 5038 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5039 S = SA->getOperand(1); 5040 } 5041 5042 // Peel off a cast operation 5043 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5044 CastOp = SCast->getSCEVType(); 5045 S = SCast->getOperand(); 5046 } 5047 5048 using namespace llvm::PatternMatch; 5049 5050 auto *SU = dyn_cast<SCEVUnknown>(S); 5051 const APInt *TrueVal, *FalseVal; 5052 if (!SU || 5053 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5054 m_APInt(FalseVal)))) { 5055 Condition = nullptr; 5056 return; 5057 } 5058 5059 TrueValue = *TrueVal; 5060 FalseValue = *FalseVal; 5061 5062 // Re-apply the cast we peeled off earlier 5063 if (CastOp.hasValue()) 5064 switch (*CastOp) { 5065 default: 5066 llvm_unreachable("Unknown SCEV cast type!"); 5067 5068 case scTruncate: 5069 TrueValue = TrueValue.trunc(BitWidth); 5070 FalseValue = FalseValue.trunc(BitWidth); 5071 break; 5072 case scZeroExtend: 5073 TrueValue = TrueValue.zext(BitWidth); 5074 FalseValue = FalseValue.zext(BitWidth); 5075 break; 5076 case scSignExtend: 5077 TrueValue = TrueValue.sext(BitWidth); 5078 FalseValue = FalseValue.sext(BitWidth); 5079 break; 5080 } 5081 5082 // Re-apply the constant offset we peeled off earlier 5083 TrueValue += Offset; 5084 FalseValue += Offset; 5085 } 5086 5087 bool isRecognized() { return Condition != nullptr; } 5088 }; 5089 5090 SelectPattern StartPattern(*this, BitWidth, Start); 5091 if (!StartPattern.isRecognized()) 5092 return ConstantRange(BitWidth, /* isFullSet = */ true); 5093 5094 SelectPattern StepPattern(*this, BitWidth, Step); 5095 if (!StepPattern.isRecognized()) 5096 return ConstantRange(BitWidth, /* isFullSet = */ true); 5097 5098 if (StartPattern.Condition != StepPattern.Condition) { 5099 // We don't handle this case today; but we could, by considering four 5100 // possibilities below instead of two. I'm not sure if there are cases where 5101 // that will help over what getRange already does, though. 5102 return ConstantRange(BitWidth, /* isFullSet = */ true); 5103 } 5104 5105 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5106 // construct arbitrary general SCEV expressions here. This function is called 5107 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5108 // say) can end up caching a suboptimal value. 5109 5110 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5111 // C2352 and C2512 (otherwise it isn't needed). 5112 5113 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5114 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5115 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5116 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5117 5118 ConstantRange TrueRange = 5119 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5120 ConstantRange FalseRange = 5121 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5122 5123 return TrueRange.unionWith(FalseRange); 5124 } 5125 5126 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5127 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5128 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5129 5130 // Return early if there are no flags to propagate to the SCEV. 5131 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5132 if (BinOp->hasNoUnsignedWrap()) 5133 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5134 if (BinOp->hasNoSignedWrap()) 5135 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5136 if (Flags == SCEV::FlagAnyWrap) 5137 return SCEV::FlagAnyWrap; 5138 5139 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5140 } 5141 5142 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5143 // Here we check that I is in the header of the innermost loop containing I, 5144 // since we only deal with instructions in the loop header. The actual loop we 5145 // need to check later will come from an add recurrence, but getting that 5146 // requires computing the SCEV of the operands, which can be expensive. This 5147 // check we can do cheaply to rule out some cases early. 5148 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5149 if (InnermostContainingLoop == nullptr || 5150 InnermostContainingLoop->getHeader() != I->getParent()) 5151 return false; 5152 5153 // Only proceed if we can prove that I does not yield poison. 5154 if (!programUndefinedIfFullPoison(I)) 5155 return false; 5156 5157 // At this point we know that if I is executed, then it does not wrap 5158 // according to at least one of NSW or NUW. If I is not executed, then we do 5159 // not know if the calculation that I represents would wrap. Multiple 5160 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5161 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5162 // derived from other instructions that map to the same SCEV. We cannot make 5163 // that guarantee for cases where I is not executed. So we need to find the 5164 // loop that I is considered in relation to and prove that I is executed for 5165 // every iteration of that loop. That implies that the value that I 5166 // calculates does not wrap anywhere in the loop, so then we can apply the 5167 // flags to the SCEV. 5168 // 5169 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5170 // from different loops, so that we know which loop to prove that I is 5171 // executed in. 5172 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5173 // I could be an extractvalue from a call to an overflow intrinsic. 5174 // TODO: We can do better here in some cases. 5175 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5176 return false; 5177 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5178 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5179 bool AllOtherOpsLoopInvariant = true; 5180 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5181 ++OtherOpIndex) { 5182 if (OtherOpIndex != OpIndex) { 5183 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5184 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5185 AllOtherOpsLoopInvariant = false; 5186 break; 5187 } 5188 } 5189 } 5190 if (AllOtherOpsLoopInvariant && 5191 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5192 return true; 5193 } 5194 } 5195 return false; 5196 } 5197 5198 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5199 // If we know that \c I can never be poison period, then that's enough. 5200 if (isSCEVExprNeverPoison(I)) 5201 return true; 5202 5203 // For an add recurrence specifically, we assume that infinite loops without 5204 // side effects are undefined behavior, and then reason as follows: 5205 // 5206 // If the add recurrence is poison in any iteration, it is poison on all 5207 // future iterations (since incrementing poison yields poison). If the result 5208 // of the add recurrence is fed into the loop latch condition and the loop 5209 // does not contain any throws or exiting blocks other than the latch, we now 5210 // have the ability to "choose" whether the backedge is taken or not (by 5211 // choosing a sufficiently evil value for the poison feeding into the branch) 5212 // for every iteration including and after the one in which \p I first became 5213 // poison. There are two possibilities (let's call the iteration in which \p 5214 // I first became poison as K): 5215 // 5216 // 1. In the set of iterations including and after K, the loop body executes 5217 // no side effects. In this case executing the backege an infinte number 5218 // of times will yield undefined behavior. 5219 // 5220 // 2. In the set of iterations including and after K, the loop body executes 5221 // at least one side effect. In this case, that specific instance of side 5222 // effect is control dependent on poison, which also yields undefined 5223 // behavior. 5224 5225 auto *ExitingBB = L->getExitingBlock(); 5226 auto *LatchBB = L->getLoopLatch(); 5227 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5228 return false; 5229 5230 SmallPtrSet<const Instruction *, 16> Pushed; 5231 SmallVector<const Instruction *, 8> PoisonStack; 5232 5233 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5234 // things that are known to be fully poison under that assumption go on the 5235 // PoisonStack. 5236 Pushed.insert(I); 5237 PoisonStack.push_back(I); 5238 5239 bool LatchControlDependentOnPoison = false; 5240 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5241 const Instruction *Poison = PoisonStack.pop_back_val(); 5242 5243 for (auto *PoisonUser : Poison->users()) { 5244 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5245 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5246 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5247 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5248 assert(BI->isConditional() && "Only possibility!"); 5249 if (BI->getParent() == LatchBB) { 5250 LatchControlDependentOnPoison = true; 5251 break; 5252 } 5253 } 5254 } 5255 } 5256 5257 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5258 } 5259 5260 ScalarEvolution::LoopProperties 5261 ScalarEvolution::getLoopProperties(const Loop *L) { 5262 typedef ScalarEvolution::LoopProperties LoopProperties; 5263 5264 auto Itr = LoopPropertiesCache.find(L); 5265 if (Itr == LoopPropertiesCache.end()) { 5266 auto HasSideEffects = [](Instruction *I) { 5267 if (auto *SI = dyn_cast<StoreInst>(I)) 5268 return !SI->isSimple(); 5269 5270 return I->mayHaveSideEffects(); 5271 }; 5272 5273 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5274 /*HasNoSideEffects*/ true}; 5275 5276 for (auto *BB : L->getBlocks()) 5277 for (auto &I : *BB) { 5278 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5279 LP.HasNoAbnormalExits = false; 5280 if (HasSideEffects(&I)) 5281 LP.HasNoSideEffects = false; 5282 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5283 break; // We're already as pessimistic as we can get. 5284 } 5285 5286 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5287 assert(InsertPair.second && "We just checked!"); 5288 Itr = InsertPair.first; 5289 } 5290 5291 return Itr->second; 5292 } 5293 5294 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5295 if (!isSCEVable(V->getType())) 5296 return getUnknown(V); 5297 5298 if (Instruction *I = dyn_cast<Instruction>(V)) { 5299 // Don't attempt to analyze instructions in blocks that aren't 5300 // reachable. Such instructions don't matter, and they aren't required 5301 // to obey basic rules for definitions dominating uses which this 5302 // analysis depends on. 5303 if (!DT.isReachableFromEntry(I->getParent())) 5304 return getUnknown(V); 5305 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5306 return getConstant(CI); 5307 else if (isa<ConstantPointerNull>(V)) 5308 return getZero(V->getType()); 5309 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5310 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5311 else if (!isa<ConstantExpr>(V)) 5312 return getUnknown(V); 5313 5314 Operator *U = cast<Operator>(V); 5315 if (auto BO = MatchBinaryOp(U, DT)) { 5316 switch (BO->Opcode) { 5317 case Instruction::Add: { 5318 // The simple thing to do would be to just call getSCEV on both operands 5319 // and call getAddExpr with the result. However if we're looking at a 5320 // bunch of things all added together, this can be quite inefficient, 5321 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5322 // Instead, gather up all the operands and make a single getAddExpr call. 5323 // LLVM IR canonical form means we need only traverse the left operands. 5324 SmallVector<const SCEV *, 4> AddOps; 5325 do { 5326 if (BO->Op) { 5327 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5328 AddOps.push_back(OpSCEV); 5329 break; 5330 } 5331 5332 // If a NUW or NSW flag can be applied to the SCEV for this 5333 // addition, then compute the SCEV for this addition by itself 5334 // with a separate call to getAddExpr. We need to do that 5335 // instead of pushing the operands of the addition onto AddOps, 5336 // since the flags are only known to apply to this particular 5337 // addition - they may not apply to other additions that can be 5338 // formed with operands from AddOps. 5339 const SCEV *RHS = getSCEV(BO->RHS); 5340 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5341 if (Flags != SCEV::FlagAnyWrap) { 5342 const SCEV *LHS = getSCEV(BO->LHS); 5343 if (BO->Opcode == Instruction::Sub) 5344 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5345 else 5346 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5347 break; 5348 } 5349 } 5350 5351 if (BO->Opcode == Instruction::Sub) 5352 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5353 else 5354 AddOps.push_back(getSCEV(BO->RHS)); 5355 5356 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5357 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5358 NewBO->Opcode != Instruction::Sub)) { 5359 AddOps.push_back(getSCEV(BO->LHS)); 5360 break; 5361 } 5362 BO = NewBO; 5363 } while (true); 5364 5365 return getAddExpr(AddOps); 5366 } 5367 5368 case Instruction::Mul: { 5369 SmallVector<const SCEV *, 4> MulOps; 5370 do { 5371 if (BO->Op) { 5372 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5373 MulOps.push_back(OpSCEV); 5374 break; 5375 } 5376 5377 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5378 if (Flags != SCEV::FlagAnyWrap) { 5379 MulOps.push_back( 5380 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5381 break; 5382 } 5383 } 5384 5385 MulOps.push_back(getSCEV(BO->RHS)); 5386 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5387 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5388 MulOps.push_back(getSCEV(BO->LHS)); 5389 break; 5390 } 5391 BO = NewBO; 5392 } while (true); 5393 5394 return getMulExpr(MulOps); 5395 } 5396 case Instruction::UDiv: 5397 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5398 case Instruction::Sub: { 5399 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5400 if (BO->Op) 5401 Flags = getNoWrapFlagsFromUB(BO->Op); 5402 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5403 } 5404 case Instruction::And: 5405 // For an expression like x&255 that merely masks off the high bits, 5406 // use zext(trunc(x)) as the SCEV expression. 5407 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5408 if (CI->isNullValue()) 5409 return getSCEV(BO->RHS); 5410 if (CI->isAllOnesValue()) 5411 return getSCEV(BO->LHS); 5412 const APInt &A = CI->getValue(); 5413 5414 // Instcombine's ShrinkDemandedConstant may strip bits out of 5415 // constants, obscuring what would otherwise be a low-bits mask. 5416 // Use computeKnownBits to compute what ShrinkDemandedConstant 5417 // knew about to reconstruct a low-bits mask value. 5418 unsigned LZ = A.countLeadingZeros(); 5419 unsigned TZ = A.countTrailingZeros(); 5420 unsigned BitWidth = A.getBitWidth(); 5421 KnownBits Known(BitWidth); 5422 computeKnownBits(BO->LHS, Known, getDataLayout(), 5423 0, &AC, nullptr, &DT); 5424 5425 APInt EffectiveMask = 5426 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5427 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 5428 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5429 const SCEV *LHS = getSCEV(BO->LHS); 5430 const SCEV *ShiftedLHS = nullptr; 5431 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5432 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5433 // For an expression like (x * 8) & 8, simplify the multiply. 5434 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5435 unsigned GCD = std::min(MulZeros, TZ); 5436 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5437 SmallVector<const SCEV*, 4> MulOps; 5438 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5439 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5440 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5441 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5442 } 5443 } 5444 if (!ShiftedLHS) 5445 ShiftedLHS = getUDivExpr(LHS, MulCount); 5446 return getMulExpr( 5447 getZeroExtendExpr( 5448 getTruncateExpr(ShiftedLHS, 5449 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5450 BO->LHS->getType()), 5451 MulCount); 5452 } 5453 } 5454 break; 5455 5456 case Instruction::Or: 5457 // If the RHS of the Or is a constant, we may have something like: 5458 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5459 // optimizations will transparently handle this case. 5460 // 5461 // In order for this transformation to be safe, the LHS must be of the 5462 // form X*(2^n) and the Or constant must be less than 2^n. 5463 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5464 const SCEV *LHS = getSCEV(BO->LHS); 5465 const APInt &CIVal = CI->getValue(); 5466 if (GetMinTrailingZeros(LHS) >= 5467 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5468 // Build a plain add SCEV. 5469 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5470 // If the LHS of the add was an addrec and it has no-wrap flags, 5471 // transfer the no-wrap flags, since an or won't introduce a wrap. 5472 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5473 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5474 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5475 OldAR->getNoWrapFlags()); 5476 } 5477 return S; 5478 } 5479 } 5480 break; 5481 5482 case Instruction::Xor: 5483 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5484 // If the RHS of xor is -1, then this is a not operation. 5485 if (CI->isAllOnesValue()) 5486 return getNotSCEV(getSCEV(BO->LHS)); 5487 5488 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5489 // This is a variant of the check for xor with -1, and it handles 5490 // the case where instcombine has trimmed non-demanded bits out 5491 // of an xor with -1. 5492 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5493 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5494 if (LBO->getOpcode() == Instruction::And && 5495 LCI->getValue() == CI->getValue()) 5496 if (const SCEVZeroExtendExpr *Z = 5497 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5498 Type *UTy = BO->LHS->getType(); 5499 const SCEV *Z0 = Z->getOperand(); 5500 Type *Z0Ty = Z0->getType(); 5501 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5502 5503 // If C is a low-bits mask, the zero extend is serving to 5504 // mask off the high bits. Complement the operand and 5505 // re-apply the zext. 5506 if (CI->getValue().isMask(Z0TySize)) 5507 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5508 5509 // If C is a single bit, it may be in the sign-bit position 5510 // before the zero-extend. In this case, represent the xor 5511 // using an add, which is equivalent, and re-apply the zext. 5512 APInt Trunc = CI->getValue().trunc(Z0TySize); 5513 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5514 Trunc.isSignMask()) 5515 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5516 UTy); 5517 } 5518 } 5519 break; 5520 5521 case Instruction::Shl: 5522 // Turn shift left of a constant amount into a multiply. 5523 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5524 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5525 5526 // If the shift count is not less than the bitwidth, the result of 5527 // the shift is undefined. Don't try to analyze it, because the 5528 // resolution chosen here may differ from the resolution chosen in 5529 // other parts of the compiler. 5530 if (SA->getValue().uge(BitWidth)) 5531 break; 5532 5533 // It is currently not resolved how to interpret NSW for left 5534 // shift by BitWidth - 1, so we avoid applying flags in that 5535 // case. Remove this check (or this comment) once the situation 5536 // is resolved. See 5537 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5538 // and http://reviews.llvm.org/D8890 . 5539 auto Flags = SCEV::FlagAnyWrap; 5540 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5541 Flags = getNoWrapFlagsFromUB(BO->Op); 5542 5543 Constant *X = ConstantInt::get(getContext(), 5544 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5545 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5546 } 5547 break; 5548 5549 case Instruction::AShr: 5550 // AShr X, C, where C is a constant. 5551 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5552 if (!CI) 5553 break; 5554 5555 Type *OuterTy = BO->LHS->getType(); 5556 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5557 // If the shift count is not less than the bitwidth, the result of 5558 // the shift is undefined. Don't try to analyze it, because the 5559 // resolution chosen here may differ from the resolution chosen in 5560 // other parts of the compiler. 5561 if (CI->getValue().uge(BitWidth)) 5562 break; 5563 5564 if (CI->isNullValue()) 5565 return getSCEV(BO->LHS); // shift by zero --> noop 5566 5567 uint64_t AShrAmt = CI->getZExtValue(); 5568 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5569 5570 Operator *L = dyn_cast<Operator>(BO->LHS); 5571 if (L && L->getOpcode() == Instruction::Shl) { 5572 // X = Shl A, n 5573 // Y = AShr X, m 5574 // Both n and m are constant. 5575 5576 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5577 if (L->getOperand(1) == BO->RHS) 5578 // For a two-shift sext-inreg, i.e. n = m, 5579 // use sext(trunc(x)) as the SCEV expression. 5580 return getSignExtendExpr( 5581 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5582 5583 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5584 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5585 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5586 if (ShlAmt > AShrAmt) { 5587 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5588 // expression. We already checked that ShlAmt < BitWidth, so 5589 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5590 // ShlAmt - AShrAmt < Amt. 5591 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5592 ShlAmt - AShrAmt); 5593 return getSignExtendExpr( 5594 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5595 getConstant(Mul)), OuterTy); 5596 } 5597 } 5598 } 5599 break; 5600 } 5601 } 5602 5603 switch (U->getOpcode()) { 5604 case Instruction::Trunc: 5605 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5606 5607 case Instruction::ZExt: 5608 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5609 5610 case Instruction::SExt: 5611 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5612 5613 case Instruction::BitCast: 5614 // BitCasts are no-op casts so we just eliminate the cast. 5615 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5616 return getSCEV(U->getOperand(0)); 5617 break; 5618 5619 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5620 // lead to pointer expressions which cannot safely be expanded to GEPs, 5621 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5622 // simplifying integer expressions. 5623 5624 case Instruction::GetElementPtr: 5625 return createNodeForGEP(cast<GEPOperator>(U)); 5626 5627 case Instruction::PHI: 5628 return createNodeForPHI(cast<PHINode>(U)); 5629 5630 case Instruction::Select: 5631 // U can also be a select constant expr, which let fall through. Since 5632 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5633 // constant expressions cannot have instructions as operands, we'd have 5634 // returned getUnknown for a select constant expressions anyway. 5635 if (isa<Instruction>(U)) 5636 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5637 U->getOperand(1), U->getOperand(2)); 5638 break; 5639 5640 case Instruction::Call: 5641 case Instruction::Invoke: 5642 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5643 return getSCEV(RV); 5644 break; 5645 } 5646 5647 return getUnknown(V); 5648 } 5649 5650 5651 5652 //===----------------------------------------------------------------------===// 5653 // Iteration Count Computation Code 5654 // 5655 5656 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5657 if (!ExitCount) 5658 return 0; 5659 5660 ConstantInt *ExitConst = ExitCount->getValue(); 5661 5662 // Guard against huge trip counts. 5663 if (ExitConst->getValue().getActiveBits() > 32) 5664 return 0; 5665 5666 // In case of integer overflow, this returns 0, which is correct. 5667 return ((unsigned)ExitConst->getZExtValue()) + 1; 5668 } 5669 5670 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 5671 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5672 return getSmallConstantTripCount(L, ExitingBB); 5673 5674 // No trip count information for multiple exits. 5675 return 0; 5676 } 5677 5678 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 5679 BasicBlock *ExitingBlock) { 5680 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5681 assert(L->isLoopExiting(ExitingBlock) && 5682 "Exiting block must actually branch out of the loop!"); 5683 const SCEVConstant *ExitCount = 5684 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5685 return getConstantTripCount(ExitCount); 5686 } 5687 5688 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 5689 const auto *MaxExitCount = 5690 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5691 return getConstantTripCount(MaxExitCount); 5692 } 5693 5694 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 5695 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5696 return getSmallConstantTripMultiple(L, ExitingBB); 5697 5698 // No trip multiple information for multiple exits. 5699 return 0; 5700 } 5701 5702 /// Returns the largest constant divisor of the trip count of this loop as a 5703 /// normal unsigned value, if possible. This means that the actual trip count is 5704 /// always a multiple of the returned value (don't forget the trip count could 5705 /// very well be zero as well!). 5706 /// 5707 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5708 /// multiple of a constant (which is also the case if the trip count is simply 5709 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5710 /// if the trip count is very large (>= 2^32). 5711 /// 5712 /// As explained in the comments for getSmallConstantTripCount, this assumes 5713 /// that control exits the loop via ExitingBlock. 5714 unsigned 5715 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 5716 BasicBlock *ExitingBlock) { 5717 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5718 assert(L->isLoopExiting(ExitingBlock) && 5719 "Exiting block must actually branch out of the loop!"); 5720 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5721 if (ExitCount == getCouldNotCompute()) 5722 return 1; 5723 5724 // Get the trip count from the BE count by adding 1. 5725 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5726 5727 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 5728 if (!TC) 5729 // Attempt to factor more general cases. Returns the greatest power of 5730 // two divisor. If overflow happens, the trip count expression is still 5731 // divisible by the greatest power of 2 divisor returned. 5732 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 5733 5734 ConstantInt *Result = TC->getValue(); 5735 5736 // Guard against huge trip counts (this requires checking 5737 // for zero to handle the case where the trip count == -1 and the 5738 // addition wraps). 5739 if (!Result || Result->getValue().getActiveBits() > 32 || 5740 Result->getValue().getActiveBits() == 0) 5741 return 1; 5742 5743 return (unsigned)Result->getZExtValue(); 5744 } 5745 5746 /// Get the expression for the number of loop iterations for which this loop is 5747 /// guaranteed not to exit via ExitingBlock. Otherwise return 5748 /// SCEVCouldNotCompute. 5749 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 5750 BasicBlock *ExitingBlock) { 5751 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5752 } 5753 5754 const SCEV * 5755 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5756 SCEVUnionPredicate &Preds) { 5757 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5758 } 5759 5760 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5761 return getBackedgeTakenInfo(L).getExact(this); 5762 } 5763 5764 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5765 /// known never to be less than the actual backedge taken count. 5766 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5767 return getBackedgeTakenInfo(L).getMax(this); 5768 } 5769 5770 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5771 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5772 } 5773 5774 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5775 static void 5776 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5777 BasicBlock *Header = L->getHeader(); 5778 5779 // Push all Loop-header PHIs onto the Worklist stack. 5780 for (BasicBlock::iterator I = Header->begin(); 5781 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5782 Worklist.push_back(PN); 5783 } 5784 5785 const ScalarEvolution::BackedgeTakenInfo & 5786 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5787 auto &BTI = getBackedgeTakenInfo(L); 5788 if (BTI.hasFullInfo()) 5789 return BTI; 5790 5791 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5792 5793 if (!Pair.second) 5794 return Pair.first->second; 5795 5796 BackedgeTakenInfo Result = 5797 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5798 5799 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5800 } 5801 5802 const ScalarEvolution::BackedgeTakenInfo & 5803 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5804 // Initially insert an invalid entry for this loop. If the insertion 5805 // succeeds, proceed to actually compute a backedge-taken count and 5806 // update the value. The temporary CouldNotCompute value tells SCEV 5807 // code elsewhere that it shouldn't attempt to request a new 5808 // backedge-taken count, which could result in infinite recursion. 5809 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5810 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5811 if (!Pair.second) 5812 return Pair.first->second; 5813 5814 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5815 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5816 // must be cleared in this scope. 5817 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5818 5819 if (Result.getExact(this) != getCouldNotCompute()) { 5820 assert(isLoopInvariant(Result.getExact(this), L) && 5821 isLoopInvariant(Result.getMax(this), L) && 5822 "Computed backedge-taken count isn't loop invariant for loop!"); 5823 ++NumTripCountsComputed; 5824 } 5825 else if (Result.getMax(this) == getCouldNotCompute() && 5826 isa<PHINode>(L->getHeader()->begin())) { 5827 // Only count loops that have phi nodes as not being computable. 5828 ++NumTripCountsNotComputed; 5829 } 5830 5831 // Now that we know more about the trip count for this loop, forget any 5832 // existing SCEV values for PHI nodes in this loop since they are only 5833 // conservative estimates made without the benefit of trip count 5834 // information. This is similar to the code in forgetLoop, except that 5835 // it handles SCEVUnknown PHI nodes specially. 5836 if (Result.hasAnyInfo()) { 5837 SmallVector<Instruction *, 16> Worklist; 5838 PushLoopPHIs(L, Worklist); 5839 5840 SmallPtrSet<Instruction *, 8> Visited; 5841 while (!Worklist.empty()) { 5842 Instruction *I = Worklist.pop_back_val(); 5843 if (!Visited.insert(I).second) 5844 continue; 5845 5846 ValueExprMapType::iterator It = 5847 ValueExprMap.find_as(static_cast<Value *>(I)); 5848 if (It != ValueExprMap.end()) { 5849 const SCEV *Old = It->second; 5850 5851 // SCEVUnknown for a PHI either means that it has an unrecognized 5852 // structure, or it's a PHI that's in the progress of being computed 5853 // by createNodeForPHI. In the former case, additional loop trip 5854 // count information isn't going to change anything. In the later 5855 // case, createNodeForPHI will perform the necessary updates on its 5856 // own when it gets to that point. 5857 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5858 eraseValueFromMap(It->first); 5859 forgetMemoizedResults(Old); 5860 } 5861 if (PHINode *PN = dyn_cast<PHINode>(I)) 5862 ConstantEvolutionLoopExitValue.erase(PN); 5863 } 5864 5865 PushDefUseChildren(I, Worklist); 5866 } 5867 } 5868 5869 // Re-lookup the insert position, since the call to 5870 // computeBackedgeTakenCount above could result in a 5871 // recusive call to getBackedgeTakenInfo (on a different 5872 // loop), which would invalidate the iterator computed 5873 // earlier. 5874 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5875 } 5876 5877 void ScalarEvolution::forgetLoop(const Loop *L) { 5878 // Drop any stored trip count value. 5879 auto RemoveLoopFromBackedgeMap = 5880 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5881 auto BTCPos = Map.find(L); 5882 if (BTCPos != Map.end()) { 5883 BTCPos->second.clear(); 5884 Map.erase(BTCPos); 5885 } 5886 }; 5887 5888 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5889 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5890 5891 // Drop information about expressions based on loop-header PHIs. 5892 SmallVector<Instruction *, 16> Worklist; 5893 PushLoopPHIs(L, Worklist); 5894 5895 SmallPtrSet<Instruction *, 8> Visited; 5896 while (!Worklist.empty()) { 5897 Instruction *I = Worklist.pop_back_val(); 5898 if (!Visited.insert(I).second) 5899 continue; 5900 5901 ValueExprMapType::iterator It = 5902 ValueExprMap.find_as(static_cast<Value *>(I)); 5903 if (It != ValueExprMap.end()) { 5904 eraseValueFromMap(It->first); 5905 forgetMemoizedResults(It->second); 5906 if (PHINode *PN = dyn_cast<PHINode>(I)) 5907 ConstantEvolutionLoopExitValue.erase(PN); 5908 } 5909 5910 PushDefUseChildren(I, Worklist); 5911 } 5912 5913 // Forget all contained loops too, to avoid dangling entries in the 5914 // ValuesAtScopes map. 5915 for (Loop *I : *L) 5916 forgetLoop(I); 5917 5918 LoopPropertiesCache.erase(L); 5919 } 5920 5921 void ScalarEvolution::forgetValue(Value *V) { 5922 Instruction *I = dyn_cast<Instruction>(V); 5923 if (!I) return; 5924 5925 // Drop information about expressions based on loop-header PHIs. 5926 SmallVector<Instruction *, 16> Worklist; 5927 Worklist.push_back(I); 5928 5929 SmallPtrSet<Instruction *, 8> Visited; 5930 while (!Worklist.empty()) { 5931 I = Worklist.pop_back_val(); 5932 if (!Visited.insert(I).second) 5933 continue; 5934 5935 ValueExprMapType::iterator It = 5936 ValueExprMap.find_as(static_cast<Value *>(I)); 5937 if (It != ValueExprMap.end()) { 5938 eraseValueFromMap(It->first); 5939 forgetMemoizedResults(It->second); 5940 if (PHINode *PN = dyn_cast<PHINode>(I)) 5941 ConstantEvolutionLoopExitValue.erase(PN); 5942 } 5943 5944 PushDefUseChildren(I, Worklist); 5945 } 5946 } 5947 5948 /// Get the exact loop backedge taken count considering all loop exits. A 5949 /// computable result can only be returned for loops with a single exit. 5950 /// Returning the minimum taken count among all exits is incorrect because one 5951 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5952 /// the limit of each loop test is never skipped. This is a valid assumption as 5953 /// long as the loop exits via that test. For precise results, it is the 5954 /// caller's responsibility to specify the relevant loop exit using 5955 /// getExact(ExitingBlock, SE). 5956 const SCEV * 5957 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5958 SCEVUnionPredicate *Preds) const { 5959 // If any exits were not computable, the loop is not computable. 5960 if (!isComplete() || ExitNotTaken.empty()) 5961 return SE->getCouldNotCompute(); 5962 5963 const SCEV *BECount = nullptr; 5964 for (auto &ENT : ExitNotTaken) { 5965 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5966 5967 if (!BECount) 5968 BECount = ENT.ExactNotTaken; 5969 else if (BECount != ENT.ExactNotTaken) 5970 return SE->getCouldNotCompute(); 5971 if (Preds && !ENT.hasAlwaysTruePredicate()) 5972 Preds->add(ENT.Predicate.get()); 5973 5974 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5975 "Predicate should be always true!"); 5976 } 5977 5978 assert(BECount && "Invalid not taken count for loop exit"); 5979 return BECount; 5980 } 5981 5982 /// Get the exact not taken count for this loop exit. 5983 const SCEV * 5984 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5985 ScalarEvolution *SE) const { 5986 for (auto &ENT : ExitNotTaken) 5987 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5988 return ENT.ExactNotTaken; 5989 5990 return SE->getCouldNotCompute(); 5991 } 5992 5993 /// getMax - Get the max backedge taken count for the loop. 5994 const SCEV * 5995 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5996 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5997 return !ENT.hasAlwaysTruePredicate(); 5998 }; 5999 6000 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6001 return SE->getCouldNotCompute(); 6002 6003 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6004 "No point in having a non-constant max backedge taken count!"); 6005 return getMax(); 6006 } 6007 6008 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6009 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6010 return !ENT.hasAlwaysTruePredicate(); 6011 }; 6012 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6013 } 6014 6015 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6016 ScalarEvolution *SE) const { 6017 if (getMax() && getMax() != SE->getCouldNotCompute() && 6018 SE->hasOperand(getMax(), S)) 6019 return true; 6020 6021 for (auto &ENT : ExitNotTaken) 6022 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6023 SE->hasOperand(ENT.ExactNotTaken, S)) 6024 return true; 6025 6026 return false; 6027 } 6028 6029 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6030 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) { 6031 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6032 isa<SCEVConstant>(MaxNotTaken)) && 6033 "No point in having a non-constant max backedge taken count!"); 6034 } 6035 6036 ScalarEvolution::ExitLimit::ExitLimit( 6037 const SCEV *E, const SCEV *M, bool MaxOrZero, 6038 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6039 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6040 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6041 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6042 "Exact is not allowed to be less precise than Max"); 6043 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6044 isa<SCEVConstant>(MaxNotTaken)) && 6045 "No point in having a non-constant max backedge taken count!"); 6046 for (auto *PredSet : PredSetList) 6047 for (auto *P : *PredSet) 6048 addPredicate(P); 6049 } 6050 6051 ScalarEvolution::ExitLimit::ExitLimit( 6052 const SCEV *E, const SCEV *M, bool MaxOrZero, 6053 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6054 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6055 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6056 isa<SCEVConstant>(MaxNotTaken)) && 6057 "No point in having a non-constant max backedge taken count!"); 6058 } 6059 6060 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6061 bool MaxOrZero) 6062 : ExitLimit(E, M, MaxOrZero, None) { 6063 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6064 isa<SCEVConstant>(MaxNotTaken)) && 6065 "No point in having a non-constant max backedge taken count!"); 6066 } 6067 6068 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6069 /// computable exit into a persistent ExitNotTakenInfo array. 6070 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6071 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6072 &&ExitCounts, 6073 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6074 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6075 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 6076 ExitNotTaken.reserve(ExitCounts.size()); 6077 std::transform( 6078 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6079 [&](const EdgeExitInfo &EEI) { 6080 BasicBlock *ExitBB = EEI.first; 6081 const ExitLimit &EL = EEI.second; 6082 if (EL.Predicates.empty()) 6083 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6084 6085 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6086 for (auto *Pred : EL.Predicates) 6087 Predicate->add(Pred); 6088 6089 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6090 }); 6091 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6092 "No point in having a non-constant max backedge taken count!"); 6093 } 6094 6095 /// Invalidate this result and free the ExitNotTakenInfo array. 6096 void ScalarEvolution::BackedgeTakenInfo::clear() { 6097 ExitNotTaken.clear(); 6098 } 6099 6100 /// Compute the number of times the backedge of the specified loop will execute. 6101 ScalarEvolution::BackedgeTakenInfo 6102 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6103 bool AllowPredicates) { 6104 SmallVector<BasicBlock *, 8> ExitingBlocks; 6105 L->getExitingBlocks(ExitingBlocks); 6106 6107 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 6108 6109 SmallVector<EdgeExitInfo, 4> ExitCounts; 6110 bool CouldComputeBECount = true; 6111 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6112 const SCEV *MustExitMaxBECount = nullptr; 6113 const SCEV *MayExitMaxBECount = nullptr; 6114 bool MustExitMaxOrZero = false; 6115 6116 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6117 // and compute maxBECount. 6118 // Do a union of all the predicates here. 6119 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6120 BasicBlock *ExitBB = ExitingBlocks[i]; 6121 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6122 6123 assert((AllowPredicates || EL.Predicates.empty()) && 6124 "Predicated exit limit when predicates are not allowed!"); 6125 6126 // 1. For each exit that can be computed, add an entry to ExitCounts. 6127 // CouldComputeBECount is true only if all exits can be computed. 6128 if (EL.ExactNotTaken == getCouldNotCompute()) 6129 // We couldn't compute an exact value for this exit, so 6130 // we won't be able to compute an exact value for the loop. 6131 CouldComputeBECount = false; 6132 else 6133 ExitCounts.emplace_back(ExitBB, EL); 6134 6135 // 2. Derive the loop's MaxBECount from each exit's max number of 6136 // non-exiting iterations. Partition the loop exits into two kinds: 6137 // LoopMustExits and LoopMayExits. 6138 // 6139 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6140 // is a LoopMayExit. If any computable LoopMustExit is found, then 6141 // MaxBECount is the minimum EL.MaxNotTaken of computable 6142 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6143 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6144 // computable EL.MaxNotTaken. 6145 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6146 DT.dominates(ExitBB, Latch)) { 6147 if (!MustExitMaxBECount) { 6148 MustExitMaxBECount = EL.MaxNotTaken; 6149 MustExitMaxOrZero = EL.MaxOrZero; 6150 } else { 6151 MustExitMaxBECount = 6152 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6153 } 6154 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6155 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6156 MayExitMaxBECount = EL.MaxNotTaken; 6157 else { 6158 MayExitMaxBECount = 6159 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6160 } 6161 } 6162 } 6163 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6164 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6165 // The loop backedge will be taken the maximum or zero times if there's 6166 // a single exit that must be taken the maximum or zero times. 6167 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6168 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6169 MaxBECount, MaxOrZero); 6170 } 6171 6172 ScalarEvolution::ExitLimit 6173 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6174 bool AllowPredicates) { 6175 6176 // Okay, we've chosen an exiting block. See what condition causes us to exit 6177 // at this block and remember the exit block and whether all other targets 6178 // lead to the loop header. 6179 bool MustExecuteLoopHeader = true; 6180 BasicBlock *Exit = nullptr; 6181 for (auto *SBB : successors(ExitingBlock)) 6182 if (!L->contains(SBB)) { 6183 if (Exit) // Multiple exit successors. 6184 return getCouldNotCompute(); 6185 Exit = SBB; 6186 } else if (SBB != L->getHeader()) { 6187 MustExecuteLoopHeader = false; 6188 } 6189 6190 // At this point, we know we have a conditional branch that determines whether 6191 // the loop is exited. However, we don't know if the branch is executed each 6192 // time through the loop. If not, then the execution count of the branch will 6193 // not be equal to the trip count of the loop. 6194 // 6195 // Currently we check for this by checking to see if the Exit branch goes to 6196 // the loop header. If so, we know it will always execute the same number of 6197 // times as the loop. We also handle the case where the exit block *is* the 6198 // loop header. This is common for un-rotated loops. 6199 // 6200 // If both of those tests fail, walk up the unique predecessor chain to the 6201 // header, stopping if there is an edge that doesn't exit the loop. If the 6202 // header is reached, the execution count of the branch will be equal to the 6203 // trip count of the loop. 6204 // 6205 // More extensive analysis could be done to handle more cases here. 6206 // 6207 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6208 // The simple checks failed, try climbing the unique predecessor chain 6209 // up to the header. 6210 bool Ok = false; 6211 for (BasicBlock *BB = ExitingBlock; BB; ) { 6212 BasicBlock *Pred = BB->getUniquePredecessor(); 6213 if (!Pred) 6214 return getCouldNotCompute(); 6215 TerminatorInst *PredTerm = Pred->getTerminator(); 6216 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6217 if (PredSucc == BB) 6218 continue; 6219 // If the predecessor has a successor that isn't BB and isn't 6220 // outside the loop, assume the worst. 6221 if (L->contains(PredSucc)) 6222 return getCouldNotCompute(); 6223 } 6224 if (Pred == L->getHeader()) { 6225 Ok = true; 6226 break; 6227 } 6228 BB = Pred; 6229 } 6230 if (!Ok) 6231 return getCouldNotCompute(); 6232 } 6233 6234 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6235 TerminatorInst *Term = ExitingBlock->getTerminator(); 6236 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6237 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6238 // Proceed to the next level to examine the exit condition expression. 6239 return computeExitLimitFromCond( 6240 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6241 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6242 } 6243 6244 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6245 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6246 /*ControlsExit=*/IsOnlyExit); 6247 6248 return getCouldNotCompute(); 6249 } 6250 6251 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6252 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6253 bool ControlsExit, bool AllowPredicates) { 6254 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6255 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6256 ControlsExit, AllowPredicates); 6257 } 6258 6259 Optional<ScalarEvolution::ExitLimit> 6260 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6261 BasicBlock *TBB, BasicBlock *FBB, 6262 bool ControlsExit, bool AllowPredicates) { 6263 (void)this->L; 6264 (void)this->TBB; 6265 (void)this->FBB; 6266 (void)this->AllowPredicates; 6267 6268 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6269 this->AllowPredicates == AllowPredicates && 6270 "Variance in assumed invariant key components!"); 6271 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6272 if (Itr == TripCountMap.end()) 6273 return None; 6274 return Itr->second; 6275 } 6276 6277 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6278 BasicBlock *TBB, BasicBlock *FBB, 6279 bool ControlsExit, 6280 bool AllowPredicates, 6281 const ExitLimit &EL) { 6282 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6283 this->AllowPredicates == AllowPredicates && 6284 "Variance in assumed invariant key components!"); 6285 6286 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6287 assert(InsertResult.second && "Expected successful insertion!"); 6288 (void)InsertResult; 6289 } 6290 6291 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6292 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6293 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6294 6295 if (auto MaybeEL = 6296 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6297 return *MaybeEL; 6298 6299 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6300 ControlsExit, AllowPredicates); 6301 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6302 return EL; 6303 } 6304 6305 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6306 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6307 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6308 // Check if the controlling expression for this loop is an And or Or. 6309 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6310 if (BO->getOpcode() == Instruction::And) { 6311 // Recurse on the operands of the and. 6312 bool EitherMayExit = L->contains(TBB); 6313 ExitLimit EL0 = computeExitLimitFromCondCached( 6314 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6315 AllowPredicates); 6316 ExitLimit EL1 = computeExitLimitFromCondCached( 6317 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6318 AllowPredicates); 6319 const SCEV *BECount = getCouldNotCompute(); 6320 const SCEV *MaxBECount = getCouldNotCompute(); 6321 if (EitherMayExit) { 6322 // Both conditions must be true for the loop to continue executing. 6323 // Choose the less conservative count. 6324 if (EL0.ExactNotTaken == getCouldNotCompute() || 6325 EL1.ExactNotTaken == getCouldNotCompute()) 6326 BECount = getCouldNotCompute(); 6327 else 6328 BECount = 6329 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6330 if (EL0.MaxNotTaken == getCouldNotCompute()) 6331 MaxBECount = EL1.MaxNotTaken; 6332 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6333 MaxBECount = EL0.MaxNotTaken; 6334 else 6335 MaxBECount = 6336 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6337 } else { 6338 // Both conditions must be true at the same time for the loop to exit. 6339 // For now, be conservative. 6340 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6341 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6342 MaxBECount = EL0.MaxNotTaken; 6343 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6344 BECount = EL0.ExactNotTaken; 6345 } 6346 6347 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6348 // to be more aggressive when computing BECount than when computing 6349 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6350 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6351 // to not. 6352 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6353 !isa<SCEVCouldNotCompute>(BECount)) 6354 MaxBECount = getConstant(getUnsignedRange(BECount).getUnsignedMax()); 6355 6356 return ExitLimit(BECount, MaxBECount, false, 6357 {&EL0.Predicates, &EL1.Predicates}); 6358 } 6359 if (BO->getOpcode() == Instruction::Or) { 6360 // Recurse on the operands of the or. 6361 bool EitherMayExit = L->contains(FBB); 6362 ExitLimit EL0 = computeExitLimitFromCondCached( 6363 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6364 AllowPredicates); 6365 ExitLimit EL1 = computeExitLimitFromCondCached( 6366 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6367 AllowPredicates); 6368 const SCEV *BECount = getCouldNotCompute(); 6369 const SCEV *MaxBECount = getCouldNotCompute(); 6370 if (EitherMayExit) { 6371 // Both conditions must be false for the loop to continue executing. 6372 // Choose the less conservative count. 6373 if (EL0.ExactNotTaken == getCouldNotCompute() || 6374 EL1.ExactNotTaken == getCouldNotCompute()) 6375 BECount = getCouldNotCompute(); 6376 else 6377 BECount = 6378 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6379 if (EL0.MaxNotTaken == getCouldNotCompute()) 6380 MaxBECount = EL1.MaxNotTaken; 6381 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6382 MaxBECount = EL0.MaxNotTaken; 6383 else 6384 MaxBECount = 6385 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6386 } else { 6387 // Both conditions must be false at the same time for the loop to exit. 6388 // For now, be conservative. 6389 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6390 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6391 MaxBECount = EL0.MaxNotTaken; 6392 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6393 BECount = EL0.ExactNotTaken; 6394 } 6395 6396 return ExitLimit(BECount, MaxBECount, false, 6397 {&EL0.Predicates, &EL1.Predicates}); 6398 } 6399 } 6400 6401 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6402 // Proceed to the next level to examine the icmp. 6403 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6404 ExitLimit EL = 6405 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6406 if (EL.hasFullInfo() || !AllowPredicates) 6407 return EL; 6408 6409 // Try again, but use SCEV predicates this time. 6410 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6411 /*AllowPredicates=*/true); 6412 } 6413 6414 // Check for a constant condition. These are normally stripped out by 6415 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6416 // preserve the CFG and is temporarily leaving constant conditions 6417 // in place. 6418 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6419 if (L->contains(FBB) == !CI->getZExtValue()) 6420 // The backedge is always taken. 6421 return getCouldNotCompute(); 6422 else 6423 // The backedge is never taken. 6424 return getZero(CI->getType()); 6425 } 6426 6427 // If it's not an integer or pointer comparison then compute it the hard way. 6428 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6429 } 6430 6431 ScalarEvolution::ExitLimit 6432 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6433 ICmpInst *ExitCond, 6434 BasicBlock *TBB, 6435 BasicBlock *FBB, 6436 bool ControlsExit, 6437 bool AllowPredicates) { 6438 6439 // If the condition was exit on true, convert the condition to exit on false 6440 ICmpInst::Predicate Cond; 6441 if (!L->contains(FBB)) 6442 Cond = ExitCond->getPredicate(); 6443 else 6444 Cond = ExitCond->getInversePredicate(); 6445 6446 // Handle common loops like: for (X = "string"; *X; ++X) 6447 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6448 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6449 ExitLimit ItCnt = 6450 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6451 if (ItCnt.hasAnyInfo()) 6452 return ItCnt; 6453 } 6454 6455 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6456 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6457 6458 // Try to evaluate any dependencies out of the loop. 6459 LHS = getSCEVAtScope(LHS, L); 6460 RHS = getSCEVAtScope(RHS, L); 6461 6462 // At this point, we would like to compute how many iterations of the 6463 // loop the predicate will return true for these inputs. 6464 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6465 // If there is a loop-invariant, force it into the RHS. 6466 std::swap(LHS, RHS); 6467 Cond = ICmpInst::getSwappedPredicate(Cond); 6468 } 6469 6470 // Simplify the operands before analyzing them. 6471 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6472 6473 // If we have a comparison of a chrec against a constant, try to use value 6474 // ranges to answer this query. 6475 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6476 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6477 if (AddRec->getLoop() == L) { 6478 // Form the constant range. 6479 ConstantRange CompRange = 6480 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6481 6482 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6483 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6484 } 6485 6486 switch (Cond) { 6487 case ICmpInst::ICMP_NE: { // while (X != Y) 6488 // Convert to: while (X-Y != 0) 6489 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6490 AllowPredicates); 6491 if (EL.hasAnyInfo()) return EL; 6492 break; 6493 } 6494 case ICmpInst::ICMP_EQ: { // while (X == Y) 6495 // Convert to: while (X-Y == 0) 6496 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6497 if (EL.hasAnyInfo()) return EL; 6498 break; 6499 } 6500 case ICmpInst::ICMP_SLT: 6501 case ICmpInst::ICMP_ULT: { // while (X < Y) 6502 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6503 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6504 AllowPredicates); 6505 if (EL.hasAnyInfo()) return EL; 6506 break; 6507 } 6508 case ICmpInst::ICMP_SGT: 6509 case ICmpInst::ICMP_UGT: { // while (X > Y) 6510 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6511 ExitLimit EL = 6512 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6513 AllowPredicates); 6514 if (EL.hasAnyInfo()) return EL; 6515 break; 6516 } 6517 default: 6518 break; 6519 } 6520 6521 auto *ExhaustiveCount = 6522 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6523 6524 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6525 return ExhaustiveCount; 6526 6527 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6528 ExitCond->getOperand(1), L, Cond); 6529 } 6530 6531 ScalarEvolution::ExitLimit 6532 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6533 SwitchInst *Switch, 6534 BasicBlock *ExitingBlock, 6535 bool ControlsExit) { 6536 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6537 6538 // Give up if the exit is the default dest of a switch. 6539 if (Switch->getDefaultDest() == ExitingBlock) 6540 return getCouldNotCompute(); 6541 6542 assert(L->contains(Switch->getDefaultDest()) && 6543 "Default case must not exit the loop!"); 6544 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6545 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6546 6547 // while (X != Y) --> while (X-Y != 0) 6548 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6549 if (EL.hasAnyInfo()) 6550 return EL; 6551 6552 return getCouldNotCompute(); 6553 } 6554 6555 static ConstantInt * 6556 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6557 ScalarEvolution &SE) { 6558 const SCEV *InVal = SE.getConstant(C); 6559 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6560 assert(isa<SCEVConstant>(Val) && 6561 "Evaluation of SCEV at constant didn't fold correctly?"); 6562 return cast<SCEVConstant>(Val)->getValue(); 6563 } 6564 6565 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6566 /// compute the backedge execution count. 6567 ScalarEvolution::ExitLimit 6568 ScalarEvolution::computeLoadConstantCompareExitLimit( 6569 LoadInst *LI, 6570 Constant *RHS, 6571 const Loop *L, 6572 ICmpInst::Predicate predicate) { 6573 6574 if (LI->isVolatile()) return getCouldNotCompute(); 6575 6576 // Check to see if the loaded pointer is a getelementptr of a global. 6577 // TODO: Use SCEV instead of manually grubbing with GEPs. 6578 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6579 if (!GEP) return getCouldNotCompute(); 6580 6581 // Make sure that it is really a constant global we are gepping, with an 6582 // initializer, and make sure the first IDX is really 0. 6583 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6584 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6585 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6586 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6587 return getCouldNotCompute(); 6588 6589 // Okay, we allow one non-constant index into the GEP instruction. 6590 Value *VarIdx = nullptr; 6591 std::vector<Constant*> Indexes; 6592 unsigned VarIdxNum = 0; 6593 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6594 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6595 Indexes.push_back(CI); 6596 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6597 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6598 VarIdx = GEP->getOperand(i); 6599 VarIdxNum = i-2; 6600 Indexes.push_back(nullptr); 6601 } 6602 6603 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6604 if (!VarIdx) 6605 return getCouldNotCompute(); 6606 6607 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6608 // Check to see if X is a loop variant variable value now. 6609 const SCEV *Idx = getSCEV(VarIdx); 6610 Idx = getSCEVAtScope(Idx, L); 6611 6612 // We can only recognize very limited forms of loop index expressions, in 6613 // particular, only affine AddRec's like {C1,+,C2}. 6614 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6615 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6616 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6617 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6618 return getCouldNotCompute(); 6619 6620 unsigned MaxSteps = MaxBruteForceIterations; 6621 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6622 ConstantInt *ItCst = ConstantInt::get( 6623 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6624 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6625 6626 // Form the GEP offset. 6627 Indexes[VarIdxNum] = Val; 6628 6629 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6630 Indexes); 6631 if (!Result) break; // Cannot compute! 6632 6633 // Evaluate the condition for this iteration. 6634 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6635 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6636 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6637 ++NumArrayLenItCounts; 6638 return getConstant(ItCst); // Found terminating iteration! 6639 } 6640 } 6641 return getCouldNotCompute(); 6642 } 6643 6644 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6645 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6646 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6647 if (!RHS) 6648 return getCouldNotCompute(); 6649 6650 const BasicBlock *Latch = L->getLoopLatch(); 6651 if (!Latch) 6652 return getCouldNotCompute(); 6653 6654 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6655 if (!Predecessor) 6656 return getCouldNotCompute(); 6657 6658 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6659 // Return LHS in OutLHS and shift_opt in OutOpCode. 6660 auto MatchPositiveShift = 6661 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6662 6663 using namespace PatternMatch; 6664 6665 ConstantInt *ShiftAmt; 6666 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6667 OutOpCode = Instruction::LShr; 6668 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6669 OutOpCode = Instruction::AShr; 6670 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6671 OutOpCode = Instruction::Shl; 6672 else 6673 return false; 6674 6675 return ShiftAmt->getValue().isStrictlyPositive(); 6676 }; 6677 6678 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6679 // 6680 // loop: 6681 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6682 // %iv.shifted = lshr i32 %iv, <positive constant> 6683 // 6684 // Return true on a successful match. Return the corresponding PHI node (%iv 6685 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6686 auto MatchShiftRecurrence = 6687 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6688 Optional<Instruction::BinaryOps> PostShiftOpCode; 6689 6690 { 6691 Instruction::BinaryOps OpC; 6692 Value *V; 6693 6694 // If we encounter a shift instruction, "peel off" the shift operation, 6695 // and remember that we did so. Later when we inspect %iv's backedge 6696 // value, we will make sure that the backedge value uses the same 6697 // operation. 6698 // 6699 // Note: the peeled shift operation does not have to be the same 6700 // instruction as the one feeding into the PHI's backedge value. We only 6701 // really care about it being the same *kind* of shift instruction -- 6702 // that's all that is required for our later inferences to hold. 6703 if (MatchPositiveShift(LHS, V, OpC)) { 6704 PostShiftOpCode = OpC; 6705 LHS = V; 6706 } 6707 } 6708 6709 PNOut = dyn_cast<PHINode>(LHS); 6710 if (!PNOut || PNOut->getParent() != L->getHeader()) 6711 return false; 6712 6713 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6714 Value *OpLHS; 6715 6716 return 6717 // The backedge value for the PHI node must be a shift by a positive 6718 // amount 6719 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6720 6721 // of the PHI node itself 6722 OpLHS == PNOut && 6723 6724 // and the kind of shift should be match the kind of shift we peeled 6725 // off, if any. 6726 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6727 }; 6728 6729 PHINode *PN; 6730 Instruction::BinaryOps OpCode; 6731 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6732 return getCouldNotCompute(); 6733 6734 const DataLayout &DL = getDataLayout(); 6735 6736 // The key rationale for this optimization is that for some kinds of shift 6737 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6738 // within a finite number of iterations. If the condition guarding the 6739 // backedge (in the sense that the backedge is taken if the condition is true) 6740 // is false for the value the shift recurrence stabilizes to, then we know 6741 // that the backedge is taken only a finite number of times. 6742 6743 ConstantInt *StableValue = nullptr; 6744 switch (OpCode) { 6745 default: 6746 llvm_unreachable("Impossible case!"); 6747 6748 case Instruction::AShr: { 6749 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6750 // bitwidth(K) iterations. 6751 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6752 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 6753 Predecessor->getTerminator(), &DT); 6754 auto *Ty = cast<IntegerType>(RHS->getType()); 6755 if (Known.isNonNegative()) 6756 StableValue = ConstantInt::get(Ty, 0); 6757 else if (Known.isNegative()) 6758 StableValue = ConstantInt::get(Ty, -1, true); 6759 else 6760 return getCouldNotCompute(); 6761 6762 break; 6763 } 6764 case Instruction::LShr: 6765 case Instruction::Shl: 6766 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6767 // stabilize to 0 in at most bitwidth(K) iterations. 6768 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6769 break; 6770 } 6771 6772 auto *Result = 6773 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6774 assert(Result->getType()->isIntegerTy(1) && 6775 "Otherwise cannot be an operand to a branch instruction"); 6776 6777 if (Result->isZeroValue()) { 6778 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6779 const SCEV *UpperBound = 6780 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6781 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6782 } 6783 6784 return getCouldNotCompute(); 6785 } 6786 6787 /// Return true if we can constant fold an instruction of the specified type, 6788 /// assuming that all operands were constants. 6789 static bool CanConstantFold(const Instruction *I) { 6790 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6791 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6792 isa<LoadInst>(I)) 6793 return true; 6794 6795 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6796 if (const Function *F = CI->getCalledFunction()) 6797 return canConstantFoldCallTo(F); 6798 return false; 6799 } 6800 6801 /// Determine whether this instruction can constant evolve within this loop 6802 /// assuming its operands can all constant evolve. 6803 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6804 // An instruction outside of the loop can't be derived from a loop PHI. 6805 if (!L->contains(I)) return false; 6806 6807 if (isa<PHINode>(I)) { 6808 // We don't currently keep track of the control flow needed to evaluate 6809 // PHIs, so we cannot handle PHIs inside of loops. 6810 return L->getHeader() == I->getParent(); 6811 } 6812 6813 // If we won't be able to constant fold this expression even if the operands 6814 // are constants, bail early. 6815 return CanConstantFold(I); 6816 } 6817 6818 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6819 /// recursing through each instruction operand until reaching a loop header phi. 6820 static PHINode * 6821 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6822 DenseMap<Instruction *, PHINode *> &PHIMap, 6823 unsigned Depth) { 6824 if (Depth > MaxConstantEvolvingDepth) 6825 return nullptr; 6826 6827 // Otherwise, we can evaluate this instruction if all of its operands are 6828 // constant or derived from a PHI node themselves. 6829 PHINode *PHI = nullptr; 6830 for (Value *Op : UseInst->operands()) { 6831 if (isa<Constant>(Op)) continue; 6832 6833 Instruction *OpInst = dyn_cast<Instruction>(Op); 6834 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6835 6836 PHINode *P = dyn_cast<PHINode>(OpInst); 6837 if (!P) 6838 // If this operand is already visited, reuse the prior result. 6839 // We may have P != PHI if this is the deepest point at which the 6840 // inconsistent paths meet. 6841 P = PHIMap.lookup(OpInst); 6842 if (!P) { 6843 // Recurse and memoize the results, whether a phi is found or not. 6844 // This recursive call invalidates pointers into PHIMap. 6845 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 6846 PHIMap[OpInst] = P; 6847 } 6848 if (!P) 6849 return nullptr; // Not evolving from PHI 6850 if (PHI && PHI != P) 6851 return nullptr; // Evolving from multiple different PHIs. 6852 PHI = P; 6853 } 6854 // This is a expression evolving from a constant PHI! 6855 return PHI; 6856 } 6857 6858 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6859 /// in the loop that V is derived from. We allow arbitrary operations along the 6860 /// way, but the operands of an operation must either be constants or a value 6861 /// derived from a constant PHI. If this expression does not fit with these 6862 /// constraints, return null. 6863 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6864 Instruction *I = dyn_cast<Instruction>(V); 6865 if (!I || !canConstantEvolve(I, L)) return nullptr; 6866 6867 if (PHINode *PN = dyn_cast<PHINode>(I)) 6868 return PN; 6869 6870 // Record non-constant instructions contained by the loop. 6871 DenseMap<Instruction *, PHINode *> PHIMap; 6872 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 6873 } 6874 6875 /// EvaluateExpression - Given an expression that passes the 6876 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6877 /// in the loop has the value PHIVal. If we can't fold this expression for some 6878 /// reason, return null. 6879 static Constant *EvaluateExpression(Value *V, const Loop *L, 6880 DenseMap<Instruction *, Constant *> &Vals, 6881 const DataLayout &DL, 6882 const TargetLibraryInfo *TLI) { 6883 // Convenient constant check, but redundant for recursive calls. 6884 if (Constant *C = dyn_cast<Constant>(V)) return C; 6885 Instruction *I = dyn_cast<Instruction>(V); 6886 if (!I) return nullptr; 6887 6888 if (Constant *C = Vals.lookup(I)) return C; 6889 6890 // An instruction inside the loop depends on a value outside the loop that we 6891 // weren't given a mapping for, or a value such as a call inside the loop. 6892 if (!canConstantEvolve(I, L)) return nullptr; 6893 6894 // An unmapped PHI can be due to a branch or another loop inside this loop, 6895 // or due to this not being the initial iteration through a loop where we 6896 // couldn't compute the evolution of this particular PHI last time. 6897 if (isa<PHINode>(I)) return nullptr; 6898 6899 std::vector<Constant*> Operands(I->getNumOperands()); 6900 6901 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6902 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6903 if (!Operand) { 6904 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6905 if (!Operands[i]) return nullptr; 6906 continue; 6907 } 6908 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6909 Vals[Operand] = C; 6910 if (!C) return nullptr; 6911 Operands[i] = C; 6912 } 6913 6914 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6915 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6916 Operands[1], DL, TLI); 6917 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6918 if (!LI->isVolatile()) 6919 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6920 } 6921 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6922 } 6923 6924 6925 // If every incoming value to PN except the one for BB is a specific Constant, 6926 // return that, else return nullptr. 6927 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6928 Constant *IncomingVal = nullptr; 6929 6930 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6931 if (PN->getIncomingBlock(i) == BB) 6932 continue; 6933 6934 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6935 if (!CurrentVal) 6936 return nullptr; 6937 6938 if (IncomingVal != CurrentVal) { 6939 if (IncomingVal) 6940 return nullptr; 6941 IncomingVal = CurrentVal; 6942 } 6943 } 6944 6945 return IncomingVal; 6946 } 6947 6948 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6949 /// in the header of its containing loop, we know the loop executes a 6950 /// constant number of times, and the PHI node is just a recurrence 6951 /// involving constants, fold it. 6952 Constant * 6953 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6954 const APInt &BEs, 6955 const Loop *L) { 6956 auto I = ConstantEvolutionLoopExitValue.find(PN); 6957 if (I != ConstantEvolutionLoopExitValue.end()) 6958 return I->second; 6959 6960 if (BEs.ugt(MaxBruteForceIterations)) 6961 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6962 6963 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6964 6965 DenseMap<Instruction *, Constant *> CurrentIterVals; 6966 BasicBlock *Header = L->getHeader(); 6967 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6968 6969 BasicBlock *Latch = L->getLoopLatch(); 6970 if (!Latch) 6971 return nullptr; 6972 6973 for (auto &I : *Header) { 6974 PHINode *PHI = dyn_cast<PHINode>(&I); 6975 if (!PHI) break; 6976 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6977 if (!StartCST) continue; 6978 CurrentIterVals[PHI] = StartCST; 6979 } 6980 if (!CurrentIterVals.count(PN)) 6981 return RetVal = nullptr; 6982 6983 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6984 6985 // Execute the loop symbolically to determine the exit value. 6986 if (BEs.getActiveBits() >= 32) 6987 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6988 6989 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6990 unsigned IterationNum = 0; 6991 const DataLayout &DL = getDataLayout(); 6992 for (; ; ++IterationNum) { 6993 if (IterationNum == NumIterations) 6994 return RetVal = CurrentIterVals[PN]; // Got exit value! 6995 6996 // Compute the value of the PHIs for the next iteration. 6997 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6998 DenseMap<Instruction *, Constant *> NextIterVals; 6999 Constant *NextPHI = 7000 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7001 if (!NextPHI) 7002 return nullptr; // Couldn't evaluate! 7003 NextIterVals[PN] = NextPHI; 7004 7005 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7006 7007 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7008 // cease to be able to evaluate one of them or if they stop evolving, 7009 // because that doesn't necessarily prevent us from computing PN. 7010 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7011 for (const auto &I : CurrentIterVals) { 7012 PHINode *PHI = dyn_cast<PHINode>(I.first); 7013 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7014 PHIsToCompute.emplace_back(PHI, I.second); 7015 } 7016 // We use two distinct loops because EvaluateExpression may invalidate any 7017 // iterators into CurrentIterVals. 7018 for (const auto &I : PHIsToCompute) { 7019 PHINode *PHI = I.first; 7020 Constant *&NextPHI = NextIterVals[PHI]; 7021 if (!NextPHI) { // Not already computed. 7022 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7023 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7024 } 7025 if (NextPHI != I.second) 7026 StoppedEvolving = false; 7027 } 7028 7029 // If all entries in CurrentIterVals == NextIterVals then we can stop 7030 // iterating, the loop can't continue to change. 7031 if (StoppedEvolving) 7032 return RetVal = CurrentIterVals[PN]; 7033 7034 CurrentIterVals.swap(NextIterVals); 7035 } 7036 } 7037 7038 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7039 Value *Cond, 7040 bool ExitWhen) { 7041 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7042 if (!PN) return getCouldNotCompute(); 7043 7044 // If the loop is canonicalized, the PHI will have exactly two entries. 7045 // That's the only form we support here. 7046 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7047 7048 DenseMap<Instruction *, Constant *> CurrentIterVals; 7049 BasicBlock *Header = L->getHeader(); 7050 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7051 7052 BasicBlock *Latch = L->getLoopLatch(); 7053 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7054 7055 for (auto &I : *Header) { 7056 PHINode *PHI = dyn_cast<PHINode>(&I); 7057 if (!PHI) 7058 break; 7059 auto *StartCST = getOtherIncomingValue(PHI, Latch); 7060 if (!StartCST) continue; 7061 CurrentIterVals[PHI] = StartCST; 7062 } 7063 if (!CurrentIterVals.count(PN)) 7064 return getCouldNotCompute(); 7065 7066 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7067 // the loop symbolically to determine when the condition gets a value of 7068 // "ExitWhen". 7069 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7070 const DataLayout &DL = getDataLayout(); 7071 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7072 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7073 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7074 7075 // Couldn't symbolically evaluate. 7076 if (!CondVal) return getCouldNotCompute(); 7077 7078 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7079 ++NumBruteForceTripCountsComputed; 7080 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7081 } 7082 7083 // Update all the PHI nodes for the next iteration. 7084 DenseMap<Instruction *, Constant *> NextIterVals; 7085 7086 // Create a list of which PHIs we need to compute. We want to do this before 7087 // calling EvaluateExpression on them because that may invalidate iterators 7088 // into CurrentIterVals. 7089 SmallVector<PHINode *, 8> PHIsToCompute; 7090 for (const auto &I : CurrentIterVals) { 7091 PHINode *PHI = dyn_cast<PHINode>(I.first); 7092 if (!PHI || PHI->getParent() != Header) continue; 7093 PHIsToCompute.push_back(PHI); 7094 } 7095 for (PHINode *PHI : PHIsToCompute) { 7096 Constant *&NextPHI = NextIterVals[PHI]; 7097 if (NextPHI) continue; // Already computed! 7098 7099 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7100 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7101 } 7102 CurrentIterVals.swap(NextIterVals); 7103 } 7104 7105 // Too many iterations were needed to evaluate. 7106 return getCouldNotCompute(); 7107 } 7108 7109 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7110 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7111 ValuesAtScopes[V]; 7112 // Check to see if we've folded this expression at this loop before. 7113 for (auto &LS : Values) 7114 if (LS.first == L) 7115 return LS.second ? LS.second : V; 7116 7117 Values.emplace_back(L, nullptr); 7118 7119 // Otherwise compute it. 7120 const SCEV *C = computeSCEVAtScope(V, L); 7121 for (auto &LS : reverse(ValuesAtScopes[V])) 7122 if (LS.first == L) { 7123 LS.second = C; 7124 break; 7125 } 7126 return C; 7127 } 7128 7129 /// This builds up a Constant using the ConstantExpr interface. That way, we 7130 /// will return Constants for objects which aren't represented by a 7131 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7132 /// Returns NULL if the SCEV isn't representable as a Constant. 7133 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7134 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7135 case scCouldNotCompute: 7136 case scAddRecExpr: 7137 break; 7138 case scConstant: 7139 return cast<SCEVConstant>(V)->getValue(); 7140 case scUnknown: 7141 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7142 case scSignExtend: { 7143 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7144 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7145 return ConstantExpr::getSExt(CastOp, SS->getType()); 7146 break; 7147 } 7148 case scZeroExtend: { 7149 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7150 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7151 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7152 break; 7153 } 7154 case scTruncate: { 7155 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7156 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7157 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7158 break; 7159 } 7160 case scAddExpr: { 7161 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7162 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7163 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7164 unsigned AS = PTy->getAddressSpace(); 7165 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7166 C = ConstantExpr::getBitCast(C, DestPtrTy); 7167 } 7168 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7169 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7170 if (!C2) return nullptr; 7171 7172 // First pointer! 7173 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7174 unsigned AS = C2->getType()->getPointerAddressSpace(); 7175 std::swap(C, C2); 7176 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7177 // The offsets have been converted to bytes. We can add bytes to an 7178 // i8* by GEP with the byte count in the first index. 7179 C = ConstantExpr::getBitCast(C, DestPtrTy); 7180 } 7181 7182 // Don't bother trying to sum two pointers. We probably can't 7183 // statically compute a load that results from it anyway. 7184 if (C2->getType()->isPointerTy()) 7185 return nullptr; 7186 7187 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7188 if (PTy->getElementType()->isStructTy()) 7189 C2 = ConstantExpr::getIntegerCast( 7190 C2, Type::getInt32Ty(C->getContext()), true); 7191 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7192 } else 7193 C = ConstantExpr::getAdd(C, C2); 7194 } 7195 return C; 7196 } 7197 break; 7198 } 7199 case scMulExpr: { 7200 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7201 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7202 // Don't bother with pointers at all. 7203 if (C->getType()->isPointerTy()) return nullptr; 7204 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7205 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7206 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7207 C = ConstantExpr::getMul(C, C2); 7208 } 7209 return C; 7210 } 7211 break; 7212 } 7213 case scUDivExpr: { 7214 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7215 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7216 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7217 if (LHS->getType() == RHS->getType()) 7218 return ConstantExpr::getUDiv(LHS, RHS); 7219 break; 7220 } 7221 case scSMaxExpr: 7222 case scUMaxExpr: 7223 break; // TODO: smax, umax. 7224 } 7225 return nullptr; 7226 } 7227 7228 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7229 if (isa<SCEVConstant>(V)) return V; 7230 7231 // If this instruction is evolved from a constant-evolving PHI, compute the 7232 // exit value from the loop without using SCEVs. 7233 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7234 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7235 const Loop *LI = this->LI[I->getParent()]; 7236 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7237 if (PHINode *PN = dyn_cast<PHINode>(I)) 7238 if (PN->getParent() == LI->getHeader()) { 7239 // Okay, there is no closed form solution for the PHI node. Check 7240 // to see if the loop that contains it has a known backedge-taken 7241 // count. If so, we may be able to force computation of the exit 7242 // value. 7243 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7244 if (const SCEVConstant *BTCC = 7245 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7246 // Okay, we know how many times the containing loop executes. If 7247 // this is a constant evolving PHI node, get the final value at 7248 // the specified iteration number. 7249 Constant *RV = 7250 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7251 if (RV) return getSCEV(RV); 7252 } 7253 } 7254 7255 // Okay, this is an expression that we cannot symbolically evaluate 7256 // into a SCEV. Check to see if it's possible to symbolically evaluate 7257 // the arguments into constants, and if so, try to constant propagate the 7258 // result. This is particularly useful for computing loop exit values. 7259 if (CanConstantFold(I)) { 7260 SmallVector<Constant *, 4> Operands; 7261 bool MadeImprovement = false; 7262 for (Value *Op : I->operands()) { 7263 if (Constant *C = dyn_cast<Constant>(Op)) { 7264 Operands.push_back(C); 7265 continue; 7266 } 7267 7268 // If any of the operands is non-constant and if they are 7269 // non-integer and non-pointer, don't even try to analyze them 7270 // with scev techniques. 7271 if (!isSCEVable(Op->getType())) 7272 return V; 7273 7274 const SCEV *OrigV = getSCEV(Op); 7275 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7276 MadeImprovement |= OrigV != OpV; 7277 7278 Constant *C = BuildConstantFromSCEV(OpV); 7279 if (!C) return V; 7280 if (C->getType() != Op->getType()) 7281 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7282 Op->getType(), 7283 false), 7284 C, Op->getType()); 7285 Operands.push_back(C); 7286 } 7287 7288 // Check to see if getSCEVAtScope actually made an improvement. 7289 if (MadeImprovement) { 7290 Constant *C = nullptr; 7291 const DataLayout &DL = getDataLayout(); 7292 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7293 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7294 Operands[1], DL, &TLI); 7295 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7296 if (!LI->isVolatile()) 7297 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7298 } else 7299 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7300 if (!C) return V; 7301 return getSCEV(C); 7302 } 7303 } 7304 } 7305 7306 // This is some other type of SCEVUnknown, just return it. 7307 return V; 7308 } 7309 7310 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7311 // Avoid performing the look-up in the common case where the specified 7312 // expression has no loop-variant portions. 7313 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7314 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7315 if (OpAtScope != Comm->getOperand(i)) { 7316 // Okay, at least one of these operands is loop variant but might be 7317 // foldable. Build a new instance of the folded commutative expression. 7318 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7319 Comm->op_begin()+i); 7320 NewOps.push_back(OpAtScope); 7321 7322 for (++i; i != e; ++i) { 7323 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7324 NewOps.push_back(OpAtScope); 7325 } 7326 if (isa<SCEVAddExpr>(Comm)) 7327 return getAddExpr(NewOps); 7328 if (isa<SCEVMulExpr>(Comm)) 7329 return getMulExpr(NewOps); 7330 if (isa<SCEVSMaxExpr>(Comm)) 7331 return getSMaxExpr(NewOps); 7332 if (isa<SCEVUMaxExpr>(Comm)) 7333 return getUMaxExpr(NewOps); 7334 llvm_unreachable("Unknown commutative SCEV type!"); 7335 } 7336 } 7337 // If we got here, all operands are loop invariant. 7338 return Comm; 7339 } 7340 7341 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7342 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7343 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7344 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7345 return Div; // must be loop invariant 7346 return getUDivExpr(LHS, RHS); 7347 } 7348 7349 // If this is a loop recurrence for a loop that does not contain L, then we 7350 // are dealing with the final value computed by the loop. 7351 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7352 // First, attempt to evaluate each operand. 7353 // Avoid performing the look-up in the common case where the specified 7354 // expression has no loop-variant portions. 7355 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7356 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7357 if (OpAtScope == AddRec->getOperand(i)) 7358 continue; 7359 7360 // Okay, at least one of these operands is loop variant but might be 7361 // foldable. Build a new instance of the folded commutative expression. 7362 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7363 AddRec->op_begin()+i); 7364 NewOps.push_back(OpAtScope); 7365 for (++i; i != e; ++i) 7366 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7367 7368 const SCEV *FoldedRec = 7369 getAddRecExpr(NewOps, AddRec->getLoop(), 7370 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7371 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7372 // The addrec may be folded to a nonrecurrence, for example, if the 7373 // induction variable is multiplied by zero after constant folding. Go 7374 // ahead and return the folded value. 7375 if (!AddRec) 7376 return FoldedRec; 7377 break; 7378 } 7379 7380 // If the scope is outside the addrec's loop, evaluate it by using the 7381 // loop exit value of the addrec. 7382 if (!AddRec->getLoop()->contains(L)) { 7383 // To evaluate this recurrence, we need to know how many times the AddRec 7384 // loop iterates. Compute this now. 7385 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7386 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7387 7388 // Then, evaluate the AddRec. 7389 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7390 } 7391 7392 return AddRec; 7393 } 7394 7395 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7396 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7397 if (Op == Cast->getOperand()) 7398 return Cast; // must be loop invariant 7399 return getZeroExtendExpr(Op, Cast->getType()); 7400 } 7401 7402 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7403 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7404 if (Op == Cast->getOperand()) 7405 return Cast; // must be loop invariant 7406 return getSignExtendExpr(Op, Cast->getType()); 7407 } 7408 7409 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7410 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7411 if (Op == Cast->getOperand()) 7412 return Cast; // must be loop invariant 7413 return getTruncateExpr(Op, Cast->getType()); 7414 } 7415 7416 llvm_unreachable("Unknown SCEV type!"); 7417 } 7418 7419 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7420 return getSCEVAtScope(getSCEV(V), L); 7421 } 7422 7423 /// Finds the minimum unsigned root of the following equation: 7424 /// 7425 /// A * X = B (mod N) 7426 /// 7427 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7428 /// A and B isn't important. 7429 /// 7430 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7431 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7432 ScalarEvolution &SE) { 7433 uint32_t BW = A.getBitWidth(); 7434 assert(BW == SE.getTypeSizeInBits(B->getType())); 7435 assert(A != 0 && "A must be non-zero."); 7436 7437 // 1. D = gcd(A, N) 7438 // 7439 // The gcd of A and N may have only one prime factor: 2. The number of 7440 // trailing zeros in A is its multiplicity 7441 uint32_t Mult2 = A.countTrailingZeros(); 7442 // D = 2^Mult2 7443 7444 // 2. Check if B is divisible by D. 7445 // 7446 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7447 // is not less than multiplicity of this prime factor for D. 7448 if (SE.GetMinTrailingZeros(B) < Mult2) 7449 return SE.getCouldNotCompute(); 7450 7451 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7452 // modulo (N / D). 7453 // 7454 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7455 // (N / D) in general. The inverse itself always fits into BW bits, though, 7456 // so we immediately truncate it. 7457 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7458 APInt Mod(BW + 1, 0); 7459 Mod.setBit(BW - Mult2); // Mod = N / D 7460 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7461 7462 // 4. Compute the minimum unsigned root of the equation: 7463 // I * (B / D) mod (N / D) 7464 // To simplify the computation, we factor out the divide by D: 7465 // (I * B mod N) / D 7466 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7467 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7468 } 7469 7470 /// Find the roots of the quadratic equation for the given quadratic chrec 7471 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7472 /// two SCEVCouldNotCompute objects. 7473 /// 7474 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7475 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7476 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7477 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7478 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7479 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7480 7481 // We currently can only solve this if the coefficients are constants. 7482 if (!LC || !MC || !NC) 7483 return None; 7484 7485 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7486 const APInt &L = LC->getAPInt(); 7487 const APInt &M = MC->getAPInt(); 7488 const APInt &N = NC->getAPInt(); 7489 APInt Two(BitWidth, 2); 7490 7491 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7492 7493 // The A coefficient is N/2 7494 APInt A = N.sdiv(Two); 7495 7496 // The B coefficient is M-N/2 7497 APInt B = M; 7498 B -= A; // A is the same as N/2. 7499 7500 // The C coefficient is L. 7501 const APInt& C = L; 7502 7503 // Compute the B^2-4ac term. 7504 APInt SqrtTerm = B; 7505 SqrtTerm *= B; 7506 SqrtTerm -= 4 * (A * C); 7507 7508 if (SqrtTerm.isNegative()) { 7509 // The loop is provably infinite. 7510 return None; 7511 } 7512 7513 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7514 // integer value or else APInt::sqrt() will assert. 7515 APInt SqrtVal = SqrtTerm.sqrt(); 7516 7517 // Compute the two solutions for the quadratic formula. 7518 // The divisions must be performed as signed divisions. 7519 APInt NegB = -std::move(B); 7520 APInt TwoA = std::move(A); 7521 TwoA <<= 1; 7522 if (TwoA.isNullValue()) 7523 return None; 7524 7525 LLVMContext &Context = SE.getContext(); 7526 7527 ConstantInt *Solution1 = 7528 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7529 ConstantInt *Solution2 = 7530 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7531 7532 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7533 cast<SCEVConstant>(SE.getConstant(Solution2))); 7534 } 7535 7536 ScalarEvolution::ExitLimit 7537 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7538 bool AllowPredicates) { 7539 7540 // This is only used for loops with a "x != y" exit test. The exit condition 7541 // is now expressed as a single expression, V = x-y. So the exit test is 7542 // effectively V != 0. We know and take advantage of the fact that this 7543 // expression only being used in a comparison by zero context. 7544 7545 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7546 // If the value is a constant 7547 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7548 // If the value is already zero, the branch will execute zero times. 7549 if (C->getValue()->isZero()) return C; 7550 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7551 } 7552 7553 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7554 if (!AddRec && AllowPredicates) 7555 // Try to make this an AddRec using runtime tests, in the first X 7556 // iterations of this loop, where X is the SCEV expression found by the 7557 // algorithm below. 7558 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7559 7560 if (!AddRec || AddRec->getLoop() != L) 7561 return getCouldNotCompute(); 7562 7563 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7564 // the quadratic equation to solve it. 7565 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7566 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7567 const SCEVConstant *R1 = Roots->first; 7568 const SCEVConstant *R2 = Roots->second; 7569 // Pick the smallest positive root value. 7570 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7571 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7572 if (!CB->getZExtValue()) 7573 std::swap(R1, R2); // R1 is the minimum root now. 7574 7575 // We can only use this value if the chrec ends up with an exact zero 7576 // value at this index. When solving for "X*X != 5", for example, we 7577 // should not accept a root of 2. 7578 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7579 if (Val->isZero()) 7580 // We found a quadratic root! 7581 return ExitLimit(R1, R1, false, Predicates); 7582 } 7583 } 7584 return getCouldNotCompute(); 7585 } 7586 7587 // Otherwise we can only handle this if it is affine. 7588 if (!AddRec->isAffine()) 7589 return getCouldNotCompute(); 7590 7591 // If this is an affine expression, the execution count of this branch is 7592 // the minimum unsigned root of the following equation: 7593 // 7594 // Start + Step*N = 0 (mod 2^BW) 7595 // 7596 // equivalent to: 7597 // 7598 // Step*N = -Start (mod 2^BW) 7599 // 7600 // where BW is the common bit width of Start and Step. 7601 7602 // Get the initial value for the loop. 7603 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7604 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7605 7606 // For now we handle only constant steps. 7607 // 7608 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7609 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7610 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7611 // We have not yet seen any such cases. 7612 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7613 if (!StepC || StepC->getValue()->equalsInt(0)) 7614 return getCouldNotCompute(); 7615 7616 // For positive steps (counting up until unsigned overflow): 7617 // N = -Start/Step (as unsigned) 7618 // For negative steps (counting down to zero): 7619 // N = Start/-Step 7620 // First compute the unsigned distance from zero in the direction of Step. 7621 bool CountDown = StepC->getAPInt().isNegative(); 7622 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7623 7624 // Handle unitary steps, which cannot wraparound. 7625 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7626 // N = Distance (as unsigned) 7627 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7628 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); 7629 7630 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7631 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7632 // case, and see if we can improve the bound. 7633 // 7634 // Explicitly handling this here is necessary because getUnsignedRange 7635 // isn't context-sensitive; it doesn't know that we only care about the 7636 // range inside the loop. 7637 const SCEV *Zero = getZero(Distance->getType()); 7638 const SCEV *One = getOne(Distance->getType()); 7639 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7640 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7641 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7642 // as "unsigned_max(Distance + 1) - 1". 7643 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7644 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7645 } 7646 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7647 } 7648 7649 // If the condition controls loop exit (the loop exits only if the expression 7650 // is true) and the addition is no-wrap we can use unsigned divide to 7651 // compute the backedge count. In this case, the step may not divide the 7652 // distance, but we don't care because if the condition is "missed" the loop 7653 // will have undefined behavior due to wrapping. 7654 if (ControlsExit && AddRec->hasNoSelfWrap() && 7655 loopHasNoAbnormalExits(AddRec->getLoop())) { 7656 const SCEV *Exact = 7657 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7658 const SCEV *Max = 7659 Exact == getCouldNotCompute() 7660 ? Exact 7661 : getConstant(getUnsignedRange(Exact).getUnsignedMax()); 7662 return ExitLimit(Exact, Max, false, Predicates); 7663 } 7664 7665 // Solve the general equation. 7666 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 7667 getNegativeSCEV(Start), *this); 7668 const SCEV *M = E == getCouldNotCompute() 7669 ? E 7670 : getConstant(getUnsignedRange(E).getUnsignedMax()); 7671 return ExitLimit(E, M, false, Predicates); 7672 } 7673 7674 ScalarEvolution::ExitLimit 7675 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7676 // Loops that look like: while (X == 0) are very strange indeed. We don't 7677 // handle them yet except for the trivial case. This could be expanded in the 7678 // future as needed. 7679 7680 // If the value is a constant, check to see if it is known to be non-zero 7681 // already. If so, the backedge will execute zero times. 7682 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7683 if (!C->getValue()->isNullValue()) 7684 return getZero(C->getType()); 7685 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7686 } 7687 7688 // We could implement others, but I really doubt anyone writes loops like 7689 // this, and if they did, they would already be constant folded. 7690 return getCouldNotCompute(); 7691 } 7692 7693 std::pair<BasicBlock *, BasicBlock *> 7694 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7695 // If the block has a unique predecessor, then there is no path from the 7696 // predecessor to the block that does not go through the direct edge 7697 // from the predecessor to the block. 7698 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7699 return {Pred, BB}; 7700 7701 // A loop's header is defined to be a block that dominates the loop. 7702 // If the header has a unique predecessor outside the loop, it must be 7703 // a block that has exactly one successor that can reach the loop. 7704 if (Loop *L = LI.getLoopFor(BB)) 7705 return {L->getLoopPredecessor(), L->getHeader()}; 7706 7707 return {nullptr, nullptr}; 7708 } 7709 7710 /// SCEV structural equivalence is usually sufficient for testing whether two 7711 /// expressions are equal, however for the purposes of looking for a condition 7712 /// guarding a loop, it can be useful to be a little more general, since a 7713 /// front-end may have replicated the controlling expression. 7714 /// 7715 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7716 // Quick check to see if they are the same SCEV. 7717 if (A == B) return true; 7718 7719 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7720 // Not all instructions that are "identical" compute the same value. For 7721 // instance, two distinct alloca instructions allocating the same type are 7722 // identical and do not read memory; but compute distinct values. 7723 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7724 }; 7725 7726 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7727 // two different instructions with the same value. Check for this case. 7728 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7729 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7730 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7731 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7732 if (ComputesEqualValues(AI, BI)) 7733 return true; 7734 7735 // Otherwise assume they may have a different value. 7736 return false; 7737 } 7738 7739 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7740 const SCEV *&LHS, const SCEV *&RHS, 7741 unsigned Depth) { 7742 bool Changed = false; 7743 7744 // If we hit the max recursion limit bail out. 7745 if (Depth >= 3) 7746 return false; 7747 7748 // Canonicalize a constant to the right side. 7749 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7750 // Check for both operands constant. 7751 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7752 if (ConstantExpr::getICmp(Pred, 7753 LHSC->getValue(), 7754 RHSC->getValue())->isNullValue()) 7755 goto trivially_false; 7756 else 7757 goto trivially_true; 7758 } 7759 // Otherwise swap the operands to put the constant on the right. 7760 std::swap(LHS, RHS); 7761 Pred = ICmpInst::getSwappedPredicate(Pred); 7762 Changed = true; 7763 } 7764 7765 // If we're comparing an addrec with a value which is loop-invariant in the 7766 // addrec's loop, put the addrec on the left. Also make a dominance check, 7767 // as both operands could be addrecs loop-invariant in each other's loop. 7768 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7769 const Loop *L = AR->getLoop(); 7770 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7771 std::swap(LHS, RHS); 7772 Pred = ICmpInst::getSwappedPredicate(Pred); 7773 Changed = true; 7774 } 7775 } 7776 7777 // If there's a constant operand, canonicalize comparisons with boundary 7778 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7779 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7780 const APInt &RA = RC->getAPInt(); 7781 7782 bool SimplifiedByConstantRange = false; 7783 7784 if (!ICmpInst::isEquality(Pred)) { 7785 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7786 if (ExactCR.isFullSet()) 7787 goto trivially_true; 7788 else if (ExactCR.isEmptySet()) 7789 goto trivially_false; 7790 7791 APInt NewRHS; 7792 CmpInst::Predicate NewPred; 7793 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7794 ICmpInst::isEquality(NewPred)) { 7795 // We were able to convert an inequality to an equality. 7796 Pred = NewPred; 7797 RHS = getConstant(NewRHS); 7798 Changed = SimplifiedByConstantRange = true; 7799 } 7800 } 7801 7802 if (!SimplifiedByConstantRange) { 7803 switch (Pred) { 7804 default: 7805 break; 7806 case ICmpInst::ICMP_EQ: 7807 case ICmpInst::ICMP_NE: 7808 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7809 if (!RA) 7810 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7811 if (const SCEVMulExpr *ME = 7812 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7813 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7814 ME->getOperand(0)->isAllOnesValue()) { 7815 RHS = AE->getOperand(1); 7816 LHS = ME->getOperand(1); 7817 Changed = true; 7818 } 7819 break; 7820 7821 7822 // The "Should have been caught earlier!" messages refer to the fact 7823 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7824 // should have fired on the corresponding cases, and canonicalized the 7825 // check to trivially_true or trivially_false. 7826 7827 case ICmpInst::ICMP_UGE: 7828 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7829 Pred = ICmpInst::ICMP_UGT; 7830 RHS = getConstant(RA - 1); 7831 Changed = true; 7832 break; 7833 case ICmpInst::ICMP_ULE: 7834 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7835 Pred = ICmpInst::ICMP_ULT; 7836 RHS = getConstant(RA + 1); 7837 Changed = true; 7838 break; 7839 case ICmpInst::ICMP_SGE: 7840 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7841 Pred = ICmpInst::ICMP_SGT; 7842 RHS = getConstant(RA - 1); 7843 Changed = true; 7844 break; 7845 case ICmpInst::ICMP_SLE: 7846 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7847 Pred = ICmpInst::ICMP_SLT; 7848 RHS = getConstant(RA + 1); 7849 Changed = true; 7850 break; 7851 } 7852 } 7853 } 7854 7855 // Check for obvious equality. 7856 if (HasSameValue(LHS, RHS)) { 7857 if (ICmpInst::isTrueWhenEqual(Pred)) 7858 goto trivially_true; 7859 if (ICmpInst::isFalseWhenEqual(Pred)) 7860 goto trivially_false; 7861 } 7862 7863 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7864 // adding or subtracting 1 from one of the operands. 7865 switch (Pred) { 7866 case ICmpInst::ICMP_SLE: 7867 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7868 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7869 SCEV::FlagNSW); 7870 Pred = ICmpInst::ICMP_SLT; 7871 Changed = true; 7872 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7873 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7874 SCEV::FlagNSW); 7875 Pred = ICmpInst::ICMP_SLT; 7876 Changed = true; 7877 } 7878 break; 7879 case ICmpInst::ICMP_SGE: 7880 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7881 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7882 SCEV::FlagNSW); 7883 Pred = ICmpInst::ICMP_SGT; 7884 Changed = true; 7885 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7886 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7887 SCEV::FlagNSW); 7888 Pred = ICmpInst::ICMP_SGT; 7889 Changed = true; 7890 } 7891 break; 7892 case ICmpInst::ICMP_ULE: 7893 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7894 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7895 SCEV::FlagNUW); 7896 Pred = ICmpInst::ICMP_ULT; 7897 Changed = true; 7898 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7899 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7900 Pred = ICmpInst::ICMP_ULT; 7901 Changed = true; 7902 } 7903 break; 7904 case ICmpInst::ICMP_UGE: 7905 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7906 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7907 Pred = ICmpInst::ICMP_UGT; 7908 Changed = true; 7909 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7910 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7911 SCEV::FlagNUW); 7912 Pred = ICmpInst::ICMP_UGT; 7913 Changed = true; 7914 } 7915 break; 7916 default: 7917 break; 7918 } 7919 7920 // TODO: More simplifications are possible here. 7921 7922 // Recursively simplify until we either hit a recursion limit or nothing 7923 // changes. 7924 if (Changed) 7925 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7926 7927 return Changed; 7928 7929 trivially_true: 7930 // Return 0 == 0. 7931 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7932 Pred = ICmpInst::ICMP_EQ; 7933 return true; 7934 7935 trivially_false: 7936 // Return 0 != 0. 7937 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7938 Pred = ICmpInst::ICMP_NE; 7939 return true; 7940 } 7941 7942 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7943 return getSignedRange(S).getSignedMax().isNegative(); 7944 } 7945 7946 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7947 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7948 } 7949 7950 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7951 return !getSignedRange(S).getSignedMin().isNegative(); 7952 } 7953 7954 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7955 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7956 } 7957 7958 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7959 return isKnownNegative(S) || isKnownPositive(S); 7960 } 7961 7962 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7963 const SCEV *LHS, const SCEV *RHS) { 7964 // Canonicalize the inputs first. 7965 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7966 7967 // If LHS or RHS is an addrec, check to see if the condition is true in 7968 // every iteration of the loop. 7969 // If LHS and RHS are both addrec, both conditions must be true in 7970 // every iteration of the loop. 7971 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7972 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7973 bool LeftGuarded = false; 7974 bool RightGuarded = false; 7975 if (LAR) { 7976 const Loop *L = LAR->getLoop(); 7977 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7978 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7979 if (!RAR) return true; 7980 LeftGuarded = true; 7981 } 7982 } 7983 if (RAR) { 7984 const Loop *L = RAR->getLoop(); 7985 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7986 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7987 if (!LAR) return true; 7988 RightGuarded = true; 7989 } 7990 } 7991 if (LeftGuarded && RightGuarded) 7992 return true; 7993 7994 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7995 return true; 7996 7997 // Otherwise see what can be done with known constant ranges. 7998 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7999 } 8000 8001 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8002 ICmpInst::Predicate Pred, 8003 bool &Increasing) { 8004 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8005 8006 #ifndef NDEBUG 8007 // Verify an invariant: inverting the predicate should turn a monotonically 8008 // increasing change to a monotonically decreasing one, and vice versa. 8009 bool IncreasingSwapped; 8010 bool ResultSwapped = isMonotonicPredicateImpl( 8011 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8012 8013 assert(Result == ResultSwapped && "should be able to analyze both!"); 8014 if (ResultSwapped) 8015 assert(Increasing == !IncreasingSwapped && 8016 "monotonicity should flip as we flip the predicate"); 8017 #endif 8018 8019 return Result; 8020 } 8021 8022 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8023 ICmpInst::Predicate Pred, 8024 bool &Increasing) { 8025 8026 // A zero step value for LHS means the induction variable is essentially a 8027 // loop invariant value. We don't really depend on the predicate actually 8028 // flipping from false to true (for increasing predicates, and the other way 8029 // around for decreasing predicates), all we care about is that *if* the 8030 // predicate changes then it only changes from false to true. 8031 // 8032 // A zero step value in itself is not very useful, but there may be places 8033 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8034 // as general as possible. 8035 8036 switch (Pred) { 8037 default: 8038 return false; // Conservative answer 8039 8040 case ICmpInst::ICMP_UGT: 8041 case ICmpInst::ICMP_UGE: 8042 case ICmpInst::ICMP_ULT: 8043 case ICmpInst::ICMP_ULE: 8044 if (!LHS->hasNoUnsignedWrap()) 8045 return false; 8046 8047 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8048 return true; 8049 8050 case ICmpInst::ICMP_SGT: 8051 case ICmpInst::ICMP_SGE: 8052 case ICmpInst::ICMP_SLT: 8053 case ICmpInst::ICMP_SLE: { 8054 if (!LHS->hasNoSignedWrap()) 8055 return false; 8056 8057 const SCEV *Step = LHS->getStepRecurrence(*this); 8058 8059 if (isKnownNonNegative(Step)) { 8060 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8061 return true; 8062 } 8063 8064 if (isKnownNonPositive(Step)) { 8065 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8066 return true; 8067 } 8068 8069 return false; 8070 } 8071 8072 } 8073 8074 llvm_unreachable("switch has default clause!"); 8075 } 8076 8077 bool ScalarEvolution::isLoopInvariantPredicate( 8078 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8079 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8080 const SCEV *&InvariantRHS) { 8081 8082 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8083 if (!isLoopInvariant(RHS, L)) { 8084 if (!isLoopInvariant(LHS, L)) 8085 return false; 8086 8087 std::swap(LHS, RHS); 8088 Pred = ICmpInst::getSwappedPredicate(Pred); 8089 } 8090 8091 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8092 if (!ArLHS || ArLHS->getLoop() != L) 8093 return false; 8094 8095 bool Increasing; 8096 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8097 return false; 8098 8099 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8100 // true as the loop iterates, and the backedge is control dependent on 8101 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8102 // 8103 // * if the predicate was false in the first iteration then the predicate 8104 // is never evaluated again, since the loop exits without taking the 8105 // backedge. 8106 // * if the predicate was true in the first iteration then it will 8107 // continue to be true for all future iterations since it is 8108 // monotonically increasing. 8109 // 8110 // For both the above possibilities, we can replace the loop varying 8111 // predicate with its value on the first iteration of the loop (which is 8112 // loop invariant). 8113 // 8114 // A similar reasoning applies for a monotonically decreasing predicate, by 8115 // replacing true with false and false with true in the above two bullets. 8116 8117 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8118 8119 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8120 return false; 8121 8122 InvariantPred = Pred; 8123 InvariantLHS = ArLHS->getStart(); 8124 InvariantRHS = RHS; 8125 return true; 8126 } 8127 8128 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8129 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8130 if (HasSameValue(LHS, RHS)) 8131 return ICmpInst::isTrueWhenEqual(Pred); 8132 8133 // This code is split out from isKnownPredicate because it is called from 8134 // within isLoopEntryGuardedByCond. 8135 8136 auto CheckRanges = 8137 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8138 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8139 .contains(RangeLHS); 8140 }; 8141 8142 // The check at the top of the function catches the case where the values are 8143 // known to be equal. 8144 if (Pred == CmpInst::ICMP_EQ) 8145 return false; 8146 8147 if (Pred == CmpInst::ICMP_NE) 8148 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8149 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8150 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8151 8152 if (CmpInst::isSigned(Pred)) 8153 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8154 8155 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8156 } 8157 8158 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8159 const SCEV *LHS, 8160 const SCEV *RHS) { 8161 8162 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8163 // Return Y via OutY. 8164 auto MatchBinaryAddToConst = 8165 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8166 SCEV::NoWrapFlags ExpectedFlags) { 8167 const SCEV *NonConstOp, *ConstOp; 8168 SCEV::NoWrapFlags FlagsPresent; 8169 8170 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8171 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8172 return false; 8173 8174 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8175 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8176 }; 8177 8178 APInt C; 8179 8180 switch (Pred) { 8181 default: 8182 break; 8183 8184 case ICmpInst::ICMP_SGE: 8185 std::swap(LHS, RHS); 8186 case ICmpInst::ICMP_SLE: 8187 // X s<= (X + C)<nsw> if C >= 0 8188 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8189 return true; 8190 8191 // (X + C)<nsw> s<= X if C <= 0 8192 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8193 !C.isStrictlyPositive()) 8194 return true; 8195 break; 8196 8197 case ICmpInst::ICMP_SGT: 8198 std::swap(LHS, RHS); 8199 case ICmpInst::ICMP_SLT: 8200 // X s< (X + C)<nsw> if C > 0 8201 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8202 C.isStrictlyPositive()) 8203 return true; 8204 8205 // (X + C)<nsw> s< X if C < 0 8206 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8207 return true; 8208 break; 8209 } 8210 8211 return false; 8212 } 8213 8214 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8215 const SCEV *LHS, 8216 const SCEV *RHS) { 8217 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8218 return false; 8219 8220 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8221 // the stack can result in exponential time complexity. 8222 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8223 8224 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8225 // 8226 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8227 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8228 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8229 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8230 // use isKnownPredicate later if needed. 8231 return isKnownNonNegative(RHS) && 8232 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8233 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8234 } 8235 8236 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8237 ICmpInst::Predicate Pred, 8238 const SCEV *LHS, const SCEV *RHS) { 8239 // No need to even try if we know the module has no guards. 8240 if (!HasGuards) 8241 return false; 8242 8243 return any_of(*BB, [&](Instruction &I) { 8244 using namespace llvm::PatternMatch; 8245 8246 Value *Condition; 8247 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8248 m_Value(Condition))) && 8249 isImpliedCond(Pred, LHS, RHS, Condition, false); 8250 }); 8251 } 8252 8253 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8254 /// protected by a conditional between LHS and RHS. This is used to 8255 /// to eliminate casts. 8256 bool 8257 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8258 ICmpInst::Predicate Pred, 8259 const SCEV *LHS, const SCEV *RHS) { 8260 // Interpret a null as meaning no loop, where there is obviously no guard 8261 // (interprocedural conditions notwithstanding). 8262 if (!L) return true; 8263 8264 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8265 return true; 8266 8267 BasicBlock *Latch = L->getLoopLatch(); 8268 if (!Latch) 8269 return false; 8270 8271 BranchInst *LoopContinuePredicate = 8272 dyn_cast<BranchInst>(Latch->getTerminator()); 8273 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8274 isImpliedCond(Pred, LHS, RHS, 8275 LoopContinuePredicate->getCondition(), 8276 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8277 return true; 8278 8279 // We don't want more than one activation of the following loops on the stack 8280 // -- that can lead to O(n!) time complexity. 8281 if (WalkingBEDominatingConds) 8282 return false; 8283 8284 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8285 8286 // See if we can exploit a trip count to prove the predicate. 8287 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8288 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8289 if (LatchBECount != getCouldNotCompute()) { 8290 // We know that Latch branches back to the loop header exactly 8291 // LatchBECount times. This means the backdege condition at Latch is 8292 // equivalent to "{0,+,1} u< LatchBECount". 8293 Type *Ty = LatchBECount->getType(); 8294 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8295 const SCEV *LoopCounter = 8296 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8297 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8298 LatchBECount)) 8299 return true; 8300 } 8301 8302 // Check conditions due to any @llvm.assume intrinsics. 8303 for (auto &AssumeVH : AC.assumptions()) { 8304 if (!AssumeVH) 8305 continue; 8306 auto *CI = cast<CallInst>(AssumeVH); 8307 if (!DT.dominates(CI, Latch->getTerminator())) 8308 continue; 8309 8310 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8311 return true; 8312 } 8313 8314 // If the loop is not reachable from the entry block, we risk running into an 8315 // infinite loop as we walk up into the dom tree. These loops do not matter 8316 // anyway, so we just return a conservative answer when we see them. 8317 if (!DT.isReachableFromEntry(L->getHeader())) 8318 return false; 8319 8320 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8321 return true; 8322 8323 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8324 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8325 8326 assert(DTN && "should reach the loop header before reaching the root!"); 8327 8328 BasicBlock *BB = DTN->getBlock(); 8329 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8330 return true; 8331 8332 BasicBlock *PBB = BB->getSinglePredecessor(); 8333 if (!PBB) 8334 continue; 8335 8336 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8337 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8338 continue; 8339 8340 Value *Condition = ContinuePredicate->getCondition(); 8341 8342 // If we have an edge `E` within the loop body that dominates the only 8343 // latch, the condition guarding `E` also guards the backedge. This 8344 // reasoning works only for loops with a single latch. 8345 8346 BasicBlockEdge DominatingEdge(PBB, BB); 8347 if (DominatingEdge.isSingleEdge()) { 8348 // We're constructively (and conservatively) enumerating edges within the 8349 // loop body that dominate the latch. The dominator tree better agree 8350 // with us on this: 8351 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8352 8353 if (isImpliedCond(Pred, LHS, RHS, Condition, 8354 BB != ContinuePredicate->getSuccessor(0))) 8355 return true; 8356 } 8357 } 8358 8359 return false; 8360 } 8361 8362 bool 8363 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8364 ICmpInst::Predicate Pred, 8365 const SCEV *LHS, const SCEV *RHS) { 8366 // Interpret a null as meaning no loop, where there is obviously no guard 8367 // (interprocedural conditions notwithstanding). 8368 if (!L) return false; 8369 8370 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8371 return true; 8372 8373 // Starting at the loop predecessor, climb up the predecessor chain, as long 8374 // as there are predecessors that can be found that have unique successors 8375 // leading to the original header. 8376 for (std::pair<BasicBlock *, BasicBlock *> 8377 Pair(L->getLoopPredecessor(), L->getHeader()); 8378 Pair.first; 8379 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8380 8381 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8382 return true; 8383 8384 BranchInst *LoopEntryPredicate = 8385 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8386 if (!LoopEntryPredicate || 8387 LoopEntryPredicate->isUnconditional()) 8388 continue; 8389 8390 if (isImpliedCond(Pred, LHS, RHS, 8391 LoopEntryPredicate->getCondition(), 8392 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8393 return true; 8394 } 8395 8396 // Check conditions due to any @llvm.assume intrinsics. 8397 for (auto &AssumeVH : AC.assumptions()) { 8398 if (!AssumeVH) 8399 continue; 8400 auto *CI = cast<CallInst>(AssumeVH); 8401 if (!DT.dominates(CI, L->getHeader())) 8402 continue; 8403 8404 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8405 return true; 8406 } 8407 8408 return false; 8409 } 8410 8411 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8412 const SCEV *LHS, const SCEV *RHS, 8413 Value *FoundCondValue, 8414 bool Inverse) { 8415 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8416 return false; 8417 8418 auto ClearOnExit = 8419 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8420 8421 // Recursively handle And and Or conditions. 8422 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8423 if (BO->getOpcode() == Instruction::And) { 8424 if (!Inverse) 8425 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8426 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8427 } else if (BO->getOpcode() == Instruction::Or) { 8428 if (Inverse) 8429 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8430 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8431 } 8432 } 8433 8434 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8435 if (!ICI) return false; 8436 8437 // Now that we found a conditional branch that dominates the loop or controls 8438 // the loop latch. Check to see if it is the comparison we are looking for. 8439 ICmpInst::Predicate FoundPred; 8440 if (Inverse) 8441 FoundPred = ICI->getInversePredicate(); 8442 else 8443 FoundPred = ICI->getPredicate(); 8444 8445 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8446 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8447 8448 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8449 } 8450 8451 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8452 const SCEV *RHS, 8453 ICmpInst::Predicate FoundPred, 8454 const SCEV *FoundLHS, 8455 const SCEV *FoundRHS) { 8456 // Balance the types. 8457 if (getTypeSizeInBits(LHS->getType()) < 8458 getTypeSizeInBits(FoundLHS->getType())) { 8459 if (CmpInst::isSigned(Pred)) { 8460 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8461 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8462 } else { 8463 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8464 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8465 } 8466 } else if (getTypeSizeInBits(LHS->getType()) > 8467 getTypeSizeInBits(FoundLHS->getType())) { 8468 if (CmpInst::isSigned(FoundPred)) { 8469 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8470 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8471 } else { 8472 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8473 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8474 } 8475 } 8476 8477 // Canonicalize the query to match the way instcombine will have 8478 // canonicalized the comparison. 8479 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8480 if (LHS == RHS) 8481 return CmpInst::isTrueWhenEqual(Pred); 8482 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8483 if (FoundLHS == FoundRHS) 8484 return CmpInst::isFalseWhenEqual(FoundPred); 8485 8486 // Check to see if we can make the LHS or RHS match. 8487 if (LHS == FoundRHS || RHS == FoundLHS) { 8488 if (isa<SCEVConstant>(RHS)) { 8489 std::swap(FoundLHS, FoundRHS); 8490 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8491 } else { 8492 std::swap(LHS, RHS); 8493 Pred = ICmpInst::getSwappedPredicate(Pred); 8494 } 8495 } 8496 8497 // Check whether the found predicate is the same as the desired predicate. 8498 if (FoundPred == Pred) 8499 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8500 8501 // Check whether swapping the found predicate makes it the same as the 8502 // desired predicate. 8503 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8504 if (isa<SCEVConstant>(RHS)) 8505 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8506 else 8507 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8508 RHS, LHS, FoundLHS, FoundRHS); 8509 } 8510 8511 // Unsigned comparison is the same as signed comparison when both the operands 8512 // are non-negative. 8513 if (CmpInst::isUnsigned(FoundPred) && 8514 CmpInst::getSignedPredicate(FoundPred) == Pred && 8515 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8516 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8517 8518 // Check if we can make progress by sharpening ranges. 8519 if (FoundPred == ICmpInst::ICMP_NE && 8520 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8521 8522 const SCEVConstant *C = nullptr; 8523 const SCEV *V = nullptr; 8524 8525 if (isa<SCEVConstant>(FoundLHS)) { 8526 C = cast<SCEVConstant>(FoundLHS); 8527 V = FoundRHS; 8528 } else { 8529 C = cast<SCEVConstant>(FoundRHS); 8530 V = FoundLHS; 8531 } 8532 8533 // The guarding predicate tells us that C != V. If the known range 8534 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8535 // range we consider has to correspond to same signedness as the 8536 // predicate we're interested in folding. 8537 8538 APInt Min = ICmpInst::isSigned(Pred) ? 8539 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8540 8541 if (Min == C->getAPInt()) { 8542 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8543 // This is true even if (Min + 1) wraps around -- in case of 8544 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8545 8546 APInt SharperMin = Min + 1; 8547 8548 switch (Pred) { 8549 case ICmpInst::ICMP_SGE: 8550 case ICmpInst::ICMP_UGE: 8551 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8552 // RHS, we're done. 8553 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8554 getConstant(SharperMin))) 8555 return true; 8556 8557 case ICmpInst::ICMP_SGT: 8558 case ICmpInst::ICMP_UGT: 8559 // We know from the range information that (V `Pred` Min || 8560 // V == Min). We know from the guarding condition that !(V 8561 // == Min). This gives us 8562 // 8563 // V `Pred` Min || V == Min && !(V == Min) 8564 // => V `Pred` Min 8565 // 8566 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8567 8568 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8569 return true; 8570 8571 default: 8572 // No change 8573 break; 8574 } 8575 } 8576 } 8577 8578 // Check whether the actual condition is beyond sufficient. 8579 if (FoundPred == ICmpInst::ICMP_EQ) 8580 if (ICmpInst::isTrueWhenEqual(Pred)) 8581 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8582 return true; 8583 if (Pred == ICmpInst::ICMP_NE) 8584 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8585 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8586 return true; 8587 8588 // Otherwise assume the worst. 8589 return false; 8590 } 8591 8592 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8593 const SCEV *&L, const SCEV *&R, 8594 SCEV::NoWrapFlags &Flags) { 8595 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8596 if (!AE || AE->getNumOperands() != 2) 8597 return false; 8598 8599 L = AE->getOperand(0); 8600 R = AE->getOperand(1); 8601 Flags = AE->getNoWrapFlags(); 8602 return true; 8603 } 8604 8605 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8606 const SCEV *Less) { 8607 // We avoid subtracting expressions here because this function is usually 8608 // fairly deep in the call stack (i.e. is called many times). 8609 8610 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8611 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8612 const auto *MAR = cast<SCEVAddRecExpr>(More); 8613 8614 if (LAR->getLoop() != MAR->getLoop()) 8615 return None; 8616 8617 // We look at affine expressions only; not for correctness but to keep 8618 // getStepRecurrence cheap. 8619 if (!LAR->isAffine() || !MAR->isAffine()) 8620 return None; 8621 8622 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8623 return None; 8624 8625 Less = LAR->getStart(); 8626 More = MAR->getStart(); 8627 8628 // fall through 8629 } 8630 8631 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8632 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8633 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8634 return M - L; 8635 } 8636 8637 const SCEV *L, *R; 8638 SCEV::NoWrapFlags Flags; 8639 if (splitBinaryAdd(Less, L, R, Flags)) 8640 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8641 if (R == More) 8642 return -(LC->getAPInt()); 8643 8644 if (splitBinaryAdd(More, L, R, Flags)) 8645 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8646 if (R == Less) 8647 return LC->getAPInt(); 8648 8649 return None; 8650 } 8651 8652 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8653 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8654 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8655 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8656 return false; 8657 8658 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8659 if (!AddRecLHS) 8660 return false; 8661 8662 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8663 if (!AddRecFoundLHS) 8664 return false; 8665 8666 // We'd like to let SCEV reason about control dependencies, so we constrain 8667 // both the inequalities to be about add recurrences on the same loop. This 8668 // way we can use isLoopEntryGuardedByCond later. 8669 8670 const Loop *L = AddRecFoundLHS->getLoop(); 8671 if (L != AddRecLHS->getLoop()) 8672 return false; 8673 8674 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8675 // 8676 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8677 // ... (2) 8678 // 8679 // Informal proof for (2), assuming (1) [*]: 8680 // 8681 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8682 // 8683 // Then 8684 // 8685 // FoundLHS s< FoundRHS s< INT_MIN - C 8686 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8687 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8688 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8689 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8690 // <=> FoundLHS + C s< FoundRHS + C 8691 // 8692 // [*]: (1) can be proved by ruling out overflow. 8693 // 8694 // [**]: This can be proved by analyzing all the four possibilities: 8695 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8696 // (A s>= 0, B s>= 0). 8697 // 8698 // Note: 8699 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8700 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8701 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8702 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8703 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8704 // C)". 8705 8706 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8707 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8708 if (!LDiff || !RDiff || *LDiff != *RDiff) 8709 return false; 8710 8711 if (LDiff->isMinValue()) 8712 return true; 8713 8714 APInt FoundRHSLimit; 8715 8716 if (Pred == CmpInst::ICMP_ULT) { 8717 FoundRHSLimit = -(*RDiff); 8718 } else { 8719 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8720 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8721 } 8722 8723 // Try to prove (1) or (2), as needed. 8724 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8725 getConstant(FoundRHSLimit)); 8726 } 8727 8728 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8729 const SCEV *LHS, const SCEV *RHS, 8730 const SCEV *FoundLHS, 8731 const SCEV *FoundRHS) { 8732 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8733 return true; 8734 8735 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8736 return true; 8737 8738 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8739 FoundLHS, FoundRHS) || 8740 // ~x < ~y --> x > y 8741 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8742 getNotSCEV(FoundRHS), 8743 getNotSCEV(FoundLHS)); 8744 } 8745 8746 8747 /// If Expr computes ~A, return A else return nullptr 8748 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8749 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8750 if (!Add || Add->getNumOperands() != 2 || 8751 !Add->getOperand(0)->isAllOnesValue()) 8752 return nullptr; 8753 8754 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8755 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8756 !AddRHS->getOperand(0)->isAllOnesValue()) 8757 return nullptr; 8758 8759 return AddRHS->getOperand(1); 8760 } 8761 8762 8763 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8764 template<typename MaxExprType> 8765 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8766 const SCEV *Candidate) { 8767 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8768 if (!MaxExpr) return false; 8769 8770 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8771 } 8772 8773 8774 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8775 template<typename MaxExprType> 8776 static bool IsMinConsistingOf(ScalarEvolution &SE, 8777 const SCEV *MaybeMinExpr, 8778 const SCEV *Candidate) { 8779 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8780 if (!MaybeMaxExpr) 8781 return false; 8782 8783 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8784 } 8785 8786 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8787 ICmpInst::Predicate Pred, 8788 const SCEV *LHS, const SCEV *RHS) { 8789 8790 // If both sides are affine addrecs for the same loop, with equal 8791 // steps, and we know the recurrences don't wrap, then we only 8792 // need to check the predicate on the starting values. 8793 8794 if (!ICmpInst::isRelational(Pred)) 8795 return false; 8796 8797 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8798 if (!LAR) 8799 return false; 8800 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8801 if (!RAR) 8802 return false; 8803 if (LAR->getLoop() != RAR->getLoop()) 8804 return false; 8805 if (!LAR->isAffine() || !RAR->isAffine()) 8806 return false; 8807 8808 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8809 return false; 8810 8811 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8812 SCEV::FlagNSW : SCEV::FlagNUW; 8813 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8814 return false; 8815 8816 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8817 } 8818 8819 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8820 /// expression? 8821 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8822 ICmpInst::Predicate Pred, 8823 const SCEV *LHS, const SCEV *RHS) { 8824 switch (Pred) { 8825 default: 8826 return false; 8827 8828 case ICmpInst::ICMP_SGE: 8829 std::swap(LHS, RHS); 8830 LLVM_FALLTHROUGH; 8831 case ICmpInst::ICMP_SLE: 8832 return 8833 // min(A, ...) <= A 8834 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8835 // A <= max(A, ...) 8836 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8837 8838 case ICmpInst::ICMP_UGE: 8839 std::swap(LHS, RHS); 8840 LLVM_FALLTHROUGH; 8841 case ICmpInst::ICMP_ULE: 8842 return 8843 // min(A, ...) <= A 8844 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8845 // A <= max(A, ...) 8846 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8847 } 8848 8849 llvm_unreachable("covered switch fell through?!"); 8850 } 8851 8852 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 8853 const SCEV *LHS, const SCEV *RHS, 8854 const SCEV *FoundLHS, 8855 const SCEV *FoundRHS, 8856 unsigned Depth) { 8857 assert(getTypeSizeInBits(LHS->getType()) == 8858 getTypeSizeInBits(RHS->getType()) && 8859 "LHS and RHS have different sizes?"); 8860 assert(getTypeSizeInBits(FoundLHS->getType()) == 8861 getTypeSizeInBits(FoundRHS->getType()) && 8862 "FoundLHS and FoundRHS have different sizes?"); 8863 // We want to avoid hurting the compile time with analysis of too big trees. 8864 if (Depth > MaxSCEVOperationsImplicationDepth) 8865 return false; 8866 // We only want to work with ICMP_SGT comparison so far. 8867 // TODO: Extend to ICMP_UGT? 8868 if (Pred == ICmpInst::ICMP_SLT) { 8869 Pred = ICmpInst::ICMP_SGT; 8870 std::swap(LHS, RHS); 8871 std::swap(FoundLHS, FoundRHS); 8872 } 8873 if (Pred != ICmpInst::ICMP_SGT) 8874 return false; 8875 8876 auto GetOpFromSExt = [&](const SCEV *S) { 8877 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 8878 return Ext->getOperand(); 8879 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 8880 // the constant in some cases. 8881 return S; 8882 }; 8883 8884 // Acquire values from extensions. 8885 auto *OrigFoundLHS = FoundLHS; 8886 LHS = GetOpFromSExt(LHS); 8887 FoundLHS = GetOpFromSExt(FoundLHS); 8888 8889 // Is the SGT predicate can be proved trivially or using the found context. 8890 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 8891 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 8892 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 8893 FoundRHS, Depth + 1); 8894 }; 8895 8896 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 8897 // We want to avoid creation of any new non-constant SCEV. Since we are 8898 // going to compare the operands to RHS, we should be certain that we don't 8899 // need any size extensions for this. So let's decline all cases when the 8900 // sizes of types of LHS and RHS do not match. 8901 // TODO: Maybe try to get RHS from sext to catch more cases? 8902 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 8903 return false; 8904 8905 // Should not overflow. 8906 if (!LHSAddExpr->hasNoSignedWrap()) 8907 return false; 8908 8909 auto *LL = LHSAddExpr->getOperand(0); 8910 auto *LR = LHSAddExpr->getOperand(1); 8911 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 8912 8913 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 8914 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 8915 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 8916 }; 8917 // Try to prove the following rule: 8918 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 8919 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 8920 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 8921 return true; 8922 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 8923 Value *LL, *LR; 8924 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 8925 using namespace llvm::PatternMatch; 8926 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 8927 // Rules for division. 8928 // We are going to perform some comparisons with Denominator and its 8929 // derivative expressions. In general case, creating a SCEV for it may 8930 // lead to a complex analysis of the entire graph, and in particular it 8931 // can request trip count recalculation for the same loop. This would 8932 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 8933 // this, we only want to create SCEVs that are constants in this section. 8934 // So we bail if Denominator is not a constant. 8935 if (!isa<ConstantInt>(LR)) 8936 return false; 8937 8938 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 8939 8940 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 8941 // then a SCEV for the numerator already exists and matches with FoundLHS. 8942 auto *Numerator = getExistingSCEV(LL); 8943 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 8944 return false; 8945 8946 // Make sure that the numerator matches with FoundLHS and the denominator 8947 // is positive. 8948 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 8949 return false; 8950 8951 auto *DTy = Denominator->getType(); 8952 auto *FRHSTy = FoundRHS->getType(); 8953 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 8954 // One of types is a pointer and another one is not. We cannot extend 8955 // them properly to a wider type, so let us just reject this case. 8956 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 8957 // to avoid this check. 8958 return false; 8959 8960 // Given that: 8961 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 8962 auto *WTy = getWiderType(DTy, FRHSTy); 8963 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 8964 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 8965 8966 // Try to prove the following rule: 8967 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 8968 // For example, given that FoundLHS > 2. It means that FoundLHS is at 8969 // least 3. If we divide it by Denominator < 4, we will have at least 1. 8970 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 8971 if (isKnownNonPositive(RHS) && 8972 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 8973 return true; 8974 8975 // Try to prove the following rule: 8976 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 8977 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 8978 // If we divide it by Denominator > 2, then: 8979 // 1. If FoundLHS is negative, then the result is 0. 8980 // 2. If FoundLHS is non-negative, then the result is non-negative. 8981 // Anyways, the result is non-negative. 8982 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 8983 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 8984 if (isKnownNegative(RHS) && 8985 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 8986 return true; 8987 } 8988 } 8989 8990 return false; 8991 } 8992 8993 bool 8994 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 8995 const SCEV *LHS, const SCEV *RHS) { 8996 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8997 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8998 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8999 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9000 } 9001 9002 bool 9003 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9004 const SCEV *LHS, const SCEV *RHS, 9005 const SCEV *FoundLHS, 9006 const SCEV *FoundRHS) { 9007 switch (Pred) { 9008 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9009 case ICmpInst::ICMP_EQ: 9010 case ICmpInst::ICMP_NE: 9011 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9012 return true; 9013 break; 9014 case ICmpInst::ICMP_SLT: 9015 case ICmpInst::ICMP_SLE: 9016 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9017 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9018 return true; 9019 break; 9020 case ICmpInst::ICMP_SGT: 9021 case ICmpInst::ICMP_SGE: 9022 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9023 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9024 return true; 9025 break; 9026 case ICmpInst::ICMP_ULT: 9027 case ICmpInst::ICMP_ULE: 9028 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9029 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9030 return true; 9031 break; 9032 case ICmpInst::ICMP_UGT: 9033 case ICmpInst::ICMP_UGE: 9034 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9035 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9036 return true; 9037 break; 9038 } 9039 9040 // Maybe it can be proved via operations? 9041 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9042 return true; 9043 9044 return false; 9045 } 9046 9047 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9048 const SCEV *LHS, 9049 const SCEV *RHS, 9050 const SCEV *FoundLHS, 9051 const SCEV *FoundRHS) { 9052 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9053 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9054 // reduce the compile time impact of this optimization. 9055 return false; 9056 9057 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9058 if (!Addend) 9059 return false; 9060 9061 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9062 9063 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9064 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9065 ConstantRange FoundLHSRange = 9066 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9067 9068 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9069 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9070 9071 // We can also compute the range of values for `LHS` that satisfy the 9072 // consequent, "`LHS` `Pred` `RHS`": 9073 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9074 ConstantRange SatisfyingLHSRange = 9075 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9076 9077 // The antecedent implies the consequent if every value of `LHS` that 9078 // satisfies the antecedent also satisfies the consequent. 9079 return SatisfyingLHSRange.contains(LHSRange); 9080 } 9081 9082 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9083 bool IsSigned, bool NoWrap) { 9084 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9085 9086 if (NoWrap) return false; 9087 9088 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9089 const SCEV *One = getOne(Stride->getType()); 9090 9091 if (IsSigned) { 9092 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 9093 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9094 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 9095 .getSignedMax(); 9096 9097 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9098 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9099 } 9100 9101 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 9102 APInt MaxValue = APInt::getMaxValue(BitWidth); 9103 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 9104 .getUnsignedMax(); 9105 9106 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9107 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9108 } 9109 9110 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9111 bool IsSigned, bool NoWrap) { 9112 if (NoWrap) return false; 9113 9114 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9115 const SCEV *One = getOne(Stride->getType()); 9116 9117 if (IsSigned) { 9118 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 9119 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9120 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 9121 .getSignedMax(); 9122 9123 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9124 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9125 } 9126 9127 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 9128 APInt MinValue = APInt::getMinValue(BitWidth); 9129 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 9130 .getUnsignedMax(); 9131 9132 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9133 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9134 } 9135 9136 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9137 bool Equality) { 9138 const SCEV *One = getOne(Step->getType()); 9139 Delta = Equality ? getAddExpr(Delta, Step) 9140 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9141 return getUDivExpr(Delta, Step); 9142 } 9143 9144 ScalarEvolution::ExitLimit 9145 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9146 const Loop *L, bool IsSigned, 9147 bool ControlsExit, bool AllowPredicates) { 9148 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9149 // We handle only IV < Invariant 9150 if (!isLoopInvariant(RHS, L)) 9151 return getCouldNotCompute(); 9152 9153 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9154 bool PredicatedIV = false; 9155 9156 if (!IV && AllowPredicates) { 9157 // Try to make this an AddRec using runtime tests, in the first X 9158 // iterations of this loop, where X is the SCEV expression found by the 9159 // algorithm below. 9160 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9161 PredicatedIV = true; 9162 } 9163 9164 // Avoid weird loops 9165 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9166 return getCouldNotCompute(); 9167 9168 bool NoWrap = ControlsExit && 9169 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9170 9171 const SCEV *Stride = IV->getStepRecurrence(*this); 9172 9173 bool PositiveStride = isKnownPositive(Stride); 9174 9175 // Avoid negative or zero stride values. 9176 if (!PositiveStride) { 9177 // We can compute the correct backedge taken count for loops with unknown 9178 // strides if we can prove that the loop is not an infinite loop with side 9179 // effects. Here's the loop structure we are trying to handle - 9180 // 9181 // i = start 9182 // do { 9183 // A[i] = i; 9184 // i += s; 9185 // } while (i < end); 9186 // 9187 // The backedge taken count for such loops is evaluated as - 9188 // (max(end, start + stride) - start - 1) /u stride 9189 // 9190 // The additional preconditions that we need to check to prove correctness 9191 // of the above formula is as follows - 9192 // 9193 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9194 // NoWrap flag). 9195 // b) loop is single exit with no side effects. 9196 // 9197 // 9198 // Precondition a) implies that if the stride is negative, this is a single 9199 // trip loop. The backedge taken count formula reduces to zero in this case. 9200 // 9201 // Precondition b) implies that the unknown stride cannot be zero otherwise 9202 // we have UB. 9203 // 9204 // The positive stride case is the same as isKnownPositive(Stride) returning 9205 // true (original behavior of the function). 9206 // 9207 // We want to make sure that the stride is truly unknown as there are edge 9208 // cases where ScalarEvolution propagates no wrap flags to the 9209 // post-increment/decrement IV even though the increment/decrement operation 9210 // itself is wrapping. The computed backedge taken count may be wrong in 9211 // such cases. This is prevented by checking that the stride is not known to 9212 // be either positive or non-positive. For example, no wrap flags are 9213 // propagated to the post-increment IV of this loop with a trip count of 2 - 9214 // 9215 // unsigned char i; 9216 // for(i=127; i<128; i+=129) 9217 // A[i] = i; 9218 // 9219 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9220 !loopHasNoSideEffects(L)) 9221 return getCouldNotCompute(); 9222 9223 } else if (!Stride->isOne() && 9224 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9225 // Avoid proven overflow cases: this will ensure that the backedge taken 9226 // count will not generate any unsigned overflow. Relaxed no-overflow 9227 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9228 // undefined behaviors like the case of C language. 9229 return getCouldNotCompute(); 9230 9231 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9232 : ICmpInst::ICMP_ULT; 9233 const SCEV *Start = IV->getStart(); 9234 const SCEV *End = RHS; 9235 // If the backedge is taken at least once, then it will be taken 9236 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9237 // is the LHS value of the less-than comparison the first time it is evaluated 9238 // and End is the RHS. 9239 const SCEV *BECountIfBackedgeTaken = 9240 computeBECount(getMinusSCEV(End, Start), Stride, false); 9241 // If the loop entry is guarded by the result of the backedge test of the 9242 // first loop iteration, then we know the backedge will be taken at least 9243 // once and so the backedge taken count is as above. If not then we use the 9244 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9245 // as if the backedge is taken at least once max(End,Start) is End and so the 9246 // result is as above, and if not max(End,Start) is Start so we get a backedge 9247 // count of zero. 9248 const SCEV *BECount; 9249 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9250 BECount = BECountIfBackedgeTaken; 9251 else { 9252 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9253 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9254 } 9255 9256 const SCEV *MaxBECount; 9257 bool MaxOrZero = false; 9258 if (isa<SCEVConstant>(BECount)) 9259 MaxBECount = BECount; 9260 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9261 // If we know exactly how many times the backedge will be taken if it's 9262 // taken at least once, then the backedge count will either be that or 9263 // zero. 9264 MaxBECount = BECountIfBackedgeTaken; 9265 MaxOrZero = true; 9266 } else { 9267 // Calculate the maximum backedge count based on the range of values 9268 // permitted by Start, End, and Stride. 9269 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 9270 : getUnsignedRange(Start).getUnsignedMin(); 9271 9272 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9273 9274 APInt StrideForMaxBECount; 9275 9276 if (PositiveStride) 9277 StrideForMaxBECount = 9278 IsSigned ? getSignedRange(Stride).getSignedMin() 9279 : getUnsignedRange(Stride).getUnsignedMin(); 9280 else 9281 // Using a stride of 1 is safe when computing max backedge taken count for 9282 // a loop with unknown stride. 9283 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9284 9285 APInt Limit = 9286 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9287 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9288 9289 // Although End can be a MAX expression we estimate MaxEnd considering only 9290 // the case End = RHS. This is safe because in the other case (End - Start) 9291 // is zero, leading to a zero maximum backedge taken count. 9292 APInt MaxEnd = 9293 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 9294 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 9295 9296 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9297 getConstant(StrideForMaxBECount), false); 9298 } 9299 9300 if (isa<SCEVCouldNotCompute>(MaxBECount) && 9301 !isa<SCEVCouldNotCompute>(BECount)) 9302 MaxBECount = getConstant(getUnsignedRange(BECount).getUnsignedMax()); 9303 9304 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9305 } 9306 9307 ScalarEvolution::ExitLimit 9308 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9309 const Loop *L, bool IsSigned, 9310 bool ControlsExit, bool AllowPredicates) { 9311 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9312 // We handle only IV > Invariant 9313 if (!isLoopInvariant(RHS, L)) 9314 return getCouldNotCompute(); 9315 9316 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9317 if (!IV && AllowPredicates) 9318 // Try to make this an AddRec using runtime tests, in the first X 9319 // iterations of this loop, where X is the SCEV expression found by the 9320 // algorithm below. 9321 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9322 9323 // Avoid weird loops 9324 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9325 return getCouldNotCompute(); 9326 9327 bool NoWrap = ControlsExit && 9328 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9329 9330 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9331 9332 // Avoid negative or zero stride values 9333 if (!isKnownPositive(Stride)) 9334 return getCouldNotCompute(); 9335 9336 // Avoid proven overflow cases: this will ensure that the backedge taken count 9337 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9338 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9339 // behaviors like the case of C language. 9340 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9341 return getCouldNotCompute(); 9342 9343 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9344 : ICmpInst::ICMP_UGT; 9345 9346 const SCEV *Start = IV->getStart(); 9347 const SCEV *End = RHS; 9348 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9349 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9350 9351 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9352 9353 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 9354 : getUnsignedRange(Start).getUnsignedMax(); 9355 9356 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 9357 : getUnsignedRange(Stride).getUnsignedMin(); 9358 9359 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9360 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9361 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9362 9363 // Although End can be a MIN expression we estimate MinEnd considering only 9364 // the case End = RHS. This is safe because in the other case (Start - End) 9365 // is zero, leading to a zero maximum backedge taken count. 9366 APInt MinEnd = 9367 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 9368 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 9369 9370 9371 const SCEV *MaxBECount = getCouldNotCompute(); 9372 if (isa<SCEVConstant>(BECount)) 9373 MaxBECount = BECount; 9374 else 9375 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9376 getConstant(MinStride), false); 9377 9378 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9379 MaxBECount = BECount; 9380 9381 return ExitLimit(BECount, MaxBECount, false, Predicates); 9382 } 9383 9384 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9385 ScalarEvolution &SE) const { 9386 if (Range.isFullSet()) // Infinite loop. 9387 return SE.getCouldNotCompute(); 9388 9389 // If the start is a non-zero constant, shift the range to simplify things. 9390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9391 if (!SC->getValue()->isZero()) { 9392 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9393 Operands[0] = SE.getZero(SC->getType()); 9394 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9395 getNoWrapFlags(FlagNW)); 9396 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9397 return ShiftedAddRec->getNumIterationsInRange( 9398 Range.subtract(SC->getAPInt()), SE); 9399 // This is strange and shouldn't happen. 9400 return SE.getCouldNotCompute(); 9401 } 9402 9403 // The only time we can solve this is when we have all constant indices. 9404 // Otherwise, we cannot determine the overflow conditions. 9405 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9406 return SE.getCouldNotCompute(); 9407 9408 // Okay at this point we know that all elements of the chrec are constants and 9409 // that the start element is zero. 9410 9411 // First check to see if the range contains zero. If not, the first 9412 // iteration exits. 9413 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9414 if (!Range.contains(APInt(BitWidth, 0))) 9415 return SE.getZero(getType()); 9416 9417 if (isAffine()) { 9418 // If this is an affine expression then we have this situation: 9419 // Solve {0,+,A} in Range === Ax in Range 9420 9421 // We know that zero is in the range. If A is positive then we know that 9422 // the upper value of the range must be the first possible exit value. 9423 // If A is negative then the lower of the range is the last possible loop 9424 // value. Also note that we already checked for a full range. 9425 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9426 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 9427 9428 // The exit value should be (End+A)/A. 9429 APInt ExitVal = (End + A).udiv(A); 9430 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9431 9432 // Evaluate at the exit value. If we really did fall out of the valid 9433 // range, then we computed our trip count, otherwise wrap around or other 9434 // things must have happened. 9435 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9436 if (Range.contains(Val->getValue())) 9437 return SE.getCouldNotCompute(); // Something strange happened 9438 9439 // Ensure that the previous value is in the range. This is a sanity check. 9440 assert(Range.contains( 9441 EvaluateConstantChrecAtConstant(this, 9442 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 9443 "Linear scev computation is off in a bad way!"); 9444 return SE.getConstant(ExitValue); 9445 } else if (isQuadratic()) { 9446 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9447 // quadratic equation to solve it. To do this, we must frame our problem in 9448 // terms of figuring out when zero is crossed, instead of when 9449 // Range.getUpper() is crossed. 9450 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9451 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9452 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9453 9454 // Next, solve the constructed addrec 9455 if (auto Roots = 9456 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9457 const SCEVConstant *R1 = Roots->first; 9458 const SCEVConstant *R2 = Roots->second; 9459 // Pick the smallest positive root value. 9460 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9461 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9462 if (!CB->getZExtValue()) 9463 std::swap(R1, R2); // R1 is the minimum root now. 9464 9465 // Make sure the root is not off by one. The returned iteration should 9466 // not be in the range, but the previous one should be. When solving 9467 // for "X*X < 5", for example, we should not return a root of 2. 9468 ConstantInt *R1Val = 9469 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9470 if (Range.contains(R1Val->getValue())) { 9471 // The next iteration must be out of the range... 9472 ConstantInt *NextVal = 9473 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9474 9475 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9476 if (!Range.contains(R1Val->getValue())) 9477 return SE.getConstant(NextVal); 9478 return SE.getCouldNotCompute(); // Something strange happened 9479 } 9480 9481 // If R1 was not in the range, then it is a good return value. Make 9482 // sure that R1-1 WAS in the range though, just in case. 9483 ConstantInt *NextVal = 9484 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9485 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9486 if (Range.contains(R1Val->getValue())) 9487 return R1; 9488 return SE.getCouldNotCompute(); // Something strange happened 9489 } 9490 } 9491 } 9492 9493 return SE.getCouldNotCompute(); 9494 } 9495 9496 // Return true when S contains at least an undef value. 9497 static inline bool containsUndefs(const SCEV *S) { 9498 return SCEVExprContains(S, [](const SCEV *S) { 9499 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9500 return isa<UndefValue>(SU->getValue()); 9501 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9502 return isa<UndefValue>(SC->getValue()); 9503 return false; 9504 }); 9505 } 9506 9507 namespace { 9508 // Collect all steps of SCEV expressions. 9509 struct SCEVCollectStrides { 9510 ScalarEvolution &SE; 9511 SmallVectorImpl<const SCEV *> &Strides; 9512 9513 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9514 : SE(SE), Strides(S) {} 9515 9516 bool follow(const SCEV *S) { 9517 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9518 Strides.push_back(AR->getStepRecurrence(SE)); 9519 return true; 9520 } 9521 bool isDone() const { return false; } 9522 }; 9523 9524 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9525 struct SCEVCollectTerms { 9526 SmallVectorImpl<const SCEV *> &Terms; 9527 9528 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9529 : Terms(T) {} 9530 9531 bool follow(const SCEV *S) { 9532 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9533 isa<SCEVSignExtendExpr>(S)) { 9534 if (!containsUndefs(S)) 9535 Terms.push_back(S); 9536 9537 // Stop recursion: once we collected a term, do not walk its operands. 9538 return false; 9539 } 9540 9541 // Keep looking. 9542 return true; 9543 } 9544 bool isDone() const { return false; } 9545 }; 9546 9547 // Check if a SCEV contains an AddRecExpr. 9548 struct SCEVHasAddRec { 9549 bool &ContainsAddRec; 9550 9551 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9552 ContainsAddRec = false; 9553 } 9554 9555 bool follow(const SCEV *S) { 9556 if (isa<SCEVAddRecExpr>(S)) { 9557 ContainsAddRec = true; 9558 9559 // Stop recursion: once we collected a term, do not walk its operands. 9560 return false; 9561 } 9562 9563 // Keep looking. 9564 return true; 9565 } 9566 bool isDone() const { return false; } 9567 }; 9568 9569 // Find factors that are multiplied with an expression that (possibly as a 9570 // subexpression) contains an AddRecExpr. In the expression: 9571 // 9572 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9573 // 9574 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9575 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9576 // parameters as they form a product with an induction variable. 9577 // 9578 // This collector expects all array size parameters to be in the same MulExpr. 9579 // It might be necessary to later add support for collecting parameters that are 9580 // spread over different nested MulExpr. 9581 struct SCEVCollectAddRecMultiplies { 9582 SmallVectorImpl<const SCEV *> &Terms; 9583 ScalarEvolution &SE; 9584 9585 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9586 : Terms(T), SE(SE) {} 9587 9588 bool follow(const SCEV *S) { 9589 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9590 bool HasAddRec = false; 9591 SmallVector<const SCEV *, 0> Operands; 9592 for (auto Op : Mul->operands()) { 9593 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 9594 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 9595 Operands.push_back(Op); 9596 } else if (Unknown) { 9597 HasAddRec = true; 9598 } else { 9599 bool ContainsAddRec; 9600 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9601 visitAll(Op, ContiansAddRec); 9602 HasAddRec |= ContainsAddRec; 9603 } 9604 } 9605 if (Operands.size() == 0) 9606 return true; 9607 9608 if (!HasAddRec) 9609 return false; 9610 9611 Terms.push_back(SE.getMulExpr(Operands)); 9612 // Stop recursion: once we collected a term, do not walk its operands. 9613 return false; 9614 } 9615 9616 // Keep looking. 9617 return true; 9618 } 9619 bool isDone() const { return false; } 9620 }; 9621 } 9622 9623 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9624 /// two places: 9625 /// 1) The strides of AddRec expressions. 9626 /// 2) Unknowns that are multiplied with AddRec expressions. 9627 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9628 SmallVectorImpl<const SCEV *> &Terms) { 9629 SmallVector<const SCEV *, 4> Strides; 9630 SCEVCollectStrides StrideCollector(*this, Strides); 9631 visitAll(Expr, StrideCollector); 9632 9633 DEBUG({ 9634 dbgs() << "Strides:\n"; 9635 for (const SCEV *S : Strides) 9636 dbgs() << *S << "\n"; 9637 }); 9638 9639 for (const SCEV *S : Strides) { 9640 SCEVCollectTerms TermCollector(Terms); 9641 visitAll(S, TermCollector); 9642 } 9643 9644 DEBUG({ 9645 dbgs() << "Terms:\n"; 9646 for (const SCEV *T : Terms) 9647 dbgs() << *T << "\n"; 9648 }); 9649 9650 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9651 visitAll(Expr, MulCollector); 9652 } 9653 9654 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9655 SmallVectorImpl<const SCEV *> &Terms, 9656 SmallVectorImpl<const SCEV *> &Sizes) { 9657 int Last = Terms.size() - 1; 9658 const SCEV *Step = Terms[Last]; 9659 9660 // End of recursion. 9661 if (Last == 0) { 9662 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9663 SmallVector<const SCEV *, 2> Qs; 9664 for (const SCEV *Op : M->operands()) 9665 if (!isa<SCEVConstant>(Op)) 9666 Qs.push_back(Op); 9667 9668 Step = SE.getMulExpr(Qs); 9669 } 9670 9671 Sizes.push_back(Step); 9672 return true; 9673 } 9674 9675 for (const SCEV *&Term : Terms) { 9676 // Normalize the terms before the next call to findArrayDimensionsRec. 9677 const SCEV *Q, *R; 9678 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9679 9680 // Bail out when GCD does not evenly divide one of the terms. 9681 if (!R->isZero()) 9682 return false; 9683 9684 Term = Q; 9685 } 9686 9687 // Remove all SCEVConstants. 9688 Terms.erase( 9689 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9690 Terms.end()); 9691 9692 if (Terms.size() > 0) 9693 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9694 return false; 9695 9696 Sizes.push_back(Step); 9697 return true; 9698 } 9699 9700 9701 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9702 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9703 for (const SCEV *T : Terms) 9704 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9705 return true; 9706 return false; 9707 } 9708 9709 // Return the number of product terms in S. 9710 static inline int numberOfTerms(const SCEV *S) { 9711 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9712 return Expr->getNumOperands(); 9713 return 1; 9714 } 9715 9716 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9717 if (isa<SCEVConstant>(T)) 9718 return nullptr; 9719 9720 if (isa<SCEVUnknown>(T)) 9721 return T; 9722 9723 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9724 SmallVector<const SCEV *, 2> Factors; 9725 for (const SCEV *Op : M->operands()) 9726 if (!isa<SCEVConstant>(Op)) 9727 Factors.push_back(Op); 9728 9729 return SE.getMulExpr(Factors); 9730 } 9731 9732 return T; 9733 } 9734 9735 /// Return the size of an element read or written by Inst. 9736 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9737 Type *Ty; 9738 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9739 Ty = Store->getValueOperand()->getType(); 9740 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9741 Ty = Load->getType(); 9742 else 9743 return nullptr; 9744 9745 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9746 return getSizeOfExpr(ETy, Ty); 9747 } 9748 9749 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9750 SmallVectorImpl<const SCEV *> &Sizes, 9751 const SCEV *ElementSize) { 9752 if (Terms.size() < 1 || !ElementSize) 9753 return; 9754 9755 // Early return when Terms do not contain parameters: we do not delinearize 9756 // non parametric SCEVs. 9757 if (!containsParameters(Terms)) 9758 return; 9759 9760 DEBUG({ 9761 dbgs() << "Terms:\n"; 9762 for (const SCEV *T : Terms) 9763 dbgs() << *T << "\n"; 9764 }); 9765 9766 // Remove duplicates. 9767 array_pod_sort(Terms.begin(), Terms.end()); 9768 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9769 9770 // Put larger terms first. 9771 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9772 return numberOfTerms(LHS) > numberOfTerms(RHS); 9773 }); 9774 9775 // Try to divide all terms by the element size. If term is not divisible by 9776 // element size, proceed with the original term. 9777 for (const SCEV *&Term : Terms) { 9778 const SCEV *Q, *R; 9779 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 9780 if (!Q->isZero()) 9781 Term = Q; 9782 } 9783 9784 SmallVector<const SCEV *, 4> NewTerms; 9785 9786 // Remove constant factors. 9787 for (const SCEV *T : Terms) 9788 if (const SCEV *NewT = removeConstantFactors(*this, T)) 9789 NewTerms.push_back(NewT); 9790 9791 DEBUG({ 9792 dbgs() << "Terms after sorting:\n"; 9793 for (const SCEV *T : NewTerms) 9794 dbgs() << *T << "\n"; 9795 }); 9796 9797 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 9798 Sizes.clear(); 9799 return; 9800 } 9801 9802 // The last element to be pushed into Sizes is the size of an element. 9803 Sizes.push_back(ElementSize); 9804 9805 DEBUG({ 9806 dbgs() << "Sizes:\n"; 9807 for (const SCEV *S : Sizes) 9808 dbgs() << *S << "\n"; 9809 }); 9810 } 9811 9812 void ScalarEvolution::computeAccessFunctions( 9813 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9814 SmallVectorImpl<const SCEV *> &Sizes) { 9815 9816 // Early exit in case this SCEV is not an affine multivariate function. 9817 if (Sizes.empty()) 9818 return; 9819 9820 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9821 if (!AR->isAffine()) 9822 return; 9823 9824 const SCEV *Res = Expr; 9825 int Last = Sizes.size() - 1; 9826 for (int i = Last; i >= 0; i--) { 9827 const SCEV *Q, *R; 9828 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9829 9830 DEBUG({ 9831 dbgs() << "Res: " << *Res << "\n"; 9832 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9833 dbgs() << "Res divided by Sizes[i]:\n"; 9834 dbgs() << "Quotient: " << *Q << "\n"; 9835 dbgs() << "Remainder: " << *R << "\n"; 9836 }); 9837 9838 Res = Q; 9839 9840 // Do not record the last subscript corresponding to the size of elements in 9841 // the array. 9842 if (i == Last) { 9843 9844 // Bail out if the remainder is too complex. 9845 if (isa<SCEVAddRecExpr>(R)) { 9846 Subscripts.clear(); 9847 Sizes.clear(); 9848 return; 9849 } 9850 9851 continue; 9852 } 9853 9854 // Record the access function for the current subscript. 9855 Subscripts.push_back(R); 9856 } 9857 9858 // Also push in last position the remainder of the last division: it will be 9859 // the access function of the innermost dimension. 9860 Subscripts.push_back(Res); 9861 9862 std::reverse(Subscripts.begin(), Subscripts.end()); 9863 9864 DEBUG({ 9865 dbgs() << "Subscripts:\n"; 9866 for (const SCEV *S : Subscripts) 9867 dbgs() << *S << "\n"; 9868 }); 9869 } 9870 9871 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9872 /// sizes of an array access. Returns the remainder of the delinearization that 9873 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9874 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9875 /// expressions in the stride and base of a SCEV corresponding to the 9876 /// computation of a GCD (greatest common divisor) of base and stride. When 9877 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9878 /// 9879 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9880 /// 9881 /// void foo(long n, long m, long o, double A[n][m][o]) { 9882 /// 9883 /// for (long i = 0; i < n; i++) 9884 /// for (long j = 0; j < m; j++) 9885 /// for (long k = 0; k < o; k++) 9886 /// A[i][j][k] = 1.0; 9887 /// } 9888 /// 9889 /// the delinearization input is the following AddRec SCEV: 9890 /// 9891 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9892 /// 9893 /// From this SCEV, we are able to say that the base offset of the access is %A 9894 /// because it appears as an offset that does not divide any of the strides in 9895 /// the loops: 9896 /// 9897 /// CHECK: Base offset: %A 9898 /// 9899 /// and then SCEV->delinearize determines the size of some of the dimensions of 9900 /// the array as these are the multiples by which the strides are happening: 9901 /// 9902 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9903 /// 9904 /// Note that the outermost dimension remains of UnknownSize because there are 9905 /// no strides that would help identifying the size of the last dimension: when 9906 /// the array has been statically allocated, one could compute the size of that 9907 /// dimension by dividing the overall size of the array by the size of the known 9908 /// dimensions: %m * %o * 8. 9909 /// 9910 /// Finally delinearize provides the access functions for the array reference 9911 /// that does correspond to A[i][j][k] of the above C testcase: 9912 /// 9913 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9914 /// 9915 /// The testcases are checking the output of a function pass: 9916 /// DelinearizationPass that walks through all loads and stores of a function 9917 /// asking for the SCEV of the memory access with respect to all enclosing 9918 /// loops, calling SCEV->delinearize on that and printing the results. 9919 9920 void ScalarEvolution::delinearize(const SCEV *Expr, 9921 SmallVectorImpl<const SCEV *> &Subscripts, 9922 SmallVectorImpl<const SCEV *> &Sizes, 9923 const SCEV *ElementSize) { 9924 // First step: collect parametric terms. 9925 SmallVector<const SCEV *, 4> Terms; 9926 collectParametricTerms(Expr, Terms); 9927 9928 if (Terms.empty()) 9929 return; 9930 9931 // Second step: find subscript sizes. 9932 findArrayDimensions(Terms, Sizes, ElementSize); 9933 9934 if (Sizes.empty()) 9935 return; 9936 9937 // Third step: compute the access functions for each subscript. 9938 computeAccessFunctions(Expr, Subscripts, Sizes); 9939 9940 if (Subscripts.empty()) 9941 return; 9942 9943 DEBUG({ 9944 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9945 dbgs() << "ArrayDecl[UnknownSize]"; 9946 for (const SCEV *S : Sizes) 9947 dbgs() << "[" << *S << "]"; 9948 9949 dbgs() << "\nArrayRef"; 9950 for (const SCEV *S : Subscripts) 9951 dbgs() << "[" << *S << "]"; 9952 dbgs() << "\n"; 9953 }); 9954 } 9955 9956 //===----------------------------------------------------------------------===// 9957 // SCEVCallbackVH Class Implementation 9958 //===----------------------------------------------------------------------===// 9959 9960 void ScalarEvolution::SCEVCallbackVH::deleted() { 9961 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9962 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9963 SE->ConstantEvolutionLoopExitValue.erase(PN); 9964 SE->eraseValueFromMap(getValPtr()); 9965 // this now dangles! 9966 } 9967 9968 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9969 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9970 9971 // Forget all the expressions associated with users of the old value, 9972 // so that future queries will recompute the expressions using the new 9973 // value. 9974 Value *Old = getValPtr(); 9975 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9976 SmallPtrSet<User *, 8> Visited; 9977 while (!Worklist.empty()) { 9978 User *U = Worklist.pop_back_val(); 9979 // Deleting the Old value will cause this to dangle. Postpone 9980 // that until everything else is done. 9981 if (U == Old) 9982 continue; 9983 if (!Visited.insert(U).second) 9984 continue; 9985 if (PHINode *PN = dyn_cast<PHINode>(U)) 9986 SE->ConstantEvolutionLoopExitValue.erase(PN); 9987 SE->eraseValueFromMap(U); 9988 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9989 } 9990 // Delete the Old value. 9991 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9992 SE->ConstantEvolutionLoopExitValue.erase(PN); 9993 SE->eraseValueFromMap(Old); 9994 // this now dangles! 9995 } 9996 9997 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9998 : CallbackVH(V), SE(se) {} 9999 10000 //===----------------------------------------------------------------------===// 10001 // ScalarEvolution Class Implementation 10002 //===----------------------------------------------------------------------===// 10003 10004 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10005 AssumptionCache &AC, DominatorTree &DT, 10006 LoopInfo &LI) 10007 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10008 CouldNotCompute(new SCEVCouldNotCompute()), 10009 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 10010 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 10011 FirstUnknown(nullptr) { 10012 10013 // To use guards for proving predicates, we need to scan every instruction in 10014 // relevant basic blocks, and not just terminators. Doing this is a waste of 10015 // time if the IR does not actually contain any calls to 10016 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10017 // 10018 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10019 // to _add_ guards to the module when there weren't any before, and wants 10020 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10021 // efficient in lieu of being smart in that rather obscure case. 10022 10023 auto *GuardDecl = F.getParent()->getFunction( 10024 Intrinsic::getName(Intrinsic::experimental_guard)); 10025 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10026 } 10027 10028 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10029 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10030 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10031 ValueExprMap(std::move(Arg.ValueExprMap)), 10032 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10033 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 10034 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10035 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10036 PredicatedBackedgeTakenCounts( 10037 std::move(Arg.PredicatedBackedgeTakenCounts)), 10038 ConstantEvolutionLoopExitValue( 10039 std::move(Arg.ConstantEvolutionLoopExitValue)), 10040 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10041 LoopDispositions(std::move(Arg.LoopDispositions)), 10042 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10043 BlockDispositions(std::move(Arg.BlockDispositions)), 10044 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10045 SignedRanges(std::move(Arg.SignedRanges)), 10046 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10047 UniquePreds(std::move(Arg.UniquePreds)), 10048 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10049 FirstUnknown(Arg.FirstUnknown) { 10050 Arg.FirstUnknown = nullptr; 10051 } 10052 10053 ScalarEvolution::~ScalarEvolution() { 10054 // Iterate through all the SCEVUnknown instances and call their 10055 // destructors, so that they release their references to their values. 10056 for (SCEVUnknown *U = FirstUnknown; U;) { 10057 SCEVUnknown *Tmp = U; 10058 U = U->Next; 10059 Tmp->~SCEVUnknown(); 10060 } 10061 FirstUnknown = nullptr; 10062 10063 ExprValueMap.clear(); 10064 ValueExprMap.clear(); 10065 HasRecMap.clear(); 10066 10067 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10068 // that a loop had multiple computable exits. 10069 for (auto &BTCI : BackedgeTakenCounts) 10070 BTCI.second.clear(); 10071 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10072 BTCI.second.clear(); 10073 10074 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10075 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10076 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10077 } 10078 10079 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10080 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10081 } 10082 10083 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10084 const Loop *L) { 10085 // Print all inner loops first 10086 for (Loop *I : *L) 10087 PrintLoopInfo(OS, SE, I); 10088 10089 OS << "Loop "; 10090 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10091 OS << ": "; 10092 10093 SmallVector<BasicBlock *, 8> ExitBlocks; 10094 L->getExitBlocks(ExitBlocks); 10095 if (ExitBlocks.size() != 1) 10096 OS << "<multiple exits> "; 10097 10098 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10099 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10100 } else { 10101 OS << "Unpredictable backedge-taken count. "; 10102 } 10103 10104 OS << "\n" 10105 "Loop "; 10106 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10107 OS << ": "; 10108 10109 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10110 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10111 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10112 OS << ", actual taken count either this or zero."; 10113 } else { 10114 OS << "Unpredictable max backedge-taken count. "; 10115 } 10116 10117 OS << "\n" 10118 "Loop "; 10119 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10120 OS << ": "; 10121 10122 SCEVUnionPredicate Pred; 10123 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10124 if (!isa<SCEVCouldNotCompute>(PBT)) { 10125 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10126 OS << " Predicates:\n"; 10127 Pred.print(OS, 4); 10128 } else { 10129 OS << "Unpredictable predicated backedge-taken count. "; 10130 } 10131 OS << "\n"; 10132 10133 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10134 OS << "Loop "; 10135 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10136 OS << ": "; 10137 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10138 } 10139 } 10140 10141 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 10142 switch (LD) { 10143 case ScalarEvolution::LoopVariant: 10144 return "Variant"; 10145 case ScalarEvolution::LoopInvariant: 10146 return "Invariant"; 10147 case ScalarEvolution::LoopComputable: 10148 return "Computable"; 10149 } 10150 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 10151 } 10152 10153 void ScalarEvolution::print(raw_ostream &OS) const { 10154 // ScalarEvolution's implementation of the print method is to print 10155 // out SCEV values of all instructions that are interesting. Doing 10156 // this potentially causes it to create new SCEV objects though, 10157 // which technically conflicts with the const qualifier. This isn't 10158 // observable from outside the class though, so casting away the 10159 // const isn't dangerous. 10160 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10161 10162 OS << "Classifying expressions for: "; 10163 F.printAsOperand(OS, /*PrintType=*/false); 10164 OS << "\n"; 10165 for (Instruction &I : instructions(F)) 10166 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 10167 OS << I << '\n'; 10168 OS << " --> "; 10169 const SCEV *SV = SE.getSCEV(&I); 10170 SV->print(OS); 10171 if (!isa<SCEVCouldNotCompute>(SV)) { 10172 OS << " U: "; 10173 SE.getUnsignedRange(SV).print(OS); 10174 OS << " S: "; 10175 SE.getSignedRange(SV).print(OS); 10176 } 10177 10178 const Loop *L = LI.getLoopFor(I.getParent()); 10179 10180 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10181 if (AtUse != SV) { 10182 OS << " --> "; 10183 AtUse->print(OS); 10184 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10185 OS << " U: "; 10186 SE.getUnsignedRange(AtUse).print(OS); 10187 OS << " S: "; 10188 SE.getSignedRange(AtUse).print(OS); 10189 } 10190 } 10191 10192 if (L) { 10193 OS << "\t\t" "Exits: "; 10194 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10195 if (!SE.isLoopInvariant(ExitValue, L)) { 10196 OS << "<<Unknown>>"; 10197 } else { 10198 OS << *ExitValue; 10199 } 10200 10201 bool First = true; 10202 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10203 if (First) { 10204 OS << "\t\t" "LoopDispositions: { "; 10205 First = false; 10206 } else { 10207 OS << ", "; 10208 } 10209 10210 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10211 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10212 } 10213 10214 for (auto *InnerL : depth_first(L)) { 10215 if (InnerL == L) 10216 continue; 10217 if (First) { 10218 OS << "\t\t" "LoopDispositions: { "; 10219 First = false; 10220 } else { 10221 OS << ", "; 10222 } 10223 10224 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10225 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10226 } 10227 10228 OS << " }"; 10229 } 10230 10231 OS << "\n"; 10232 } 10233 10234 OS << "Determining loop execution counts for: "; 10235 F.printAsOperand(OS, /*PrintType=*/false); 10236 OS << "\n"; 10237 for (Loop *I : LI) 10238 PrintLoopInfo(OS, &SE, I); 10239 } 10240 10241 ScalarEvolution::LoopDisposition 10242 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10243 auto &Values = LoopDispositions[S]; 10244 for (auto &V : Values) { 10245 if (V.getPointer() == L) 10246 return V.getInt(); 10247 } 10248 Values.emplace_back(L, LoopVariant); 10249 LoopDisposition D = computeLoopDisposition(S, L); 10250 auto &Values2 = LoopDispositions[S]; 10251 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10252 if (V.getPointer() == L) { 10253 V.setInt(D); 10254 break; 10255 } 10256 } 10257 return D; 10258 } 10259 10260 ScalarEvolution::LoopDisposition 10261 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10262 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10263 case scConstant: 10264 return LoopInvariant; 10265 case scTruncate: 10266 case scZeroExtend: 10267 case scSignExtend: 10268 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10269 case scAddRecExpr: { 10270 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10271 10272 // If L is the addrec's loop, it's computable. 10273 if (AR->getLoop() == L) 10274 return LoopComputable; 10275 10276 // Add recurrences are never invariant in the function-body (null loop). 10277 if (!L) 10278 return LoopVariant; 10279 10280 // This recurrence is variant w.r.t. L if L contains AR's loop. 10281 if (L->contains(AR->getLoop())) 10282 return LoopVariant; 10283 10284 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10285 if (AR->getLoop()->contains(L)) 10286 return LoopInvariant; 10287 10288 // This recurrence is variant w.r.t. L if any of its operands 10289 // are variant. 10290 for (auto *Op : AR->operands()) 10291 if (!isLoopInvariant(Op, L)) 10292 return LoopVariant; 10293 10294 // Otherwise it's loop-invariant. 10295 return LoopInvariant; 10296 } 10297 case scAddExpr: 10298 case scMulExpr: 10299 case scUMaxExpr: 10300 case scSMaxExpr: { 10301 bool HasVarying = false; 10302 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10303 LoopDisposition D = getLoopDisposition(Op, L); 10304 if (D == LoopVariant) 10305 return LoopVariant; 10306 if (D == LoopComputable) 10307 HasVarying = true; 10308 } 10309 return HasVarying ? LoopComputable : LoopInvariant; 10310 } 10311 case scUDivExpr: { 10312 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10313 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10314 if (LD == LoopVariant) 10315 return LoopVariant; 10316 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10317 if (RD == LoopVariant) 10318 return LoopVariant; 10319 return (LD == LoopInvariant && RD == LoopInvariant) ? 10320 LoopInvariant : LoopComputable; 10321 } 10322 case scUnknown: 10323 // All non-instruction values are loop invariant. All instructions are loop 10324 // invariant if they are not contained in the specified loop. 10325 // Instructions are never considered invariant in the function body 10326 // (null loop) because they are defined within the "loop". 10327 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10328 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10329 return LoopInvariant; 10330 case scCouldNotCompute: 10331 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10332 } 10333 llvm_unreachable("Unknown SCEV kind!"); 10334 } 10335 10336 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10337 return getLoopDisposition(S, L) == LoopInvariant; 10338 } 10339 10340 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10341 return getLoopDisposition(S, L) == LoopComputable; 10342 } 10343 10344 ScalarEvolution::BlockDisposition 10345 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10346 auto &Values = BlockDispositions[S]; 10347 for (auto &V : Values) { 10348 if (V.getPointer() == BB) 10349 return V.getInt(); 10350 } 10351 Values.emplace_back(BB, DoesNotDominateBlock); 10352 BlockDisposition D = computeBlockDisposition(S, BB); 10353 auto &Values2 = BlockDispositions[S]; 10354 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10355 if (V.getPointer() == BB) { 10356 V.setInt(D); 10357 break; 10358 } 10359 } 10360 return D; 10361 } 10362 10363 ScalarEvolution::BlockDisposition 10364 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10365 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10366 case scConstant: 10367 return ProperlyDominatesBlock; 10368 case scTruncate: 10369 case scZeroExtend: 10370 case scSignExtend: 10371 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10372 case scAddRecExpr: { 10373 // This uses a "dominates" query instead of "properly dominates" query 10374 // to test for proper dominance too, because the instruction which 10375 // produces the addrec's value is a PHI, and a PHI effectively properly 10376 // dominates its entire containing block. 10377 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10378 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10379 return DoesNotDominateBlock; 10380 10381 // Fall through into SCEVNAryExpr handling. 10382 LLVM_FALLTHROUGH; 10383 } 10384 case scAddExpr: 10385 case scMulExpr: 10386 case scUMaxExpr: 10387 case scSMaxExpr: { 10388 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10389 bool Proper = true; 10390 for (const SCEV *NAryOp : NAry->operands()) { 10391 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10392 if (D == DoesNotDominateBlock) 10393 return DoesNotDominateBlock; 10394 if (D == DominatesBlock) 10395 Proper = false; 10396 } 10397 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10398 } 10399 case scUDivExpr: { 10400 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10401 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10402 BlockDisposition LD = getBlockDisposition(LHS, BB); 10403 if (LD == DoesNotDominateBlock) 10404 return DoesNotDominateBlock; 10405 BlockDisposition RD = getBlockDisposition(RHS, BB); 10406 if (RD == DoesNotDominateBlock) 10407 return DoesNotDominateBlock; 10408 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10409 ProperlyDominatesBlock : DominatesBlock; 10410 } 10411 case scUnknown: 10412 if (Instruction *I = 10413 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10414 if (I->getParent() == BB) 10415 return DominatesBlock; 10416 if (DT.properlyDominates(I->getParent(), BB)) 10417 return ProperlyDominatesBlock; 10418 return DoesNotDominateBlock; 10419 } 10420 return ProperlyDominatesBlock; 10421 case scCouldNotCompute: 10422 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10423 } 10424 llvm_unreachable("Unknown SCEV kind!"); 10425 } 10426 10427 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10428 return getBlockDisposition(S, BB) >= DominatesBlock; 10429 } 10430 10431 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10432 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10433 } 10434 10435 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10436 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10437 } 10438 10439 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10440 ValuesAtScopes.erase(S); 10441 LoopDispositions.erase(S); 10442 BlockDispositions.erase(S); 10443 UnsignedRanges.erase(S); 10444 SignedRanges.erase(S); 10445 ExprValueMap.erase(S); 10446 HasRecMap.erase(S); 10447 MinTrailingZerosCache.erase(S); 10448 10449 auto RemoveSCEVFromBackedgeMap = 10450 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10451 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10452 BackedgeTakenInfo &BEInfo = I->second; 10453 if (BEInfo.hasOperand(S, this)) { 10454 BEInfo.clear(); 10455 Map.erase(I++); 10456 } else 10457 ++I; 10458 } 10459 }; 10460 10461 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10462 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10463 } 10464 10465 void ScalarEvolution::verify() const { 10466 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10467 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10468 10469 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 10470 10471 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 10472 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 10473 const SCEV *visitConstant(const SCEVConstant *Constant) { 10474 return SE.getConstant(Constant->getAPInt()); 10475 } 10476 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10477 return SE.getUnknown(Expr->getValue()); 10478 } 10479 10480 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 10481 return SE.getCouldNotCompute(); 10482 } 10483 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 10484 }; 10485 10486 SCEVMapper SCM(SE2); 10487 10488 while (!LoopStack.empty()) { 10489 auto *L = LoopStack.pop_back_val(); 10490 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 10491 10492 auto *CurBECount = SCM.visit( 10493 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 10494 auto *NewBECount = SE2.getBackedgeTakenCount(L); 10495 10496 if (CurBECount == SE2.getCouldNotCompute() || 10497 NewBECount == SE2.getCouldNotCompute()) { 10498 // NB! This situation is legal, but is very suspicious -- whatever pass 10499 // change the loop to make a trip count go from could not compute to 10500 // computable or vice-versa *should have* invalidated SCEV. However, we 10501 // choose not to assert here (for now) since we don't want false 10502 // positives. 10503 continue; 10504 } 10505 10506 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 10507 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 10508 // not propagate undef aggressively). This means we can (and do) fail 10509 // verification in cases where a transform makes the trip count of a loop 10510 // go from "undef" to "undef+1" (say). The transform is fine, since in 10511 // both cases the loop iterates "undef" times, but SCEV thinks we 10512 // increased the trip count of the loop by 1 incorrectly. 10513 continue; 10514 } 10515 10516 if (SE.getTypeSizeInBits(CurBECount->getType()) > 10517 SE.getTypeSizeInBits(NewBECount->getType())) 10518 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 10519 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 10520 SE.getTypeSizeInBits(NewBECount->getType())) 10521 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 10522 10523 auto *ConstantDelta = 10524 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 10525 10526 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 10527 dbgs() << "Trip Count Changed!\n"; 10528 dbgs() << "Old: " << *CurBECount << "\n"; 10529 dbgs() << "New: " << *NewBECount << "\n"; 10530 dbgs() << "Delta: " << *ConstantDelta << "\n"; 10531 std::abort(); 10532 } 10533 } 10534 } 10535 10536 bool ScalarEvolution::invalidate( 10537 Function &F, const PreservedAnalyses &PA, 10538 FunctionAnalysisManager::Invalidator &Inv) { 10539 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10540 // of its dependencies is invalidated. 10541 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10542 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10543 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10544 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10545 Inv.invalidate<LoopAnalysis>(F, PA); 10546 } 10547 10548 AnalysisKey ScalarEvolutionAnalysis::Key; 10549 10550 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10551 FunctionAnalysisManager &AM) { 10552 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10553 AM.getResult<AssumptionAnalysis>(F), 10554 AM.getResult<DominatorTreeAnalysis>(F), 10555 AM.getResult<LoopAnalysis>(F)); 10556 } 10557 10558 PreservedAnalyses 10559 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10560 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10561 return PreservedAnalyses::all(); 10562 } 10563 10564 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10565 "Scalar Evolution Analysis", false, true) 10566 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10567 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10568 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10569 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10570 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10571 "Scalar Evolution Analysis", false, true) 10572 char ScalarEvolutionWrapperPass::ID = 0; 10573 10574 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10575 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10576 } 10577 10578 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10579 SE.reset(new ScalarEvolution( 10580 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10581 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10582 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10583 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10584 return false; 10585 } 10586 10587 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10588 10589 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10590 SE->print(OS); 10591 } 10592 10593 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10594 if (!VerifySCEV) 10595 return; 10596 10597 SE->verify(); 10598 } 10599 10600 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10601 AU.setPreservesAll(); 10602 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10603 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10604 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10605 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10606 } 10607 10608 const SCEVPredicate * 10609 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10610 const SCEVConstant *RHS) { 10611 FoldingSetNodeID ID; 10612 // Unique this node based on the arguments 10613 ID.AddInteger(SCEVPredicate::P_Equal); 10614 ID.AddPointer(LHS); 10615 ID.AddPointer(RHS); 10616 void *IP = nullptr; 10617 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10618 return S; 10619 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10620 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10621 UniquePreds.InsertNode(Eq, IP); 10622 return Eq; 10623 } 10624 10625 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10626 const SCEVAddRecExpr *AR, 10627 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10628 FoldingSetNodeID ID; 10629 // Unique this node based on the arguments 10630 ID.AddInteger(SCEVPredicate::P_Wrap); 10631 ID.AddPointer(AR); 10632 ID.AddInteger(AddedFlags); 10633 void *IP = nullptr; 10634 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10635 return S; 10636 auto *OF = new (SCEVAllocator) 10637 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10638 UniquePreds.InsertNode(OF, IP); 10639 return OF; 10640 } 10641 10642 namespace { 10643 10644 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10645 public: 10646 /// Rewrites \p S in the context of a loop L and the SCEV predication 10647 /// infrastructure. 10648 /// 10649 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10650 /// equivalences present in \p Pred. 10651 /// 10652 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10653 /// \p NewPreds such that the result will be an AddRecExpr. 10654 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10655 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10656 SCEVUnionPredicate *Pred) { 10657 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10658 return Rewriter.visit(S); 10659 } 10660 10661 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10662 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10663 SCEVUnionPredicate *Pred) 10664 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10665 10666 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10667 if (Pred) { 10668 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10669 for (auto *Pred : ExprPreds) 10670 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10671 if (IPred->getLHS() == Expr) 10672 return IPred->getRHS(); 10673 } 10674 10675 return Expr; 10676 } 10677 10678 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10679 const SCEV *Operand = visit(Expr->getOperand()); 10680 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10681 if (AR && AR->getLoop() == L && AR->isAffine()) { 10682 // This couldn't be folded because the operand didn't have the nuw 10683 // flag. Add the nusw flag as an assumption that we could make. 10684 const SCEV *Step = AR->getStepRecurrence(SE); 10685 Type *Ty = Expr->getType(); 10686 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10687 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10688 SE.getSignExtendExpr(Step, Ty), L, 10689 AR->getNoWrapFlags()); 10690 } 10691 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10692 } 10693 10694 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10695 const SCEV *Operand = visit(Expr->getOperand()); 10696 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10697 if (AR && AR->getLoop() == L && AR->isAffine()) { 10698 // This couldn't be folded because the operand didn't have the nsw 10699 // flag. Add the nssw flag as an assumption that we could make. 10700 const SCEV *Step = AR->getStepRecurrence(SE); 10701 Type *Ty = Expr->getType(); 10702 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10703 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10704 SE.getSignExtendExpr(Step, Ty), L, 10705 AR->getNoWrapFlags()); 10706 } 10707 return SE.getSignExtendExpr(Operand, Expr->getType()); 10708 } 10709 10710 private: 10711 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10712 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10713 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10714 if (!NewPreds) { 10715 // Check if we've already made this assumption. 10716 return Pred && Pred->implies(A); 10717 } 10718 NewPreds->insert(A); 10719 return true; 10720 } 10721 10722 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10723 SCEVUnionPredicate *Pred; 10724 const Loop *L; 10725 }; 10726 } // end anonymous namespace 10727 10728 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10729 SCEVUnionPredicate &Preds) { 10730 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10731 } 10732 10733 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10734 const SCEV *S, const Loop *L, 10735 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10736 10737 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10738 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10739 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10740 10741 if (!AddRec) 10742 return nullptr; 10743 10744 // Since the transformation was successful, we can now transfer the SCEV 10745 // predicates. 10746 for (auto *P : TransformPreds) 10747 Preds.insert(P); 10748 10749 return AddRec; 10750 } 10751 10752 /// SCEV predicates 10753 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10754 SCEVPredicateKind Kind) 10755 : FastID(ID), Kind(Kind) {} 10756 10757 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10758 const SCEVUnknown *LHS, 10759 const SCEVConstant *RHS) 10760 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10761 10762 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10763 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10764 10765 if (!Op) 10766 return false; 10767 10768 return Op->LHS == LHS && Op->RHS == RHS; 10769 } 10770 10771 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10772 10773 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10774 10775 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10776 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10777 } 10778 10779 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10780 const SCEVAddRecExpr *AR, 10781 IncrementWrapFlags Flags) 10782 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10783 10784 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10785 10786 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10787 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10788 10789 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10790 } 10791 10792 bool SCEVWrapPredicate::isAlwaysTrue() const { 10793 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10794 IncrementWrapFlags IFlags = Flags; 10795 10796 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10797 IFlags = clearFlags(IFlags, IncrementNSSW); 10798 10799 return IFlags == IncrementAnyWrap; 10800 } 10801 10802 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10803 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10804 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10805 OS << "<nusw>"; 10806 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10807 OS << "<nssw>"; 10808 OS << "\n"; 10809 } 10810 10811 SCEVWrapPredicate::IncrementWrapFlags 10812 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10813 ScalarEvolution &SE) { 10814 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10815 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10816 10817 // We can safely transfer the NSW flag as NSSW. 10818 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10819 ImpliedFlags = IncrementNSSW; 10820 10821 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10822 // If the increment is positive, the SCEV NUW flag will also imply the 10823 // WrapPredicate NUSW flag. 10824 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10825 if (Step->getValue()->getValue().isNonNegative()) 10826 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10827 } 10828 10829 return ImpliedFlags; 10830 } 10831 10832 /// Union predicates don't get cached so create a dummy set ID for it. 10833 SCEVUnionPredicate::SCEVUnionPredicate() 10834 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10835 10836 bool SCEVUnionPredicate::isAlwaysTrue() const { 10837 return all_of(Preds, 10838 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10839 } 10840 10841 ArrayRef<const SCEVPredicate *> 10842 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10843 auto I = SCEVToPreds.find(Expr); 10844 if (I == SCEVToPreds.end()) 10845 return ArrayRef<const SCEVPredicate *>(); 10846 return I->second; 10847 } 10848 10849 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10850 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10851 return all_of(Set->Preds, 10852 [this](const SCEVPredicate *I) { return this->implies(I); }); 10853 10854 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10855 if (ScevPredsIt == SCEVToPreds.end()) 10856 return false; 10857 auto &SCEVPreds = ScevPredsIt->second; 10858 10859 return any_of(SCEVPreds, 10860 [N](const SCEVPredicate *I) { return I->implies(N); }); 10861 } 10862 10863 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10864 10865 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10866 for (auto Pred : Preds) 10867 Pred->print(OS, Depth); 10868 } 10869 10870 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10871 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10872 for (auto Pred : Set->Preds) 10873 add(Pred); 10874 return; 10875 } 10876 10877 if (implies(N)) 10878 return; 10879 10880 const SCEV *Key = N->getExpr(); 10881 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10882 " associated expression!"); 10883 10884 SCEVToPreds[Key].push_back(N); 10885 Preds.push_back(N); 10886 } 10887 10888 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10889 Loop &L) 10890 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10891 10892 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10893 const SCEV *Expr = SE.getSCEV(V); 10894 RewriteEntry &Entry = RewriteMap[Expr]; 10895 10896 // If we already have an entry and the version matches, return it. 10897 if (Entry.second && Generation == Entry.first) 10898 return Entry.second; 10899 10900 // We found an entry but it's stale. Rewrite the stale entry 10901 // according to the current predicate. 10902 if (Entry.second) 10903 Expr = Entry.second; 10904 10905 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10906 Entry = {Generation, NewSCEV}; 10907 10908 return NewSCEV; 10909 } 10910 10911 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10912 if (!BackedgeCount) { 10913 SCEVUnionPredicate BackedgePred; 10914 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10915 addPredicate(BackedgePred); 10916 } 10917 return BackedgeCount; 10918 } 10919 10920 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10921 if (Preds.implies(&Pred)) 10922 return; 10923 Preds.add(&Pred); 10924 updateGeneration(); 10925 } 10926 10927 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10928 return Preds; 10929 } 10930 10931 void PredicatedScalarEvolution::updateGeneration() { 10932 // If the generation number wrapped recompute everything. 10933 if (++Generation == 0) { 10934 for (auto &II : RewriteMap) { 10935 const SCEV *Rewritten = II.second.second; 10936 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10937 } 10938 } 10939 } 10940 10941 void PredicatedScalarEvolution::setNoOverflow( 10942 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10943 const SCEV *Expr = getSCEV(V); 10944 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10945 10946 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10947 10948 // Clear the statically implied flags. 10949 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10950 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10951 10952 auto II = FlagsMap.insert({V, Flags}); 10953 if (!II.second) 10954 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10955 } 10956 10957 bool PredicatedScalarEvolution::hasNoOverflow( 10958 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10959 const SCEV *Expr = getSCEV(V); 10960 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10961 10962 Flags = SCEVWrapPredicate::clearFlags( 10963 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10964 10965 auto II = FlagsMap.find(V); 10966 10967 if (II != FlagsMap.end()) 10968 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10969 10970 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10971 } 10972 10973 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10974 const SCEV *Expr = this->getSCEV(V); 10975 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10976 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10977 10978 if (!New) 10979 return nullptr; 10980 10981 for (auto *P : NewPreds) 10982 Preds.add(P); 10983 10984 updateGeneration(); 10985 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10986 return New; 10987 } 10988 10989 PredicatedScalarEvolution::PredicatedScalarEvolution( 10990 const PredicatedScalarEvolution &Init) 10991 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10992 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10993 for (const auto &I : Init.FlagsMap) 10994 FlagsMap.insert(I); 10995 } 10996 10997 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10998 // For each block. 10999 for (auto *BB : L.getBlocks()) 11000 for (auto &I : *BB) { 11001 if (!SE.isSCEVable(I.getType())) 11002 continue; 11003 11004 auto *Expr = SE.getSCEV(&I); 11005 auto II = RewriteMap.find(Expr); 11006 11007 if (II == RewriteMap.end()) 11008 continue; 11009 11010 // Don't print things that are not interesting. 11011 if (II->second.second == Expr) 11012 continue; 11013 11014 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11015 OS.indent(Depth + 2) << *Expr << "\n"; 11016 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11017 } 11018 } 11019