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 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 // Compare addrec loop depths. 633 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 634 if (LLoop != RLoop) { 635 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 636 if (LDepth != RDepth) 637 return (int)LDepth - (int)RDepth; 638 } 639 640 // Addrec complexity grows with operand count. 641 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 642 if (LNumOps != RNumOps) 643 return (int)LNumOps - (int)RNumOps; 644 645 // Lexicographically compare. 646 for (unsigned i = 0; i != LNumOps; ++i) { 647 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 648 RA->getOperand(i), Depth + 1); 649 if (X != 0) 650 return X; 651 } 652 EqCacheSCEV.insert({LHS, RHS}); 653 return 0; 654 } 655 656 case scAddExpr: 657 case scMulExpr: 658 case scSMaxExpr: 659 case scUMaxExpr: { 660 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 661 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 662 663 // Lexicographically compare n-ary expressions. 664 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 665 if (LNumOps != RNumOps) 666 return (int)LNumOps - (int)RNumOps; 667 668 for (unsigned i = 0; i != LNumOps; ++i) { 669 if (i >= RNumOps) 670 return 1; 671 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 672 RC->getOperand(i), Depth + 1); 673 if (X != 0) 674 return X; 675 } 676 EqCacheSCEV.insert({LHS, RHS}); 677 return 0; 678 } 679 680 case scUDivExpr: { 681 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 682 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 683 684 // Lexicographically compare udiv expressions. 685 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 686 Depth + 1); 687 if (X != 0) 688 return X; 689 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), 690 Depth + 1); 691 if (X == 0) 692 EqCacheSCEV.insert({LHS, RHS}); 693 return X; 694 } 695 696 case scTruncate: 697 case scZeroExtend: 698 case scSignExtend: { 699 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 700 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 701 702 // Compare cast expressions by operand. 703 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 704 RC->getOperand(), Depth + 1); 705 if (X == 0) 706 EqCacheSCEV.insert({LHS, RHS}); 707 return X; 708 } 709 710 case scCouldNotCompute: 711 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 712 } 713 llvm_unreachable("Unknown SCEV kind!"); 714 } 715 716 /// Given a list of SCEV objects, order them by their complexity, and group 717 /// objects of the same complexity together by value. When this routine is 718 /// finished, we know that any duplicates in the vector are consecutive and that 719 /// complexity is monotonically increasing. 720 /// 721 /// Note that we go take special precautions to ensure that we get deterministic 722 /// results from this routine. In other words, we don't want the results of 723 /// this to depend on where the addresses of various SCEV objects happened to 724 /// land in memory. 725 /// 726 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 727 LoopInfo *LI) { 728 if (Ops.size() < 2) return; // Noop 729 730 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 731 if (Ops.size() == 2) { 732 // This is the common case, which also happens to be trivially simple. 733 // Special case it. 734 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 735 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) 736 std::swap(LHS, RHS); 737 return; 738 } 739 740 // Do the rough sort by complexity. 741 std::stable_sort(Ops.begin(), Ops.end(), 742 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { 743 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; 744 }); 745 746 // Now that we are sorted by complexity, group elements of the same 747 // complexity. Note that this is, at worst, N^2, but the vector is likely to 748 // be extremely short in practice. Note that we take this approach because we 749 // do not want to depend on the addresses of the objects we are grouping. 750 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 751 const SCEV *S = Ops[i]; 752 unsigned Complexity = S->getSCEVType(); 753 754 // If there are any objects of the same complexity and same value as this 755 // one, group them. 756 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 757 if (Ops[j] == S) { // Found a duplicate. 758 // Move it to immediately after i'th element. 759 std::swap(Ops[i+1], Ops[j]); 760 ++i; // no need to rescan it. 761 if (i == e-2) return; // Done! 762 } 763 } 764 } 765 } 766 767 // Returns the size of the SCEV S. 768 static inline int sizeOfSCEV(const SCEV *S) { 769 struct FindSCEVSize { 770 int Size; 771 FindSCEVSize() : Size(0) {} 772 773 bool follow(const SCEV *S) { 774 ++Size; 775 // Keep looking at all operands of S. 776 return true; 777 } 778 bool isDone() const { 779 return false; 780 } 781 }; 782 783 FindSCEVSize F; 784 SCEVTraversal<FindSCEVSize> ST(F); 785 ST.visitAll(S); 786 return F.Size; 787 } 788 789 namespace { 790 791 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 792 public: 793 // Computes the Quotient and Remainder of the division of Numerator by 794 // Denominator. 795 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 796 const SCEV *Denominator, const SCEV **Quotient, 797 const SCEV **Remainder) { 798 assert(Numerator && Denominator && "Uninitialized SCEV"); 799 800 SCEVDivision D(SE, Numerator, Denominator); 801 802 // Check for the trivial case here to avoid having to check for it in the 803 // rest of the code. 804 if (Numerator == Denominator) { 805 *Quotient = D.One; 806 *Remainder = D.Zero; 807 return; 808 } 809 810 if (Numerator->isZero()) { 811 *Quotient = D.Zero; 812 *Remainder = D.Zero; 813 return; 814 } 815 816 // A simple case when N/1. The quotient is N. 817 if (Denominator->isOne()) { 818 *Quotient = Numerator; 819 *Remainder = D.Zero; 820 return; 821 } 822 823 // Split the Denominator when it is a product. 824 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 825 const SCEV *Q, *R; 826 *Quotient = Numerator; 827 for (const SCEV *Op : T->operands()) { 828 divide(SE, *Quotient, Op, &Q, &R); 829 *Quotient = Q; 830 831 // Bail out when the Numerator is not divisible by one of the terms of 832 // the Denominator. 833 if (!R->isZero()) { 834 *Quotient = D.Zero; 835 *Remainder = Numerator; 836 return; 837 } 838 } 839 *Remainder = D.Zero; 840 return; 841 } 842 843 D.visit(Numerator); 844 *Quotient = D.Quotient; 845 *Remainder = D.Remainder; 846 } 847 848 // Except in the trivial case described above, we do not know how to divide 849 // Expr by Denominator for the following functions with empty implementation. 850 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 851 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 852 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 853 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 854 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 855 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 856 void visitUnknown(const SCEVUnknown *Numerator) {} 857 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 858 859 void visitConstant(const SCEVConstant *Numerator) { 860 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 861 APInt NumeratorVal = Numerator->getAPInt(); 862 APInt DenominatorVal = D->getAPInt(); 863 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 864 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 865 866 if (NumeratorBW > DenominatorBW) 867 DenominatorVal = DenominatorVal.sext(NumeratorBW); 868 else if (NumeratorBW < DenominatorBW) 869 NumeratorVal = NumeratorVal.sext(DenominatorBW); 870 871 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 872 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 873 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 874 Quotient = SE.getConstant(QuotientVal); 875 Remainder = SE.getConstant(RemainderVal); 876 return; 877 } 878 } 879 880 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 881 const SCEV *StartQ, *StartR, *StepQ, *StepR; 882 if (!Numerator->isAffine()) 883 return cannotDivide(Numerator); 884 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 885 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 886 // Bail out if the types do not match. 887 Type *Ty = Denominator->getType(); 888 if (Ty != StartQ->getType() || Ty != StartR->getType() || 889 Ty != StepQ->getType() || Ty != StepR->getType()) 890 return cannotDivide(Numerator); 891 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 892 Numerator->getNoWrapFlags()); 893 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 894 Numerator->getNoWrapFlags()); 895 } 896 897 void visitAddExpr(const SCEVAddExpr *Numerator) { 898 SmallVector<const SCEV *, 2> Qs, Rs; 899 Type *Ty = Denominator->getType(); 900 901 for (const SCEV *Op : Numerator->operands()) { 902 const SCEV *Q, *R; 903 divide(SE, Op, Denominator, &Q, &R); 904 905 // Bail out if types do not match. 906 if (Ty != Q->getType() || Ty != R->getType()) 907 return cannotDivide(Numerator); 908 909 Qs.push_back(Q); 910 Rs.push_back(R); 911 } 912 913 if (Qs.size() == 1) { 914 Quotient = Qs[0]; 915 Remainder = Rs[0]; 916 return; 917 } 918 919 Quotient = SE.getAddExpr(Qs); 920 Remainder = SE.getAddExpr(Rs); 921 } 922 923 void visitMulExpr(const SCEVMulExpr *Numerator) { 924 SmallVector<const SCEV *, 2> Qs; 925 Type *Ty = Denominator->getType(); 926 927 bool FoundDenominatorTerm = false; 928 for (const SCEV *Op : Numerator->operands()) { 929 // Bail out if types do not match. 930 if (Ty != Op->getType()) 931 return cannotDivide(Numerator); 932 933 if (FoundDenominatorTerm) { 934 Qs.push_back(Op); 935 continue; 936 } 937 938 // Check whether Denominator divides one of the product operands. 939 const SCEV *Q, *R; 940 divide(SE, Op, Denominator, &Q, &R); 941 if (!R->isZero()) { 942 Qs.push_back(Op); 943 continue; 944 } 945 946 // Bail out if types do not match. 947 if (Ty != Q->getType()) 948 return cannotDivide(Numerator); 949 950 FoundDenominatorTerm = true; 951 Qs.push_back(Q); 952 } 953 954 if (FoundDenominatorTerm) { 955 Remainder = Zero; 956 if (Qs.size() == 1) 957 Quotient = Qs[0]; 958 else 959 Quotient = SE.getMulExpr(Qs); 960 return; 961 } 962 963 if (!isa<SCEVUnknown>(Denominator)) 964 return cannotDivide(Numerator); 965 966 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 967 ValueToValueMap RewriteMap; 968 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 969 cast<SCEVConstant>(Zero)->getValue(); 970 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 971 972 if (Remainder->isZero()) { 973 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 974 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 975 cast<SCEVConstant>(One)->getValue(); 976 Quotient = 977 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 978 return; 979 } 980 981 // Quotient is (Numerator - Remainder) divided by Denominator. 982 const SCEV *Q, *R; 983 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 984 // This SCEV does not seem to simplify: fail the division here. 985 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 986 return cannotDivide(Numerator); 987 divide(SE, Diff, Denominator, &Q, &R); 988 if (R != Zero) 989 return cannotDivide(Numerator); 990 Quotient = Q; 991 } 992 993 private: 994 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 995 const SCEV *Denominator) 996 : SE(S), Denominator(Denominator) { 997 Zero = SE.getZero(Denominator->getType()); 998 One = SE.getOne(Denominator->getType()); 999 1000 // We generally do not know how to divide Expr by Denominator. We 1001 // initialize the division to a "cannot divide" state to simplify the rest 1002 // of the code. 1003 cannotDivide(Numerator); 1004 } 1005 1006 // Convenience function for giving up on the division. We set the quotient to 1007 // be equal to zero and the remainder to be equal to the numerator. 1008 void cannotDivide(const SCEV *Numerator) { 1009 Quotient = Zero; 1010 Remainder = Numerator; 1011 } 1012 1013 ScalarEvolution &SE; 1014 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1015 }; 1016 1017 } 1018 1019 //===----------------------------------------------------------------------===// 1020 // Simple SCEV method implementations 1021 //===----------------------------------------------------------------------===// 1022 1023 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1024 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1025 ScalarEvolution &SE, 1026 Type *ResultTy) { 1027 // Handle the simplest case efficiently. 1028 if (K == 1) 1029 return SE.getTruncateOrZeroExtend(It, ResultTy); 1030 1031 // We are using the following formula for BC(It, K): 1032 // 1033 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1034 // 1035 // Suppose, W is the bitwidth of the return value. We must be prepared for 1036 // overflow. Hence, we must assure that the result of our computation is 1037 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1038 // safe in modular arithmetic. 1039 // 1040 // However, this code doesn't use exactly that formula; the formula it uses 1041 // is something like the following, where T is the number of factors of 2 in 1042 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1043 // exponentiation: 1044 // 1045 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1046 // 1047 // This formula is trivially equivalent to the previous formula. However, 1048 // this formula can be implemented much more efficiently. The trick is that 1049 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1050 // arithmetic. To do exact division in modular arithmetic, all we have 1051 // to do is multiply by the inverse. Therefore, this step can be done at 1052 // width W. 1053 // 1054 // The next issue is how to safely do the division by 2^T. The way this 1055 // is done is by doing the multiplication step at a width of at least W + T 1056 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1057 // when we perform the division by 2^T (which is equivalent to a right shift 1058 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1059 // truncated out after the division by 2^T. 1060 // 1061 // In comparison to just directly using the first formula, this technique 1062 // is much more efficient; using the first formula requires W * K bits, 1063 // but this formula less than W + K bits. Also, the first formula requires 1064 // a division step, whereas this formula only requires multiplies and shifts. 1065 // 1066 // It doesn't matter whether the subtraction step is done in the calculation 1067 // width or the input iteration count's width; if the subtraction overflows, 1068 // the result must be zero anyway. We prefer here to do it in the width of 1069 // the induction variable because it helps a lot for certain cases; CodeGen 1070 // isn't smart enough to ignore the overflow, which leads to much less 1071 // efficient code if the width of the subtraction is wider than the native 1072 // register width. 1073 // 1074 // (It's possible to not widen at all by pulling out factors of 2 before 1075 // the multiplication; for example, K=2 can be calculated as 1076 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1077 // extra arithmetic, so it's not an obvious win, and it gets 1078 // much more complicated for K > 3.) 1079 1080 // Protection from insane SCEVs; this bound is conservative, 1081 // but it probably doesn't matter. 1082 if (K > 1000) 1083 return SE.getCouldNotCompute(); 1084 1085 unsigned W = SE.getTypeSizeInBits(ResultTy); 1086 1087 // Calculate K! / 2^T and T; we divide out the factors of two before 1088 // multiplying for calculating K! / 2^T to avoid overflow. 1089 // Other overflow doesn't matter because we only care about the bottom 1090 // W bits of the result. 1091 APInt OddFactorial(W, 1); 1092 unsigned T = 1; 1093 for (unsigned i = 3; i <= K; ++i) { 1094 APInt Mult(W, i); 1095 unsigned TwoFactors = Mult.countTrailingZeros(); 1096 T += TwoFactors; 1097 Mult.lshrInPlace(TwoFactors); 1098 OddFactorial *= Mult; 1099 } 1100 1101 // We need at least W + T bits for the multiplication step 1102 unsigned CalculationBits = W + T; 1103 1104 // Calculate 2^T, at width T+W. 1105 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1106 1107 // Calculate the multiplicative inverse of K! / 2^T; 1108 // this multiplication factor will perform the exact division by 1109 // K! / 2^T. 1110 APInt Mod = APInt::getSignedMinValue(W+1); 1111 APInt MultiplyFactor = OddFactorial.zext(W+1); 1112 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1113 MultiplyFactor = MultiplyFactor.trunc(W); 1114 1115 // Calculate the product, at width T+W 1116 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1117 CalculationBits); 1118 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1119 for (unsigned i = 1; i != K; ++i) { 1120 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1121 Dividend = SE.getMulExpr(Dividend, 1122 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1123 } 1124 1125 // Divide by 2^T 1126 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1127 1128 // Truncate the result, and divide by K! / 2^T. 1129 1130 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1131 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1132 } 1133 1134 /// Return the value of this chain of recurrences at the specified iteration 1135 /// number. We can evaluate this recurrence by multiplying each element in the 1136 /// chain by the binomial coefficient corresponding to it. In other words, we 1137 /// can evaluate {A,+,B,+,C,+,D} as: 1138 /// 1139 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1140 /// 1141 /// where BC(It, k) stands for binomial coefficient. 1142 /// 1143 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1144 ScalarEvolution &SE) const { 1145 const SCEV *Result = getStart(); 1146 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1147 // The computation is correct in the face of overflow provided that the 1148 // multiplication is performed _after_ the evaluation of the binomial 1149 // coefficient. 1150 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1151 if (isa<SCEVCouldNotCompute>(Coeff)) 1152 return Coeff; 1153 1154 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1155 } 1156 return Result; 1157 } 1158 1159 //===----------------------------------------------------------------------===// 1160 // SCEV Expression folder implementations 1161 //===----------------------------------------------------------------------===// 1162 1163 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1164 Type *Ty) { 1165 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1166 "This is not a truncating conversion!"); 1167 assert(isSCEVable(Ty) && 1168 "This is not a conversion to a SCEVable type!"); 1169 Ty = getEffectiveSCEVType(Ty); 1170 1171 FoldingSetNodeID ID; 1172 ID.AddInteger(scTruncate); 1173 ID.AddPointer(Op); 1174 ID.AddPointer(Ty); 1175 void *IP = nullptr; 1176 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1177 1178 // Fold if the operand is constant. 1179 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1180 return getConstant( 1181 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1182 1183 // trunc(trunc(x)) --> trunc(x) 1184 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1185 return getTruncateExpr(ST->getOperand(), Ty); 1186 1187 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1188 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1189 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1190 1191 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1192 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1193 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1194 1195 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1196 // eliminate all the truncates, or we replace other casts with truncates. 1197 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1198 SmallVector<const SCEV *, 4> Operands; 1199 bool hasTrunc = false; 1200 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1201 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1202 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1203 hasTrunc = isa<SCEVTruncateExpr>(S); 1204 Operands.push_back(S); 1205 } 1206 if (!hasTrunc) 1207 return getAddExpr(Operands); 1208 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1209 } 1210 1211 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1212 // eliminate all the truncates, or we replace other casts with truncates. 1213 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1214 SmallVector<const SCEV *, 4> Operands; 1215 bool hasTrunc = false; 1216 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1217 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1218 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1219 hasTrunc = isa<SCEVTruncateExpr>(S); 1220 Operands.push_back(S); 1221 } 1222 if (!hasTrunc) 1223 return getMulExpr(Operands); 1224 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1225 } 1226 1227 // If the input value is a chrec scev, truncate the chrec's operands. 1228 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1229 SmallVector<const SCEV *, 4> Operands; 1230 for (const SCEV *Op : AddRec->operands()) 1231 Operands.push_back(getTruncateExpr(Op, Ty)); 1232 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1233 } 1234 1235 // The cast wasn't folded; create an explicit cast node. We can reuse 1236 // the existing insert position since if we get here, we won't have 1237 // made any changes which would invalidate it. 1238 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1239 Op, Ty); 1240 UniqueSCEVs.InsertNode(S, IP); 1241 return S; 1242 } 1243 1244 // Get the limit of a recurrence such that incrementing by Step cannot cause 1245 // signed overflow as long as the value of the recurrence within the 1246 // loop does not exceed this limit before incrementing. 1247 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1248 ICmpInst::Predicate *Pred, 1249 ScalarEvolution *SE) { 1250 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1251 if (SE->isKnownPositive(Step)) { 1252 *Pred = ICmpInst::ICMP_SLT; 1253 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1254 SE->getSignedRange(Step).getSignedMax()); 1255 } 1256 if (SE->isKnownNegative(Step)) { 1257 *Pred = ICmpInst::ICMP_SGT; 1258 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1259 SE->getSignedRange(Step).getSignedMin()); 1260 } 1261 return nullptr; 1262 } 1263 1264 // Get the limit of a recurrence such that incrementing by Step cannot cause 1265 // unsigned overflow as long as the value of the recurrence within the loop does 1266 // not exceed this limit before incrementing. 1267 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1268 ICmpInst::Predicate *Pred, 1269 ScalarEvolution *SE) { 1270 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1271 *Pred = ICmpInst::ICMP_ULT; 1272 1273 return SE->getConstant(APInt::getMinValue(BitWidth) - 1274 SE->getUnsignedRange(Step).getUnsignedMax()); 1275 } 1276 1277 namespace { 1278 1279 struct ExtendOpTraitsBase { 1280 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)( 1281 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache); 1282 }; 1283 1284 // Used to make code generic over signed and unsigned overflow. 1285 template <typename ExtendOp> struct ExtendOpTraits { 1286 // Members present: 1287 // 1288 // static const SCEV::NoWrapFlags WrapType; 1289 // 1290 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1291 // 1292 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1293 // ICmpInst::Predicate *Pred, 1294 // ScalarEvolution *SE); 1295 }; 1296 1297 template <> 1298 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1299 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1300 1301 static const GetExtendExprTy GetExtendExpr; 1302 1303 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1304 ICmpInst::Predicate *Pred, 1305 ScalarEvolution *SE) { 1306 return getSignedOverflowLimitForStep(Step, Pred, SE); 1307 } 1308 }; 1309 1310 const ExtendOpTraitsBase::GetExtendExprTy 1311 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr = 1312 &ScalarEvolution::getSignExtendExprCached; 1313 1314 template <> 1315 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1316 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1317 1318 static const GetExtendExprTy GetExtendExpr; 1319 1320 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1321 ICmpInst::Predicate *Pred, 1322 ScalarEvolution *SE) { 1323 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1324 } 1325 }; 1326 1327 const ExtendOpTraitsBase::GetExtendExprTy 1328 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr = 1329 &ScalarEvolution::getZeroExtendExprCached; 1330 } 1331 1332 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1333 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1334 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1335 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1336 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1337 // expression "Step + sext/zext(PreIncAR)" is congruent with 1338 // "sext/zext(PostIncAR)" 1339 template <typename ExtendOpTy> 1340 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1341 ScalarEvolution *SE, 1342 ScalarEvolution::ExtendCacheTy &Cache) { 1343 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1344 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1345 1346 const Loop *L = AR->getLoop(); 1347 const SCEV *Start = AR->getStart(); 1348 const SCEV *Step = AR->getStepRecurrence(*SE); 1349 1350 // Check for a simple looking step prior to loop entry. 1351 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1352 if (!SA) 1353 return nullptr; 1354 1355 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1356 // subtraction is expensive. For this purpose, perform a quick and dirty 1357 // difference, by checking for Step in the operand list. 1358 SmallVector<const SCEV *, 4> DiffOps; 1359 for (const SCEV *Op : SA->operands()) 1360 if (Op != Step) 1361 DiffOps.push_back(Op); 1362 1363 if (DiffOps.size() == SA->getNumOperands()) 1364 return nullptr; 1365 1366 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1367 // `Step`: 1368 1369 // 1. NSW/NUW flags on the step increment. 1370 auto PreStartFlags = 1371 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1372 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1373 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1374 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1375 1376 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1377 // "S+X does not sign/unsign-overflow". 1378 // 1379 1380 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1381 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1382 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1383 return PreStart; 1384 1385 // 2. Direct overflow check on the step operation's expression. 1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1388 const SCEV *OperandExtendedStart = 1389 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache), 1390 (SE->*GetExtendExpr)(Step, WideTy, Cache)); 1391 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) { 1392 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1393 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1394 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1395 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1396 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1397 } 1398 return PreStart; 1399 } 1400 1401 // 3. Loop precondition. 1402 ICmpInst::Predicate Pred; 1403 const SCEV *OverflowLimit = 1404 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1405 1406 if (OverflowLimit && 1407 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1408 return PreStart; 1409 1410 return nullptr; 1411 } 1412 1413 // Get the normalized zero or sign extended expression for this AddRec's Start. 1414 template <typename ExtendOpTy> 1415 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1416 ScalarEvolution *SE, 1417 ScalarEvolution::ExtendCacheTy &Cache) { 1418 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1419 1420 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache); 1421 if (!PreStart) 1422 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache); 1423 1424 return SE->getAddExpr( 1425 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache), 1426 (SE->*GetExtendExpr)(PreStart, Ty, Cache)); 1427 } 1428 1429 // Try to prove away overflow by looking at "nearby" add recurrences. A 1430 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1431 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1432 // 1433 // Formally: 1434 // 1435 // {S,+,X} == {S-T,+,X} + T 1436 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1437 // 1438 // If ({S-T,+,X} + T) does not overflow ... (1) 1439 // 1440 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1441 // 1442 // If {S-T,+,X} does not overflow ... (2) 1443 // 1444 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1445 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1446 // 1447 // If (S-T)+T does not overflow ... (3) 1448 // 1449 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1450 // == {Ext(S),+,Ext(X)} == LHS 1451 // 1452 // Thus, if (1), (2) and (3) are true for some T, then 1453 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1454 // 1455 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1456 // does not overflow" restricted to the 0th iteration. Therefore we only need 1457 // to check for (1) and (2). 1458 // 1459 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1460 // is `Delta` (defined below). 1461 // 1462 template <typename ExtendOpTy> 1463 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1464 const SCEV *Step, 1465 const Loop *L) { 1466 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1467 1468 // We restrict `Start` to a constant to prevent SCEV from spending too much 1469 // time here. It is correct (but more expensive) to continue with a 1470 // non-constant `Start` and do a general SCEV subtraction to compute 1471 // `PreStart` below. 1472 // 1473 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1474 if (!StartC) 1475 return false; 1476 1477 APInt StartAI = StartC->getAPInt(); 1478 1479 for (unsigned Delta : {-2, -1, 1, 2}) { 1480 const SCEV *PreStart = getConstant(StartAI - Delta); 1481 1482 FoldingSetNodeID ID; 1483 ID.AddInteger(scAddRecExpr); 1484 ID.AddPointer(PreStart); 1485 ID.AddPointer(Step); 1486 ID.AddPointer(L); 1487 void *IP = nullptr; 1488 const auto *PreAR = 1489 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1490 1491 // Give up if we don't already have the add recurrence we need because 1492 // actually constructing an add recurrence is relatively expensive. 1493 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1494 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1495 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1496 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1497 DeltaS, &Pred, this); 1498 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1499 return true; 1500 } 1501 } 1502 1503 return false; 1504 } 1505 1506 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) { 1507 // Use the local cache to prevent exponential behavior of 1508 // getZeroExtendExprImpl. 1509 ExtendCacheTy Cache; 1510 return getZeroExtendExprCached(Op, Ty, Cache); 1511 } 1512 1513 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no 1514 /// related entry in the \p Cache, call getZeroExtendExprImpl and save 1515 /// the result in the \p Cache. 1516 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty, 1517 ExtendCacheTy &Cache) { 1518 auto It = Cache.find({Op, Ty}); 1519 if (It != Cache.end()) 1520 return It->second; 1521 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache); 1522 auto InsertResult = Cache.insert({{Op, Ty}, ZExt}); 1523 assert(InsertResult.second && "Expect the key was not in the cache"); 1524 (void)InsertResult; 1525 return ZExt; 1526 } 1527 1528 /// The real implementation of getZeroExtendExpr. 1529 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty, 1530 ExtendCacheTy &Cache) { 1531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1532 "This is not an extending conversion!"); 1533 assert(isSCEVable(Ty) && 1534 "This is not a conversion to a SCEVable type!"); 1535 Ty = getEffectiveSCEVType(Ty); 1536 1537 // Fold if the operand is constant. 1538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1539 return getConstant( 1540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1541 1542 // zext(zext(x)) --> zext(x) 1543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1544 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache); 1545 1546 // Before doing any expensive analysis, check to see if we've already 1547 // computed a SCEV for this Op and Ty. 1548 FoldingSetNodeID ID; 1549 ID.AddInteger(scZeroExtend); 1550 ID.AddPointer(Op); 1551 ID.AddPointer(Ty); 1552 void *IP = nullptr; 1553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1554 1555 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1556 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1557 // It's possible the bits taken off by the truncate were all zero bits. If 1558 // so, we should be able to simplify this further. 1559 const SCEV *X = ST->getOperand(); 1560 ConstantRange CR = getUnsignedRange(X); 1561 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1562 unsigned NewBits = getTypeSizeInBits(Ty); 1563 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1564 CR.zextOrTrunc(NewBits))) 1565 return getTruncateOrZeroExtend(X, Ty); 1566 } 1567 1568 // If the input value is a chrec scev, and we can prove that the value 1569 // did not overflow the old, smaller, value, we can zero extend all of the 1570 // operands (often constants). This allows analysis of something like 1571 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1572 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1573 if (AR->isAffine()) { 1574 const SCEV *Start = AR->getStart(); 1575 const SCEV *Step = AR->getStepRecurrence(*this); 1576 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1577 const Loop *L = AR->getLoop(); 1578 1579 if (!AR->hasNoUnsignedWrap()) { 1580 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1581 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1582 } 1583 1584 // If we have special knowledge that this addrec won't overflow, 1585 // we don't need to do any further analysis. 1586 if (AR->hasNoUnsignedWrap()) 1587 return getAddRecExpr( 1588 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1589 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1590 1591 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1592 // Note that this serves two purposes: It filters out loops that are 1593 // simply not analyzable, and it covers the case where this code is 1594 // being called from within backedge-taken count analysis, such that 1595 // attempting to ask for the backedge-taken count would likely result 1596 // in infinite recursion. In the later case, the analysis code will 1597 // cope with a conservative value, and it will take care to purge 1598 // that value once it has finished. 1599 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1600 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1601 // Manually compute the final value for AR, checking for 1602 // overflow. 1603 1604 // Check whether the backedge-taken count can be losslessly casted to 1605 // the addrec's type. The count is always unsigned. 1606 const SCEV *CastedMaxBECount = 1607 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1608 const SCEV *RecastedMaxBECount = 1609 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1610 if (MaxBECount == RecastedMaxBECount) { 1611 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1612 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1613 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1614 const SCEV *ZAdd = 1615 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache); 1616 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache); 1617 const SCEV *WideMaxBECount = 1618 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache); 1619 const SCEV *OperandExtendedAdd = getAddExpr( 1620 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached( 1621 Step, WideTy, Cache))); 1622 if (ZAdd == OperandExtendedAdd) { 1623 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1624 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1625 // Return the expression with the addrec on the outside. 1626 return getAddRecExpr( 1627 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1628 getZeroExtendExprCached(Step, Ty, Cache), L, 1629 AR->getNoWrapFlags()); 1630 } 1631 // Similar to above, only this time treat the step value as signed. 1632 // This covers loops that count down. 1633 OperandExtendedAdd = 1634 getAddExpr(WideStart, 1635 getMulExpr(WideMaxBECount, 1636 getSignExtendExpr(Step, WideTy))); 1637 if (ZAdd == OperandExtendedAdd) { 1638 // Cache knowledge of AR NW, which is propagated to this AddRec. 1639 // Negative step causes unsigned wrap, but it still can't self-wrap. 1640 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1641 // Return the expression with the addrec on the outside. 1642 return getAddRecExpr( 1643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1644 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1645 } 1646 } 1647 } 1648 1649 // Normally, in the cases we can prove no-overflow via a 1650 // backedge guarding condition, we can also compute a backedge 1651 // taken count for the loop. The exceptions are assumptions and 1652 // guards present in the loop -- SCEV is not great at exploiting 1653 // these to compute max backedge taken counts, but can still use 1654 // these to prove lack of overflow. Use this fact to avoid 1655 // doing extra work that may not pay off. 1656 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1657 !AC.assumptions().empty()) { 1658 // If the backedge is guarded by a comparison with the pre-inc 1659 // value the addrec is safe. Also, if the entry is guarded by 1660 // a comparison with the start value and the backedge is 1661 // guarded by a comparison with the post-inc value, the addrec 1662 // is safe. 1663 if (isKnownPositive(Step)) { 1664 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1665 getUnsignedRange(Step).getUnsignedMax()); 1666 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1667 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1668 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1669 AR->getPostIncExpr(*this), N))) { 1670 // Cache knowledge of AR NUW, which is propagated to this 1671 // AddRec. 1672 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1673 // Return the expression with the addrec on the outside. 1674 return getAddRecExpr( 1675 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1676 getZeroExtendExprCached(Step, Ty, Cache), L, 1677 AR->getNoWrapFlags()); 1678 } 1679 } else if (isKnownNegative(Step)) { 1680 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1681 getSignedRange(Step).getSignedMin()); 1682 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1683 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1684 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1685 AR->getPostIncExpr(*this), N))) { 1686 // Cache knowledge of AR NW, which is propagated to this 1687 // AddRec. Negative step causes unsigned wrap, but it 1688 // still can't self-wrap. 1689 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1690 // Return the expression with the addrec on the outside. 1691 return getAddRecExpr( 1692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1693 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1694 } 1695 } 1696 } 1697 1698 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1700 return getAddRecExpr( 1701 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache), 1702 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1703 } 1704 } 1705 1706 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1707 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1708 if (SA->hasNoUnsignedWrap()) { 1709 // If the addition does not unsign overflow then we can, by definition, 1710 // commute the zero extension with the addition operation. 1711 SmallVector<const SCEV *, 4> Ops; 1712 for (const auto *Op : SA->operands()) 1713 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache)); 1714 return getAddExpr(Ops, SCEV::FlagNUW); 1715 } 1716 } 1717 1718 // The cast wasn't folded; create an explicit cast node. 1719 // Recompute the insert position, as it may have been invalidated. 1720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1721 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1722 Op, Ty); 1723 UniqueSCEVs.InsertNode(S, IP); 1724 return S; 1725 } 1726 1727 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) { 1728 // Use the local cache to prevent exponential behavior of 1729 // getSignExtendExprImpl. 1730 ExtendCacheTy Cache; 1731 return getSignExtendExprCached(Op, Ty, Cache); 1732 } 1733 1734 /// Query \p Cache before calling getSignExtendExprImpl. If there is no 1735 /// related entry in the \p Cache, call getSignExtendExprImpl and save 1736 /// the result in the \p Cache. 1737 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty, 1738 ExtendCacheTy &Cache) { 1739 auto It = Cache.find({Op, Ty}); 1740 if (It != Cache.end()) 1741 return It->second; 1742 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache); 1743 auto InsertResult = Cache.insert({{Op, Ty}, SExt}); 1744 assert(InsertResult.second && "Expect the key was not in the cache"); 1745 (void)InsertResult; 1746 return SExt; 1747 } 1748 1749 /// The real implementation of getSignExtendExpr. 1750 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty, 1751 ExtendCacheTy &Cache) { 1752 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1753 "This is not an extending conversion!"); 1754 assert(isSCEVable(Ty) && 1755 "This is not a conversion to a SCEVable type!"); 1756 Ty = getEffectiveSCEVType(Ty); 1757 1758 // Fold if the operand is constant. 1759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1760 return getConstant( 1761 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1762 1763 // sext(sext(x)) --> sext(x) 1764 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1765 return getSignExtendExprCached(SS->getOperand(), Ty, Cache); 1766 1767 // sext(zext(x)) --> zext(x) 1768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1769 return getZeroExtendExpr(SZ->getOperand(), Ty); 1770 1771 // Before doing any expensive analysis, check to see if we've already 1772 // computed a SCEV for this Op and Ty. 1773 FoldingSetNodeID ID; 1774 ID.AddInteger(scSignExtend); 1775 ID.AddPointer(Op); 1776 ID.AddPointer(Ty); 1777 void *IP = nullptr; 1778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1779 1780 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1781 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1782 // It's possible the bits taken off by the truncate were all sign bits. If 1783 // so, we should be able to simplify this further. 1784 const SCEV *X = ST->getOperand(); 1785 ConstantRange CR = getSignedRange(X); 1786 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1787 unsigned NewBits = getTypeSizeInBits(Ty); 1788 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1789 CR.sextOrTrunc(NewBits))) 1790 return getTruncateOrSignExtend(X, Ty); 1791 } 1792 1793 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1794 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1795 if (SA->getNumOperands() == 2) { 1796 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1797 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1798 if (SMul && SC1) { 1799 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1800 const APInt &C1 = SC1->getAPInt(); 1801 const APInt &C2 = SC2->getAPInt(); 1802 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1803 C2.ugt(C1) && C2.isPowerOf2()) 1804 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache), 1805 getSignExtendExprCached(SMul, Ty, Cache)); 1806 } 1807 } 1808 } 1809 1810 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1811 if (SA->hasNoSignedWrap()) { 1812 // If the addition does not sign overflow then we can, by definition, 1813 // commute the sign extension with the addition operation. 1814 SmallVector<const SCEV *, 4> Ops; 1815 for (const auto *Op : SA->operands()) 1816 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache)); 1817 return getAddExpr(Ops, SCEV::FlagNSW); 1818 } 1819 } 1820 // If the input value is a chrec scev, and we can prove that the value 1821 // did not overflow the old, smaller, value, we can sign extend all of the 1822 // operands (often constants). This allows analysis of something like 1823 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1824 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1825 if (AR->isAffine()) { 1826 const SCEV *Start = AR->getStart(); 1827 const SCEV *Step = AR->getStepRecurrence(*this); 1828 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1829 const Loop *L = AR->getLoop(); 1830 1831 if (!AR->hasNoSignedWrap()) { 1832 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1833 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1834 } 1835 1836 // If we have special knowledge that this addrec won't overflow, 1837 // we don't need to do any further analysis. 1838 if (AR->hasNoSignedWrap()) 1839 return getAddRecExpr( 1840 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1841 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW); 1842 1843 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1844 // Note that this serves two purposes: It filters out loops that are 1845 // simply not analyzable, and it covers the case where this code is 1846 // being called from within backedge-taken count analysis, such that 1847 // attempting to ask for the backedge-taken count would likely result 1848 // in infinite recursion. In the later case, the analysis code will 1849 // cope with a conservative value, and it will take care to purge 1850 // that value once it has finished. 1851 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1852 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1853 // Manually compute the final value for AR, checking for 1854 // overflow. 1855 1856 // Check whether the backedge-taken count can be losslessly casted to 1857 // the addrec's type. The count is always unsigned. 1858 const SCEV *CastedMaxBECount = 1859 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1860 const SCEV *RecastedMaxBECount = 1861 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1862 if (MaxBECount == RecastedMaxBECount) { 1863 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1864 // Check whether Start+Step*MaxBECount has no signed overflow. 1865 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1866 const SCEV *SAdd = 1867 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache); 1868 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache); 1869 const SCEV *WideMaxBECount = 1870 getZeroExtendExpr(CastedMaxBECount, WideTy); 1871 const SCEV *OperandExtendedAdd = getAddExpr( 1872 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached( 1873 Step, WideTy, Cache))); 1874 if (SAdd == OperandExtendedAdd) { 1875 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1877 // Return the expression with the addrec on the outside. 1878 return getAddRecExpr( 1879 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1880 getSignExtendExprCached(Step, Ty, Cache), L, 1881 AR->getNoWrapFlags()); 1882 } 1883 // Similar to above, only this time treat the step value as unsigned. 1884 // This covers loops that count up with an unsigned step. 1885 OperandExtendedAdd = 1886 getAddExpr(WideStart, 1887 getMulExpr(WideMaxBECount, 1888 getZeroExtendExpr(Step, WideTy))); 1889 if (SAdd == OperandExtendedAdd) { 1890 // If AR wraps around then 1891 // 1892 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1893 // => SAdd != OperandExtendedAdd 1894 // 1895 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1896 // (SAdd == OperandExtendedAdd => AR is NW) 1897 1898 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1899 1900 // Return the expression with the addrec on the outside. 1901 return getAddRecExpr( 1902 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1903 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1904 } 1905 } 1906 } 1907 1908 // Normally, in the cases we can prove no-overflow via a 1909 // backedge guarding condition, we can also compute a backedge 1910 // taken count for the loop. The exceptions are assumptions and 1911 // guards present in the loop -- SCEV is not great at exploiting 1912 // these to compute max backedge taken counts, but can still use 1913 // these to prove lack of overflow. Use this fact to avoid 1914 // doing extra work that may not pay off. 1915 1916 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1917 !AC.assumptions().empty()) { 1918 // If the backedge is guarded by a comparison with the pre-inc 1919 // value the addrec is safe. Also, if the entry is guarded by 1920 // a comparison with the start value and the backedge is 1921 // guarded by a comparison with the post-inc value, the addrec 1922 // is safe. 1923 ICmpInst::Predicate Pred; 1924 const SCEV *OverflowLimit = 1925 getSignedOverflowLimitForStep(Step, &Pred, this); 1926 if (OverflowLimit && 1927 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1928 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1929 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1930 OverflowLimit)))) { 1931 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1932 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1933 return getAddRecExpr( 1934 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1935 getSignExtendExprCached(Step, Ty, Cache), L, 1936 AR->getNoWrapFlags()); 1937 } 1938 } 1939 1940 // If Start and Step are constants, check if we can apply this 1941 // transformation: 1942 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1943 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1944 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1945 if (SC1 && SC2) { 1946 const APInt &C1 = SC1->getAPInt(); 1947 const APInt &C2 = SC2->getAPInt(); 1948 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1949 C2.isPowerOf2()) { 1950 Start = getSignExtendExprCached(Start, Ty, Cache); 1951 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1952 AR->getNoWrapFlags()); 1953 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache)); 1954 } 1955 } 1956 1957 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1958 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1959 return getAddRecExpr( 1960 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache), 1961 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags()); 1962 } 1963 } 1964 1965 // If the input value is provably positive and we could not simplify 1966 // away the sext build a zext instead. 1967 if (isKnownNonNegative(Op)) 1968 return getZeroExtendExpr(Op, Ty); 1969 1970 // The cast wasn't folded; create an explicit cast node. 1971 // Recompute the insert position, as it may have been invalidated. 1972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1973 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1974 Op, Ty); 1975 UniqueSCEVs.InsertNode(S, IP); 1976 return S; 1977 } 1978 1979 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1980 /// unspecified bits out to the given type. 1981 /// 1982 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1983 Type *Ty) { 1984 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1985 "This is not an extending conversion!"); 1986 assert(isSCEVable(Ty) && 1987 "This is not a conversion to a SCEVable type!"); 1988 Ty = getEffectiveSCEVType(Ty); 1989 1990 // Sign-extend negative constants. 1991 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1992 if (SC->getAPInt().isNegative()) 1993 return getSignExtendExpr(Op, Ty); 1994 1995 // Peel off a truncate cast. 1996 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1997 const SCEV *NewOp = T->getOperand(); 1998 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1999 return getAnyExtendExpr(NewOp, Ty); 2000 return getTruncateOrNoop(NewOp, Ty); 2001 } 2002 2003 // Next try a zext cast. If the cast is folded, use it. 2004 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2005 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2006 return ZExt; 2007 2008 // Next try a sext cast. If the cast is folded, use it. 2009 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2010 if (!isa<SCEVSignExtendExpr>(SExt)) 2011 return SExt; 2012 2013 // Force the cast to be folded into the operands of an addrec. 2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2015 SmallVector<const SCEV *, 4> Ops; 2016 for (const SCEV *Op : AR->operands()) 2017 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2018 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2019 } 2020 2021 // If the expression is obviously signed, use the sext cast value. 2022 if (isa<SCEVSMaxExpr>(Op)) 2023 return SExt; 2024 2025 // Absent any other information, use the zext cast value. 2026 return ZExt; 2027 } 2028 2029 /// Process the given Ops list, which is a list of operands to be added under 2030 /// the given scale, update the given map. This is a helper function for 2031 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2032 /// that would form an add expression like this: 2033 /// 2034 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2035 /// 2036 /// where A and B are constants, update the map with these values: 2037 /// 2038 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2039 /// 2040 /// and add 13 + A*B*29 to AccumulatedConstant. 2041 /// This will allow getAddRecExpr to produce this: 2042 /// 2043 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2044 /// 2045 /// This form often exposes folding opportunities that are hidden in 2046 /// the original operand list. 2047 /// 2048 /// Return true iff it appears that any interesting folding opportunities 2049 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2050 /// the common case where no interesting opportunities are present, and 2051 /// is also used as a check to avoid infinite recursion. 2052 /// 2053 static bool 2054 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2055 SmallVectorImpl<const SCEV *> &NewOps, 2056 APInt &AccumulatedConstant, 2057 const SCEV *const *Ops, size_t NumOperands, 2058 const APInt &Scale, 2059 ScalarEvolution &SE) { 2060 bool Interesting = false; 2061 2062 // Iterate over the add operands. They are sorted, with constants first. 2063 unsigned i = 0; 2064 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2065 ++i; 2066 // Pull a buried constant out to the outside. 2067 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2068 Interesting = true; 2069 AccumulatedConstant += Scale * C->getAPInt(); 2070 } 2071 2072 // Next comes everything else. We're especially interested in multiplies 2073 // here, but they're in the middle, so just visit the rest with one loop. 2074 for (; i != NumOperands; ++i) { 2075 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2076 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2077 APInt NewScale = 2078 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2079 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2080 // A multiplication of a constant with another add; recurse. 2081 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2082 Interesting |= 2083 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2084 Add->op_begin(), Add->getNumOperands(), 2085 NewScale, SE); 2086 } else { 2087 // A multiplication of a constant with some other value. Update 2088 // the map. 2089 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2090 const SCEV *Key = SE.getMulExpr(MulOps); 2091 auto Pair = M.insert({Key, NewScale}); 2092 if (Pair.second) { 2093 NewOps.push_back(Pair.first->first); 2094 } else { 2095 Pair.first->second += NewScale; 2096 // The map already had an entry for this value, which may indicate 2097 // a folding opportunity. 2098 Interesting = true; 2099 } 2100 } 2101 } else { 2102 // An ordinary operand. Update the map. 2103 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2104 M.insert({Ops[i], Scale}); 2105 if (Pair.second) { 2106 NewOps.push_back(Pair.first->first); 2107 } else { 2108 Pair.first->second += Scale; 2109 // The map already had an entry for this value, which may indicate 2110 // a folding opportunity. 2111 Interesting = true; 2112 } 2113 } 2114 } 2115 2116 return Interesting; 2117 } 2118 2119 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2120 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2121 // can't-overflow flags for the operation if possible. 2122 static SCEV::NoWrapFlags 2123 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2124 const SmallVectorImpl<const SCEV *> &Ops, 2125 SCEV::NoWrapFlags Flags) { 2126 using namespace std::placeholders; 2127 typedef OverflowingBinaryOperator OBO; 2128 2129 bool CanAnalyze = 2130 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2131 (void)CanAnalyze; 2132 assert(CanAnalyze && "don't call from other places!"); 2133 2134 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2135 SCEV::NoWrapFlags SignOrUnsignWrap = 2136 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2137 2138 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2139 auto IsKnownNonNegative = [&](const SCEV *S) { 2140 return SE->isKnownNonNegative(S); 2141 }; 2142 2143 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2144 Flags = 2145 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2146 2147 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2148 2149 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2150 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2151 2152 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2153 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2154 2155 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2156 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2157 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2158 Instruction::Add, C, OBO::NoSignedWrap); 2159 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2160 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2161 } 2162 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2163 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2164 Instruction::Add, C, OBO::NoUnsignedWrap); 2165 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2167 } 2168 } 2169 2170 return Flags; 2171 } 2172 2173 /// Get a canonical add expression, or something simpler if possible. 2174 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2175 SCEV::NoWrapFlags Flags, 2176 unsigned Depth) { 2177 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2178 "only nuw or nsw allowed"); 2179 assert(!Ops.empty() && "Cannot get empty add!"); 2180 if (Ops.size() == 1) return Ops[0]; 2181 #ifndef NDEBUG 2182 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2183 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2184 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2185 "SCEVAddExpr operand types don't match!"); 2186 #endif 2187 2188 // Sort by complexity, this groups all similar expression types together. 2189 GroupByComplexity(Ops, &LI); 2190 2191 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2192 2193 // If there are any constants, fold them together. 2194 unsigned Idx = 0; 2195 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2196 ++Idx; 2197 assert(Idx < Ops.size()); 2198 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2199 // We found two constants, fold them together! 2200 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2201 if (Ops.size() == 2) return Ops[0]; 2202 Ops.erase(Ops.begin()+1); // Erase the folded element 2203 LHSC = cast<SCEVConstant>(Ops[0]); 2204 } 2205 2206 // If we are left with a constant zero being added, strip it off. 2207 if (LHSC->getValue()->isZero()) { 2208 Ops.erase(Ops.begin()); 2209 --Idx; 2210 } 2211 2212 if (Ops.size() == 1) return Ops[0]; 2213 } 2214 2215 // Limit recursion calls depth 2216 if (Depth > MaxAddExprDepth) 2217 return getOrCreateAddExpr(Ops, Flags); 2218 2219 // Okay, check to see if the same value occurs in the operand list more than 2220 // once. If so, merge them together into an multiply expression. Since we 2221 // sorted the list, these values are required to be adjacent. 2222 Type *Ty = Ops[0]->getType(); 2223 bool FoundMatch = false; 2224 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2225 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2226 // Scan ahead to count how many equal operands there are. 2227 unsigned Count = 2; 2228 while (i+Count != e && Ops[i+Count] == Ops[i]) 2229 ++Count; 2230 // Merge the values into a multiply. 2231 const SCEV *Scale = getConstant(Ty, Count); 2232 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2233 if (Ops.size() == Count) 2234 return Mul; 2235 Ops[i] = Mul; 2236 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2237 --i; e -= Count - 1; 2238 FoundMatch = true; 2239 } 2240 if (FoundMatch) 2241 return getAddExpr(Ops, Flags); 2242 2243 // Check for truncates. If all the operands are truncated from the same 2244 // type, see if factoring out the truncate would permit the result to be 2245 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2246 // if the contents of the resulting outer trunc fold to something simple. 2247 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2248 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2249 Type *DstType = Trunc->getType(); 2250 Type *SrcType = Trunc->getOperand()->getType(); 2251 SmallVector<const SCEV *, 8> LargeOps; 2252 bool Ok = true; 2253 // Check all the operands to see if they can be represented in the 2254 // source type of the truncate. 2255 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2256 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2257 if (T->getOperand()->getType() != SrcType) { 2258 Ok = false; 2259 break; 2260 } 2261 LargeOps.push_back(T->getOperand()); 2262 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2263 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2264 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2265 SmallVector<const SCEV *, 8> LargeMulOps; 2266 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2267 if (const SCEVTruncateExpr *T = 2268 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2269 if (T->getOperand()->getType() != SrcType) { 2270 Ok = false; 2271 break; 2272 } 2273 LargeMulOps.push_back(T->getOperand()); 2274 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2275 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2276 } else { 2277 Ok = false; 2278 break; 2279 } 2280 } 2281 if (Ok) 2282 LargeOps.push_back(getMulExpr(LargeMulOps)); 2283 } else { 2284 Ok = false; 2285 break; 2286 } 2287 } 2288 if (Ok) { 2289 // Evaluate the expression in the larger type. 2290 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2291 // If it folds to something simple, use it. Otherwise, don't. 2292 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2293 return getTruncateExpr(Fold, DstType); 2294 } 2295 } 2296 2297 // Skip past any other cast SCEVs. 2298 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2299 ++Idx; 2300 2301 // If there are add operands they would be next. 2302 if (Idx < Ops.size()) { 2303 bool DeletedAdd = false; 2304 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2305 if (Ops.size() > AddOpsInlineThreshold || 2306 Add->getNumOperands() > AddOpsInlineThreshold) 2307 break; 2308 // If we have an add, expand the add operands onto the end of the operands 2309 // list. 2310 Ops.erase(Ops.begin()+Idx); 2311 Ops.append(Add->op_begin(), Add->op_end()); 2312 DeletedAdd = true; 2313 } 2314 2315 // If we deleted at least one add, we added operands to the end of the list, 2316 // and they are not necessarily sorted. Recurse to resort and resimplify 2317 // any operands we just acquired. 2318 if (DeletedAdd) 2319 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2320 } 2321 2322 // Skip over the add expression until we get to a multiply. 2323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2324 ++Idx; 2325 2326 // Check to see if there are any folding opportunities present with 2327 // operands multiplied by constant values. 2328 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2329 uint64_t BitWidth = getTypeSizeInBits(Ty); 2330 DenseMap<const SCEV *, APInt> M; 2331 SmallVector<const SCEV *, 8> NewOps; 2332 APInt AccumulatedConstant(BitWidth, 0); 2333 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2334 Ops.data(), Ops.size(), 2335 APInt(BitWidth, 1), *this)) { 2336 struct APIntCompare { 2337 bool operator()(const APInt &LHS, const APInt &RHS) const { 2338 return LHS.ult(RHS); 2339 } 2340 }; 2341 2342 // Some interesting folding opportunity is present, so its worthwhile to 2343 // re-generate the operands list. Group the operands by constant scale, 2344 // to avoid multiplying by the same constant scale multiple times. 2345 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2346 for (const SCEV *NewOp : NewOps) 2347 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2348 // Re-generate the operands list. 2349 Ops.clear(); 2350 if (AccumulatedConstant != 0) 2351 Ops.push_back(getConstant(AccumulatedConstant)); 2352 for (auto &MulOp : MulOpLists) 2353 if (MulOp.first != 0) 2354 Ops.push_back(getMulExpr( 2355 getConstant(MulOp.first), 2356 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1))); 2357 if (Ops.empty()) 2358 return getZero(Ty); 2359 if (Ops.size() == 1) 2360 return Ops[0]; 2361 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2362 } 2363 } 2364 2365 // If we are adding something to a multiply expression, make sure the 2366 // something is not already an operand of the multiply. If so, merge it into 2367 // the multiply. 2368 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2369 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2370 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2371 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2372 if (isa<SCEVConstant>(MulOpSCEV)) 2373 continue; 2374 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2375 if (MulOpSCEV == Ops[AddOp]) { 2376 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2377 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2378 if (Mul->getNumOperands() != 2) { 2379 // If the multiply has more than two operands, we must get the 2380 // Y*Z term. 2381 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2382 Mul->op_begin()+MulOp); 2383 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2384 InnerMul = getMulExpr(MulOps); 2385 } 2386 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2387 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2388 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2389 if (Ops.size() == 2) return OuterMul; 2390 if (AddOp < Idx) { 2391 Ops.erase(Ops.begin()+AddOp); 2392 Ops.erase(Ops.begin()+Idx-1); 2393 } else { 2394 Ops.erase(Ops.begin()+Idx); 2395 Ops.erase(Ops.begin()+AddOp-1); 2396 } 2397 Ops.push_back(OuterMul); 2398 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2399 } 2400 2401 // Check this multiply against other multiplies being added together. 2402 for (unsigned OtherMulIdx = Idx+1; 2403 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2404 ++OtherMulIdx) { 2405 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2406 // If MulOp occurs in OtherMul, we can fold the two multiplies 2407 // together. 2408 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2409 OMulOp != e; ++OMulOp) 2410 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2411 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2412 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2413 if (Mul->getNumOperands() != 2) { 2414 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2415 Mul->op_begin()+MulOp); 2416 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2417 InnerMul1 = getMulExpr(MulOps); 2418 } 2419 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2420 if (OtherMul->getNumOperands() != 2) { 2421 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2422 OtherMul->op_begin()+OMulOp); 2423 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2424 InnerMul2 = getMulExpr(MulOps); 2425 } 2426 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2427 const SCEV *InnerMulSum = 2428 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2429 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2430 if (Ops.size() == 2) return OuterMul; 2431 Ops.erase(Ops.begin()+Idx); 2432 Ops.erase(Ops.begin()+OtherMulIdx-1); 2433 Ops.push_back(OuterMul); 2434 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2435 } 2436 } 2437 } 2438 } 2439 2440 // If there are any add recurrences in the operands list, see if any other 2441 // added values are loop invariant. If so, we can fold them into the 2442 // recurrence. 2443 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2444 ++Idx; 2445 2446 // Scan over all recurrences, trying to fold loop invariants into them. 2447 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2448 // Scan all of the other operands to this add and add them to the vector if 2449 // they are loop invariant w.r.t. the recurrence. 2450 SmallVector<const SCEV *, 8> LIOps; 2451 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2452 const Loop *AddRecLoop = AddRec->getLoop(); 2453 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2454 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2455 LIOps.push_back(Ops[i]); 2456 Ops.erase(Ops.begin()+i); 2457 --i; --e; 2458 } 2459 2460 // If we found some loop invariants, fold them into the recurrence. 2461 if (!LIOps.empty()) { 2462 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2463 LIOps.push_back(AddRec->getStart()); 2464 2465 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2466 AddRec->op_end()); 2467 // This follows from the fact that the no-wrap flags on the outer add 2468 // expression are applicable on the 0th iteration, when the add recurrence 2469 // will be equal to its start value. 2470 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2471 2472 // Build the new addrec. Propagate the NUW and NSW flags if both the 2473 // outer add and the inner addrec are guaranteed to have no overflow. 2474 // Always propagate NW. 2475 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2476 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2477 2478 // If all of the other operands were loop invariant, we are done. 2479 if (Ops.size() == 1) return NewRec; 2480 2481 // Otherwise, add the folded AddRec by the non-invariant parts. 2482 for (unsigned i = 0;; ++i) 2483 if (Ops[i] == AddRec) { 2484 Ops[i] = NewRec; 2485 break; 2486 } 2487 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2488 } 2489 2490 // Okay, if there weren't any loop invariants to be folded, check to see if 2491 // there are multiple AddRec's with the same loop induction variable being 2492 // added together. If so, we can fold them. 2493 for (unsigned OtherIdx = Idx+1; 2494 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2495 ++OtherIdx) 2496 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2497 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2498 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2499 AddRec->op_end()); 2500 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2501 ++OtherIdx) 2502 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2503 if (OtherAddRec->getLoop() == AddRecLoop) { 2504 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2505 i != e; ++i) { 2506 if (i >= AddRecOps.size()) { 2507 AddRecOps.append(OtherAddRec->op_begin()+i, 2508 OtherAddRec->op_end()); 2509 break; 2510 } 2511 SmallVector<const SCEV *, 2> TwoOps = { 2512 AddRecOps[i], OtherAddRec->getOperand(i)}; 2513 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2514 } 2515 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2516 } 2517 // Step size has changed, so we cannot guarantee no self-wraparound. 2518 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2519 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2520 } 2521 2522 // Otherwise couldn't fold anything into this recurrence. Move onto the 2523 // next one. 2524 } 2525 2526 // Okay, it looks like we really DO need an add expr. Check to see if we 2527 // already have one, otherwise create a new one. 2528 return getOrCreateAddExpr(Ops, Flags); 2529 } 2530 2531 const SCEV * 2532 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2533 SCEV::NoWrapFlags Flags) { 2534 FoldingSetNodeID ID; 2535 ID.AddInteger(scAddExpr); 2536 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2537 ID.AddPointer(Ops[i]); 2538 void *IP = nullptr; 2539 SCEVAddExpr *S = 2540 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2541 if (!S) { 2542 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2543 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2544 S = new (SCEVAllocator) 2545 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2546 UniqueSCEVs.InsertNode(S, IP); 2547 } 2548 S->setNoWrapFlags(Flags); 2549 return S; 2550 } 2551 2552 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2553 uint64_t k = i*j; 2554 if (j > 1 && k / j != i) Overflow = true; 2555 return k; 2556 } 2557 2558 /// Compute the result of "n choose k", the binomial coefficient. If an 2559 /// intermediate computation overflows, Overflow will be set and the return will 2560 /// be garbage. Overflow is not cleared on absence of overflow. 2561 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2562 // We use the multiplicative formula: 2563 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2564 // At each iteration, we take the n-th term of the numeral and divide by the 2565 // (k-n)th term of the denominator. This division will always produce an 2566 // integral result, and helps reduce the chance of overflow in the 2567 // intermediate computations. However, we can still overflow even when the 2568 // final result would fit. 2569 2570 if (n == 0 || n == k) return 1; 2571 if (k > n) return 0; 2572 2573 if (k > n/2) 2574 k = n-k; 2575 2576 uint64_t r = 1; 2577 for (uint64_t i = 1; i <= k; ++i) { 2578 r = umul_ov(r, n-(i-1), Overflow); 2579 r /= i; 2580 } 2581 return r; 2582 } 2583 2584 /// Determine if any of the operands in this SCEV are a constant or if 2585 /// any of the add or multiply expressions in this SCEV contain a constant. 2586 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2587 SmallVector<const SCEV *, 4> Ops; 2588 Ops.push_back(StartExpr); 2589 while (!Ops.empty()) { 2590 const SCEV *CurrentExpr = Ops.pop_back_val(); 2591 if (isa<SCEVConstant>(*CurrentExpr)) 2592 return true; 2593 2594 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2595 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2596 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2597 } 2598 } 2599 return false; 2600 } 2601 2602 /// Get a canonical multiply expression, or something simpler if possible. 2603 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2604 SCEV::NoWrapFlags Flags) { 2605 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2606 "only nuw or nsw allowed"); 2607 assert(!Ops.empty() && "Cannot get empty mul!"); 2608 if (Ops.size() == 1) return Ops[0]; 2609 #ifndef NDEBUG 2610 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2611 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2612 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2613 "SCEVMulExpr operand types don't match!"); 2614 #endif 2615 2616 // Sort by complexity, this groups all similar expression types together. 2617 GroupByComplexity(Ops, &LI); 2618 2619 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2620 2621 // If there are any constants, fold them together. 2622 unsigned Idx = 0; 2623 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2624 2625 // C1*(C2+V) -> C1*C2 + C1*V 2626 if (Ops.size() == 2) 2627 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2628 // If any of Add's ops are Adds or Muls with a constant, 2629 // apply this transformation as well. 2630 if (Add->getNumOperands() == 2) 2631 if (containsConstantSomewhere(Add)) 2632 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2633 getMulExpr(LHSC, Add->getOperand(1))); 2634 2635 ++Idx; 2636 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2637 // We found two constants, fold them together! 2638 ConstantInt *Fold = 2639 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2640 Ops[0] = getConstant(Fold); 2641 Ops.erase(Ops.begin()+1); // Erase the folded element 2642 if (Ops.size() == 1) return Ops[0]; 2643 LHSC = cast<SCEVConstant>(Ops[0]); 2644 } 2645 2646 // If we are left with a constant one being multiplied, strip it off. 2647 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2648 Ops.erase(Ops.begin()); 2649 --Idx; 2650 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2651 // If we have a multiply of zero, it will always be zero. 2652 return Ops[0]; 2653 } else if (Ops[0]->isAllOnesValue()) { 2654 // If we have a mul by -1 of an add, try distributing the -1 among the 2655 // add operands. 2656 if (Ops.size() == 2) { 2657 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2658 SmallVector<const SCEV *, 4> NewOps; 2659 bool AnyFolded = false; 2660 for (const SCEV *AddOp : Add->operands()) { 2661 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2662 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2663 NewOps.push_back(Mul); 2664 } 2665 if (AnyFolded) 2666 return getAddExpr(NewOps); 2667 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2668 // Negation preserves a recurrence's no self-wrap property. 2669 SmallVector<const SCEV *, 4> Operands; 2670 for (const SCEV *AddRecOp : AddRec->operands()) 2671 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2672 2673 return getAddRecExpr(Operands, AddRec->getLoop(), 2674 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2675 } 2676 } 2677 } 2678 2679 if (Ops.size() == 1) 2680 return Ops[0]; 2681 } 2682 2683 // Skip over the add expression until we get to a multiply. 2684 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2685 ++Idx; 2686 2687 // If there are mul operands inline them all into this expression. 2688 if (Idx < Ops.size()) { 2689 bool DeletedMul = false; 2690 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2691 if (Ops.size() > MulOpsInlineThreshold) 2692 break; 2693 // If we have an mul, expand the mul operands onto the end of the operands 2694 // list. 2695 Ops.erase(Ops.begin()+Idx); 2696 Ops.append(Mul->op_begin(), Mul->op_end()); 2697 DeletedMul = true; 2698 } 2699 2700 // If we deleted at least one mul, we added operands to the end of the list, 2701 // and they are not necessarily sorted. Recurse to resort and resimplify 2702 // any operands we just acquired. 2703 if (DeletedMul) 2704 return getMulExpr(Ops); 2705 } 2706 2707 // If there are any add recurrences in the operands list, see if any other 2708 // added values are loop invariant. If so, we can fold them into the 2709 // recurrence. 2710 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2711 ++Idx; 2712 2713 // Scan over all recurrences, trying to fold loop invariants into them. 2714 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2715 // Scan all of the other operands to this mul and add them to the vector if 2716 // they are loop invariant w.r.t. the recurrence. 2717 SmallVector<const SCEV *, 8> LIOps; 2718 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2719 const Loop *AddRecLoop = AddRec->getLoop(); 2720 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2721 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2722 LIOps.push_back(Ops[i]); 2723 Ops.erase(Ops.begin()+i); 2724 --i; --e; 2725 } 2726 2727 // If we found some loop invariants, fold them into the recurrence. 2728 if (!LIOps.empty()) { 2729 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2730 SmallVector<const SCEV *, 4> NewOps; 2731 NewOps.reserve(AddRec->getNumOperands()); 2732 const SCEV *Scale = getMulExpr(LIOps); 2733 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2734 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2735 2736 // Build the new addrec. Propagate the NUW and NSW flags if both the 2737 // outer mul and the inner addrec are guaranteed to have no overflow. 2738 // 2739 // No self-wrap cannot be guaranteed after changing the step size, but 2740 // will be inferred if either NUW or NSW is true. 2741 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2742 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2743 2744 // If all of the other operands were loop invariant, we are done. 2745 if (Ops.size() == 1) return NewRec; 2746 2747 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2748 for (unsigned i = 0;; ++i) 2749 if (Ops[i] == AddRec) { 2750 Ops[i] = NewRec; 2751 break; 2752 } 2753 return getMulExpr(Ops); 2754 } 2755 2756 // Okay, if there weren't any loop invariants to be folded, check to see if 2757 // there are multiple AddRec's with the same loop induction variable being 2758 // multiplied together. If so, we can fold them. 2759 2760 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2761 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2762 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2763 // ]]],+,...up to x=2n}. 2764 // Note that the arguments to choose() are always integers with values 2765 // known at compile time, never SCEV objects. 2766 // 2767 // The implementation avoids pointless extra computations when the two 2768 // addrec's are of different length (mathematically, it's equivalent to 2769 // an infinite stream of zeros on the right). 2770 bool OpsModified = false; 2771 for (unsigned OtherIdx = Idx+1; 2772 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2773 ++OtherIdx) { 2774 const SCEVAddRecExpr *OtherAddRec = 2775 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2776 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2777 continue; 2778 2779 bool Overflow = false; 2780 Type *Ty = AddRec->getType(); 2781 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2782 SmallVector<const SCEV*, 7> AddRecOps; 2783 for (int x = 0, xe = AddRec->getNumOperands() + 2784 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2785 const SCEV *Term = getZero(Ty); 2786 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2787 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2788 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2789 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2790 z < ze && !Overflow; ++z) { 2791 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2792 uint64_t Coeff; 2793 if (LargerThan64Bits) 2794 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2795 else 2796 Coeff = Coeff1*Coeff2; 2797 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2798 const SCEV *Term1 = AddRec->getOperand(y-z); 2799 const SCEV *Term2 = OtherAddRec->getOperand(z); 2800 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2801 } 2802 } 2803 AddRecOps.push_back(Term); 2804 } 2805 if (!Overflow) { 2806 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2807 SCEV::FlagAnyWrap); 2808 if (Ops.size() == 2) return NewAddRec; 2809 Ops[Idx] = NewAddRec; 2810 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2811 OpsModified = true; 2812 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2813 if (!AddRec) 2814 break; 2815 } 2816 } 2817 if (OpsModified) 2818 return getMulExpr(Ops); 2819 2820 // Otherwise couldn't fold anything into this recurrence. Move onto the 2821 // next one. 2822 } 2823 2824 // Okay, it looks like we really DO need an mul expr. Check to see if we 2825 // already have one, otherwise create a new one. 2826 FoldingSetNodeID ID; 2827 ID.AddInteger(scMulExpr); 2828 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2829 ID.AddPointer(Ops[i]); 2830 void *IP = nullptr; 2831 SCEVMulExpr *S = 2832 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2833 if (!S) { 2834 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2835 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2836 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2837 O, Ops.size()); 2838 UniqueSCEVs.InsertNode(S, IP); 2839 } 2840 S->setNoWrapFlags(Flags); 2841 return S; 2842 } 2843 2844 /// Get a canonical unsigned division expression, or something simpler if 2845 /// possible. 2846 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2847 const SCEV *RHS) { 2848 assert(getEffectiveSCEVType(LHS->getType()) == 2849 getEffectiveSCEVType(RHS->getType()) && 2850 "SCEVUDivExpr operand types don't match!"); 2851 2852 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2853 if (RHSC->getValue()->equalsInt(1)) 2854 return LHS; // X udiv 1 --> x 2855 // If the denominator is zero, the result of the udiv is undefined. Don't 2856 // try to analyze it, because the resolution chosen here may differ from 2857 // the resolution chosen in other parts of the compiler. 2858 if (!RHSC->getValue()->isZero()) { 2859 // Determine if the division can be folded into the operands of 2860 // its operands. 2861 // TODO: Generalize this to non-constants by using known-bits information. 2862 Type *Ty = LHS->getType(); 2863 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2864 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2865 // For non-power-of-two values, effectively round the value up to the 2866 // nearest power of two. 2867 if (!RHSC->getAPInt().isPowerOf2()) 2868 ++MaxShiftAmt; 2869 IntegerType *ExtTy = 2870 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2872 if (const SCEVConstant *Step = 2873 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2874 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2875 const APInt &StepInt = Step->getAPInt(); 2876 const APInt &DivInt = RHSC->getAPInt(); 2877 if (!StepInt.urem(DivInt) && 2878 getZeroExtendExpr(AR, ExtTy) == 2879 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2880 getZeroExtendExpr(Step, ExtTy), 2881 AR->getLoop(), SCEV::FlagAnyWrap)) { 2882 SmallVector<const SCEV *, 4> Operands; 2883 for (const SCEV *Op : AR->operands()) 2884 Operands.push_back(getUDivExpr(Op, RHS)); 2885 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2886 } 2887 /// Get a canonical UDivExpr for a recurrence. 2888 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2889 // We can currently only fold X%N if X is constant. 2890 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2891 if (StartC && !DivInt.urem(StepInt) && 2892 getZeroExtendExpr(AR, ExtTy) == 2893 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2894 getZeroExtendExpr(Step, ExtTy), 2895 AR->getLoop(), SCEV::FlagAnyWrap)) { 2896 const APInt &StartInt = StartC->getAPInt(); 2897 const APInt &StartRem = StartInt.urem(StepInt); 2898 if (StartRem != 0) 2899 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2900 AR->getLoop(), SCEV::FlagNW); 2901 } 2902 } 2903 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2904 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2905 SmallVector<const SCEV *, 4> Operands; 2906 for (const SCEV *Op : M->operands()) 2907 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2908 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2909 // Find an operand that's safely divisible. 2910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2911 const SCEV *Op = M->getOperand(i); 2912 const SCEV *Div = getUDivExpr(Op, RHSC); 2913 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2914 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2915 M->op_end()); 2916 Operands[i] = Div; 2917 return getMulExpr(Operands); 2918 } 2919 } 2920 } 2921 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2922 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2923 SmallVector<const SCEV *, 4> Operands; 2924 for (const SCEV *Op : A->operands()) 2925 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2926 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2927 Operands.clear(); 2928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2929 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2930 if (isa<SCEVUDivExpr>(Op) || 2931 getMulExpr(Op, RHS) != A->getOperand(i)) 2932 break; 2933 Operands.push_back(Op); 2934 } 2935 if (Operands.size() == A->getNumOperands()) 2936 return getAddExpr(Operands); 2937 } 2938 } 2939 2940 // Fold if both operands are constant. 2941 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2942 Constant *LHSCV = LHSC->getValue(); 2943 Constant *RHSCV = RHSC->getValue(); 2944 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2945 RHSCV))); 2946 } 2947 } 2948 } 2949 2950 FoldingSetNodeID ID; 2951 ID.AddInteger(scUDivExpr); 2952 ID.AddPointer(LHS); 2953 ID.AddPointer(RHS); 2954 void *IP = nullptr; 2955 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2956 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2957 LHS, RHS); 2958 UniqueSCEVs.InsertNode(S, IP); 2959 return S; 2960 } 2961 2962 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2963 APInt A = C1->getAPInt().abs(); 2964 APInt B = C2->getAPInt().abs(); 2965 uint32_t ABW = A.getBitWidth(); 2966 uint32_t BBW = B.getBitWidth(); 2967 2968 if (ABW > BBW) 2969 B = B.zext(ABW); 2970 else if (ABW < BBW) 2971 A = A.zext(BBW); 2972 2973 return APIntOps::GreatestCommonDivisor(A, B); 2974 } 2975 2976 /// Get a canonical unsigned division expression, or something simpler if 2977 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2978 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2979 /// it's not exact because the udiv may be clearing bits. 2980 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2981 const SCEV *RHS) { 2982 // TODO: we could try to find factors in all sorts of things, but for now we 2983 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2984 // end of this file for inspiration. 2985 2986 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2987 if (!Mul || !Mul->hasNoUnsignedWrap()) 2988 return getUDivExpr(LHS, RHS); 2989 2990 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2991 // If the mulexpr multiplies by a constant, then that constant must be the 2992 // first element of the mulexpr. 2993 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2994 if (LHSCst == RHSCst) { 2995 SmallVector<const SCEV *, 2> Operands; 2996 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2997 return getMulExpr(Operands); 2998 } 2999 3000 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3001 // that there's a factor provided by one of the other terms. We need to 3002 // check. 3003 APInt Factor = gcd(LHSCst, RHSCst); 3004 if (!Factor.isIntN(1)) { 3005 LHSCst = 3006 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3007 RHSCst = 3008 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3009 SmallVector<const SCEV *, 2> Operands; 3010 Operands.push_back(LHSCst); 3011 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3012 LHS = getMulExpr(Operands); 3013 RHS = RHSCst; 3014 Mul = dyn_cast<SCEVMulExpr>(LHS); 3015 if (!Mul) 3016 return getUDivExactExpr(LHS, RHS); 3017 } 3018 } 3019 } 3020 3021 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3022 if (Mul->getOperand(i) == RHS) { 3023 SmallVector<const SCEV *, 2> Operands; 3024 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3025 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3026 return getMulExpr(Operands); 3027 } 3028 } 3029 3030 return getUDivExpr(LHS, RHS); 3031 } 3032 3033 /// Get an add recurrence expression for the specified loop. Simplify the 3034 /// expression as much as possible. 3035 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3036 const Loop *L, 3037 SCEV::NoWrapFlags Flags) { 3038 SmallVector<const SCEV *, 4> Operands; 3039 Operands.push_back(Start); 3040 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3041 if (StepChrec->getLoop() == L) { 3042 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3043 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3044 } 3045 3046 Operands.push_back(Step); 3047 return getAddRecExpr(Operands, L, Flags); 3048 } 3049 3050 /// Get an add recurrence expression for the specified loop. Simplify the 3051 /// expression as much as possible. 3052 const SCEV * 3053 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3054 const Loop *L, SCEV::NoWrapFlags Flags) { 3055 if (Operands.size() == 1) return Operands[0]; 3056 #ifndef NDEBUG 3057 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3058 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3059 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3060 "SCEVAddRecExpr operand types don't match!"); 3061 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3062 assert(isLoopInvariant(Operands[i], L) && 3063 "SCEVAddRecExpr operand is not loop-invariant!"); 3064 #endif 3065 3066 if (Operands.back()->isZero()) { 3067 Operands.pop_back(); 3068 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3069 } 3070 3071 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3072 // use that information to infer NUW and NSW flags. However, computing a 3073 // BE count requires calling getAddRecExpr, so we may not yet have a 3074 // meaningful BE count at this point (and if we don't, we'd be stuck 3075 // with a SCEVCouldNotCompute as the cached BE count). 3076 3077 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3078 3079 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3080 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3081 const Loop *NestedLoop = NestedAR->getLoop(); 3082 if (L->contains(NestedLoop) 3083 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3084 : (!NestedLoop->contains(L) && 3085 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3086 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3087 NestedAR->op_end()); 3088 Operands[0] = NestedAR->getStart(); 3089 // AddRecs require their operands be loop-invariant with respect to their 3090 // loops. Don't perform this transformation if it would break this 3091 // requirement. 3092 bool AllInvariant = all_of( 3093 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3094 3095 if (AllInvariant) { 3096 // Create a recurrence for the outer loop with the same step size. 3097 // 3098 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3099 // inner recurrence has the same property. 3100 SCEV::NoWrapFlags OuterFlags = 3101 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3102 3103 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3104 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3105 return isLoopInvariant(Op, NestedLoop); 3106 }); 3107 3108 if (AllInvariant) { 3109 // Ok, both add recurrences are valid after the transformation. 3110 // 3111 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3112 // the outer recurrence has the same property. 3113 SCEV::NoWrapFlags InnerFlags = 3114 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3115 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3116 } 3117 } 3118 // Reset Operands to its original state. 3119 Operands[0] = NestedAR; 3120 } 3121 } 3122 3123 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3124 // already have one, otherwise create a new one. 3125 FoldingSetNodeID ID; 3126 ID.AddInteger(scAddRecExpr); 3127 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3128 ID.AddPointer(Operands[i]); 3129 ID.AddPointer(L); 3130 void *IP = nullptr; 3131 SCEVAddRecExpr *S = 3132 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3133 if (!S) { 3134 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3135 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3136 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3137 O, Operands.size(), L); 3138 UniqueSCEVs.InsertNode(S, IP); 3139 } 3140 S->setNoWrapFlags(Flags); 3141 return S; 3142 } 3143 3144 const SCEV * 3145 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3146 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3147 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3148 // getSCEV(Base)->getType() has the same address space as Base->getType() 3149 // because SCEV::getType() preserves the address space. 3150 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3151 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3152 // instruction to its SCEV, because the Instruction may be guarded by control 3153 // flow and the no-overflow bits may not be valid for the expression in any 3154 // context. This can be fixed similarly to how these flags are handled for 3155 // adds. 3156 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3157 : SCEV::FlagAnyWrap; 3158 3159 const SCEV *TotalOffset = getZero(IntPtrTy); 3160 // The array size is unimportant. The first thing we do on CurTy is getting 3161 // its element type. 3162 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3163 for (const SCEV *IndexExpr : IndexExprs) { 3164 // Compute the (potentially symbolic) offset in bytes for this index. 3165 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3166 // For a struct, add the member offset. 3167 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3168 unsigned FieldNo = Index->getZExtValue(); 3169 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3170 3171 // Add the field offset to the running total offset. 3172 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3173 3174 // Update CurTy to the type of the field at Index. 3175 CurTy = STy->getTypeAtIndex(Index); 3176 } else { 3177 // Update CurTy to its element type. 3178 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3179 // For an array, add the element offset, explicitly scaled. 3180 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3181 // Getelementptr indices are signed. 3182 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3183 3184 // Multiply the index by the element size to compute the element offset. 3185 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3186 3187 // Add the element offset to the running total offset. 3188 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3189 } 3190 } 3191 3192 // Add the total offset from all the GEP indices to the base. 3193 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3194 } 3195 3196 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3197 const SCEV *RHS) { 3198 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3199 return getSMaxExpr(Ops); 3200 } 3201 3202 const SCEV * 3203 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3204 assert(!Ops.empty() && "Cannot get empty smax!"); 3205 if (Ops.size() == 1) return Ops[0]; 3206 #ifndef NDEBUG 3207 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3208 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3209 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3210 "SCEVSMaxExpr operand types don't match!"); 3211 #endif 3212 3213 // Sort by complexity, this groups all similar expression types together. 3214 GroupByComplexity(Ops, &LI); 3215 3216 // If there are any constants, fold them together. 3217 unsigned Idx = 0; 3218 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3219 ++Idx; 3220 assert(Idx < Ops.size()); 3221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3222 // We found two constants, fold them together! 3223 ConstantInt *Fold = ConstantInt::get( 3224 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3225 Ops[0] = getConstant(Fold); 3226 Ops.erase(Ops.begin()+1); // Erase the folded element 3227 if (Ops.size() == 1) return Ops[0]; 3228 LHSC = cast<SCEVConstant>(Ops[0]); 3229 } 3230 3231 // If we are left with a constant minimum-int, strip it off. 3232 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3233 Ops.erase(Ops.begin()); 3234 --Idx; 3235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3236 // If we have an smax with a constant maximum-int, it will always be 3237 // maximum-int. 3238 return Ops[0]; 3239 } 3240 3241 if (Ops.size() == 1) return Ops[0]; 3242 } 3243 3244 // Find the first SMax 3245 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3246 ++Idx; 3247 3248 // Check to see if one of the operands is an SMax. If so, expand its operands 3249 // onto our operand list, and recurse to simplify. 3250 if (Idx < Ops.size()) { 3251 bool DeletedSMax = false; 3252 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3253 Ops.erase(Ops.begin()+Idx); 3254 Ops.append(SMax->op_begin(), SMax->op_end()); 3255 DeletedSMax = true; 3256 } 3257 3258 if (DeletedSMax) 3259 return getSMaxExpr(Ops); 3260 } 3261 3262 // Okay, check to see if the same value occurs in the operand list twice. If 3263 // so, delete one. Since we sorted the list, these values are required to 3264 // be adjacent. 3265 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3266 // X smax Y smax Y --> X smax Y 3267 // X smax Y --> X, if X is always greater than Y 3268 if (Ops[i] == Ops[i+1] || 3269 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3270 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3271 --i; --e; 3272 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3273 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3274 --i; --e; 3275 } 3276 3277 if (Ops.size() == 1) return Ops[0]; 3278 3279 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3280 3281 // Okay, it looks like we really DO need an smax expr. Check to see if we 3282 // already have one, otherwise create a new one. 3283 FoldingSetNodeID ID; 3284 ID.AddInteger(scSMaxExpr); 3285 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3286 ID.AddPointer(Ops[i]); 3287 void *IP = nullptr; 3288 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3289 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3290 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3291 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3292 O, Ops.size()); 3293 UniqueSCEVs.InsertNode(S, IP); 3294 return S; 3295 } 3296 3297 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3298 const SCEV *RHS) { 3299 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3300 return getUMaxExpr(Ops); 3301 } 3302 3303 const SCEV * 3304 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3305 assert(!Ops.empty() && "Cannot get empty umax!"); 3306 if (Ops.size() == 1) return Ops[0]; 3307 #ifndef NDEBUG 3308 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3309 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3310 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3311 "SCEVUMaxExpr operand types don't match!"); 3312 #endif 3313 3314 // Sort by complexity, this groups all similar expression types together. 3315 GroupByComplexity(Ops, &LI); 3316 3317 // If there are any constants, fold them together. 3318 unsigned Idx = 0; 3319 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3320 ++Idx; 3321 assert(Idx < Ops.size()); 3322 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3323 // We found two constants, fold them together! 3324 ConstantInt *Fold = ConstantInt::get( 3325 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3326 Ops[0] = getConstant(Fold); 3327 Ops.erase(Ops.begin()+1); // Erase the folded element 3328 if (Ops.size() == 1) return Ops[0]; 3329 LHSC = cast<SCEVConstant>(Ops[0]); 3330 } 3331 3332 // If we are left with a constant minimum-int, strip it off. 3333 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3334 Ops.erase(Ops.begin()); 3335 --Idx; 3336 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3337 // If we have an umax with a constant maximum-int, it will always be 3338 // maximum-int. 3339 return Ops[0]; 3340 } 3341 3342 if (Ops.size() == 1) return Ops[0]; 3343 } 3344 3345 // Find the first UMax 3346 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3347 ++Idx; 3348 3349 // Check to see if one of the operands is a UMax. If so, expand its operands 3350 // onto our operand list, and recurse to simplify. 3351 if (Idx < Ops.size()) { 3352 bool DeletedUMax = false; 3353 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3354 Ops.erase(Ops.begin()+Idx); 3355 Ops.append(UMax->op_begin(), UMax->op_end()); 3356 DeletedUMax = true; 3357 } 3358 3359 if (DeletedUMax) 3360 return getUMaxExpr(Ops); 3361 } 3362 3363 // Okay, check to see if the same value occurs in the operand list twice. If 3364 // so, delete one. Since we sorted the list, these values are required to 3365 // be adjacent. 3366 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3367 // X umax Y umax Y --> X umax Y 3368 // X umax Y --> X, if X is always greater than Y 3369 if (Ops[i] == Ops[i+1] || 3370 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3371 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3372 --i; --e; 3373 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3374 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3375 --i; --e; 3376 } 3377 3378 if (Ops.size() == 1) return Ops[0]; 3379 3380 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3381 3382 // Okay, it looks like we really DO need a umax expr. Check to see if we 3383 // already have one, otherwise create a new one. 3384 FoldingSetNodeID ID; 3385 ID.AddInteger(scUMaxExpr); 3386 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3387 ID.AddPointer(Ops[i]); 3388 void *IP = nullptr; 3389 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3390 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3391 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3392 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3393 O, Ops.size()); 3394 UniqueSCEVs.InsertNode(S, IP); 3395 return S; 3396 } 3397 3398 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3399 const SCEV *RHS) { 3400 // ~smax(~x, ~y) == smin(x, y). 3401 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3402 } 3403 3404 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3405 const SCEV *RHS) { 3406 // ~umax(~x, ~y) == umin(x, y) 3407 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3408 } 3409 3410 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3411 // We can bypass creating a target-independent 3412 // constant expression and then folding it back into a ConstantInt. 3413 // This is just a compile-time optimization. 3414 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3415 } 3416 3417 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3418 StructType *STy, 3419 unsigned FieldNo) { 3420 // We can bypass creating a target-independent 3421 // constant expression and then folding it back into a ConstantInt. 3422 // This is just a compile-time optimization. 3423 return getConstant( 3424 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3425 } 3426 3427 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3428 // Don't attempt to do anything other than create a SCEVUnknown object 3429 // here. createSCEV only calls getUnknown after checking for all other 3430 // interesting possibilities, and any other code that calls getUnknown 3431 // is doing so in order to hide a value from SCEV canonicalization. 3432 3433 FoldingSetNodeID ID; 3434 ID.AddInteger(scUnknown); 3435 ID.AddPointer(V); 3436 void *IP = nullptr; 3437 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3438 assert(cast<SCEVUnknown>(S)->getValue() == V && 3439 "Stale SCEVUnknown in uniquing map!"); 3440 return S; 3441 } 3442 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3443 FirstUnknown); 3444 FirstUnknown = cast<SCEVUnknown>(S); 3445 UniqueSCEVs.InsertNode(S, IP); 3446 return S; 3447 } 3448 3449 //===----------------------------------------------------------------------===// 3450 // Basic SCEV Analysis and PHI Idiom Recognition Code 3451 // 3452 3453 /// Test if values of the given type are analyzable within the SCEV 3454 /// framework. This primarily includes integer types, and it can optionally 3455 /// include pointer types if the ScalarEvolution class has access to 3456 /// target-specific information. 3457 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3458 // Integers and pointers are always SCEVable. 3459 return Ty->isIntegerTy() || Ty->isPointerTy(); 3460 } 3461 3462 /// Return the size in bits of the specified type, for which isSCEVable must 3463 /// return true. 3464 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3465 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3466 return getDataLayout().getTypeSizeInBits(Ty); 3467 } 3468 3469 /// Return a type with the same bitwidth as the given type and which represents 3470 /// how SCEV will treat the given type, for which isSCEVable must return 3471 /// true. For pointer types, this is the pointer-sized integer type. 3472 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3473 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3474 3475 if (Ty->isIntegerTy()) 3476 return Ty; 3477 3478 // The only other support type is pointer. 3479 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3480 return getDataLayout().getIntPtrType(Ty); 3481 } 3482 3483 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3484 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3485 } 3486 3487 const SCEV *ScalarEvolution::getCouldNotCompute() { 3488 return CouldNotCompute.get(); 3489 } 3490 3491 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3492 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3493 auto *SU = dyn_cast<SCEVUnknown>(S); 3494 return SU && SU->getValue() == nullptr; 3495 }); 3496 3497 return !ContainsNulls; 3498 } 3499 3500 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3501 HasRecMapType::iterator I = HasRecMap.find(S); 3502 if (I != HasRecMap.end()) 3503 return I->second; 3504 3505 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3506 HasRecMap.insert({S, FoundAddRec}); 3507 return FoundAddRec; 3508 } 3509 3510 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3511 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3512 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3513 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3514 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3515 if (!Add) 3516 return {S, nullptr}; 3517 3518 if (Add->getNumOperands() != 2) 3519 return {S, nullptr}; 3520 3521 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3522 if (!ConstOp) 3523 return {S, nullptr}; 3524 3525 return {Add->getOperand(1), ConstOp->getValue()}; 3526 } 3527 3528 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3529 /// by the value and offset from any ValueOffsetPair in the set. 3530 SetVector<ScalarEvolution::ValueOffsetPair> * 3531 ScalarEvolution::getSCEVValues(const SCEV *S) { 3532 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3533 if (SI == ExprValueMap.end()) 3534 return nullptr; 3535 #ifndef NDEBUG 3536 if (VerifySCEVMap) { 3537 // Check there is no dangling Value in the set returned. 3538 for (const auto &VE : SI->second) 3539 assert(ValueExprMap.count(VE.first)); 3540 } 3541 #endif 3542 return &SI->second; 3543 } 3544 3545 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3546 /// cannot be used separately. eraseValueFromMap should be used to remove 3547 /// V from ValueExprMap and ExprValueMap at the same time. 3548 void ScalarEvolution::eraseValueFromMap(Value *V) { 3549 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3550 if (I != ValueExprMap.end()) { 3551 const SCEV *S = I->second; 3552 // Remove {V, 0} from the set of ExprValueMap[S] 3553 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3554 SV->remove({V, nullptr}); 3555 3556 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3557 const SCEV *Stripped; 3558 ConstantInt *Offset; 3559 std::tie(Stripped, Offset) = splitAddExpr(S); 3560 if (Offset != nullptr) { 3561 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3562 SV->remove({V, Offset}); 3563 } 3564 ValueExprMap.erase(V); 3565 } 3566 } 3567 3568 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3569 /// create a new one. 3570 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3571 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3572 3573 const SCEV *S = getExistingSCEV(V); 3574 if (S == nullptr) { 3575 S = createSCEV(V); 3576 // During PHI resolution, it is possible to create two SCEVs for the same 3577 // V, so it is needed to double check whether V->S is inserted into 3578 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3579 std::pair<ValueExprMapType::iterator, bool> Pair = 3580 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3581 if (Pair.second) { 3582 ExprValueMap[S].insert({V, nullptr}); 3583 3584 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3585 // ExprValueMap. 3586 const SCEV *Stripped = S; 3587 ConstantInt *Offset = nullptr; 3588 std::tie(Stripped, Offset) = splitAddExpr(S); 3589 // If stripped is SCEVUnknown, don't bother to save 3590 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3591 // increase the complexity of the expansion code. 3592 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3593 // because it may generate add/sub instead of GEP in SCEV expansion. 3594 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3595 !isa<GetElementPtrInst>(V)) 3596 ExprValueMap[Stripped].insert({V, Offset}); 3597 } 3598 } 3599 return S; 3600 } 3601 3602 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3603 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3604 3605 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3606 if (I != ValueExprMap.end()) { 3607 const SCEV *S = I->second; 3608 if (checkValidity(S)) 3609 return S; 3610 eraseValueFromMap(V); 3611 forgetMemoizedResults(S); 3612 } 3613 return nullptr; 3614 } 3615 3616 /// Return a SCEV corresponding to -V = -1*V 3617 /// 3618 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3619 SCEV::NoWrapFlags Flags) { 3620 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3621 return getConstant( 3622 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3623 3624 Type *Ty = V->getType(); 3625 Ty = getEffectiveSCEVType(Ty); 3626 return getMulExpr( 3627 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3628 } 3629 3630 /// Return a SCEV corresponding to ~V = -1-V 3631 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3632 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3633 return getConstant( 3634 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3635 3636 Type *Ty = V->getType(); 3637 Ty = getEffectiveSCEVType(Ty); 3638 const SCEV *AllOnes = 3639 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3640 return getMinusSCEV(AllOnes, V); 3641 } 3642 3643 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3644 SCEV::NoWrapFlags Flags) { 3645 // Fast path: X - X --> 0. 3646 if (LHS == RHS) 3647 return getZero(LHS->getType()); 3648 3649 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3650 // makes it so that we cannot make much use of NUW. 3651 auto AddFlags = SCEV::FlagAnyWrap; 3652 const bool RHSIsNotMinSigned = 3653 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3654 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3655 // Let M be the minimum representable signed value. Then (-1)*RHS 3656 // signed-wraps if and only if RHS is M. That can happen even for 3657 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3658 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3659 // (-1)*RHS, we need to prove that RHS != M. 3660 // 3661 // If LHS is non-negative and we know that LHS - RHS does not 3662 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3663 // either by proving that RHS > M or that LHS >= 0. 3664 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3665 AddFlags = SCEV::FlagNSW; 3666 } 3667 } 3668 3669 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3670 // RHS is NSW and LHS >= 0. 3671 // 3672 // The difficulty here is that the NSW flag may have been proven 3673 // relative to a loop that is to be found in a recurrence in LHS and 3674 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3675 // larger scope than intended. 3676 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3677 3678 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3679 } 3680 3681 const SCEV * 3682 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3683 Type *SrcTy = V->getType(); 3684 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3685 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3686 "Cannot truncate or zero extend with non-integer arguments!"); 3687 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3688 return V; // No conversion 3689 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3690 return getTruncateExpr(V, Ty); 3691 return getZeroExtendExpr(V, Ty); 3692 } 3693 3694 const SCEV * 3695 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3696 Type *Ty) { 3697 Type *SrcTy = V->getType(); 3698 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3699 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3700 "Cannot truncate or zero extend with non-integer arguments!"); 3701 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3702 return V; // No conversion 3703 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3704 return getTruncateExpr(V, Ty); 3705 return getSignExtendExpr(V, Ty); 3706 } 3707 3708 const SCEV * 3709 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3710 Type *SrcTy = V->getType(); 3711 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3712 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3713 "Cannot noop or zero extend with non-integer arguments!"); 3714 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3715 "getNoopOrZeroExtend cannot truncate!"); 3716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3717 return V; // No conversion 3718 return getZeroExtendExpr(V, Ty); 3719 } 3720 3721 const SCEV * 3722 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3723 Type *SrcTy = V->getType(); 3724 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3725 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3726 "Cannot noop or sign extend with non-integer arguments!"); 3727 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3728 "getNoopOrSignExtend cannot truncate!"); 3729 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3730 return V; // No conversion 3731 return getSignExtendExpr(V, Ty); 3732 } 3733 3734 const SCEV * 3735 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3736 Type *SrcTy = V->getType(); 3737 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3738 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3739 "Cannot noop or any extend with non-integer arguments!"); 3740 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3741 "getNoopOrAnyExtend cannot truncate!"); 3742 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3743 return V; // No conversion 3744 return getAnyExtendExpr(V, Ty); 3745 } 3746 3747 const SCEV * 3748 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3749 Type *SrcTy = V->getType(); 3750 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3751 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3752 "Cannot truncate or noop with non-integer arguments!"); 3753 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3754 "getTruncateOrNoop cannot extend!"); 3755 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3756 return V; // No conversion 3757 return getTruncateExpr(V, Ty); 3758 } 3759 3760 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3761 const SCEV *RHS) { 3762 const SCEV *PromotedLHS = LHS; 3763 const SCEV *PromotedRHS = RHS; 3764 3765 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3766 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3767 else 3768 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3769 3770 return getUMaxExpr(PromotedLHS, PromotedRHS); 3771 } 3772 3773 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3774 const SCEV *RHS) { 3775 const SCEV *PromotedLHS = LHS; 3776 const SCEV *PromotedRHS = RHS; 3777 3778 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3779 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3780 else 3781 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3782 3783 return getUMinExpr(PromotedLHS, PromotedRHS); 3784 } 3785 3786 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3787 // A pointer operand may evaluate to a nonpointer expression, such as null. 3788 if (!V->getType()->isPointerTy()) 3789 return V; 3790 3791 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3792 return getPointerBase(Cast->getOperand()); 3793 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3794 const SCEV *PtrOp = nullptr; 3795 for (const SCEV *NAryOp : NAry->operands()) { 3796 if (NAryOp->getType()->isPointerTy()) { 3797 // Cannot find the base of an expression with multiple pointer operands. 3798 if (PtrOp) 3799 return V; 3800 PtrOp = NAryOp; 3801 } 3802 } 3803 if (!PtrOp) 3804 return V; 3805 return getPointerBase(PtrOp); 3806 } 3807 return V; 3808 } 3809 3810 /// Push users of the given Instruction onto the given Worklist. 3811 static void 3812 PushDefUseChildren(Instruction *I, 3813 SmallVectorImpl<Instruction *> &Worklist) { 3814 // Push the def-use children onto the Worklist stack. 3815 for (User *U : I->users()) 3816 Worklist.push_back(cast<Instruction>(U)); 3817 } 3818 3819 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3820 SmallVector<Instruction *, 16> Worklist; 3821 PushDefUseChildren(PN, Worklist); 3822 3823 SmallPtrSet<Instruction *, 8> Visited; 3824 Visited.insert(PN); 3825 while (!Worklist.empty()) { 3826 Instruction *I = Worklist.pop_back_val(); 3827 if (!Visited.insert(I).second) 3828 continue; 3829 3830 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3831 if (It != ValueExprMap.end()) { 3832 const SCEV *Old = It->second; 3833 3834 // Short-circuit the def-use traversal if the symbolic name 3835 // ceases to appear in expressions. 3836 if (Old != SymName && !hasOperand(Old, SymName)) 3837 continue; 3838 3839 // SCEVUnknown for a PHI either means that it has an unrecognized 3840 // structure, it's a PHI that's in the progress of being computed 3841 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3842 // additional loop trip count information isn't going to change anything. 3843 // In the second case, createNodeForPHI will perform the necessary 3844 // updates on its own when it gets to that point. In the third, we do 3845 // want to forget the SCEVUnknown. 3846 if (!isa<PHINode>(I) || 3847 !isa<SCEVUnknown>(Old) || 3848 (I != PN && Old == SymName)) { 3849 eraseValueFromMap(It->first); 3850 forgetMemoizedResults(Old); 3851 } 3852 } 3853 3854 PushDefUseChildren(I, Worklist); 3855 } 3856 } 3857 3858 namespace { 3859 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3860 public: 3861 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3862 ScalarEvolution &SE) { 3863 SCEVInitRewriter Rewriter(L, SE); 3864 const SCEV *Result = Rewriter.visit(S); 3865 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3866 } 3867 3868 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3869 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3870 3871 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3872 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3873 Valid = false; 3874 return Expr; 3875 } 3876 3877 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3878 // Only allow AddRecExprs for this loop. 3879 if (Expr->getLoop() == L) 3880 return Expr->getStart(); 3881 Valid = false; 3882 return Expr; 3883 } 3884 3885 bool isValid() { return Valid; } 3886 3887 private: 3888 const Loop *L; 3889 bool Valid; 3890 }; 3891 3892 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3893 public: 3894 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3895 ScalarEvolution &SE) { 3896 SCEVShiftRewriter Rewriter(L, SE); 3897 const SCEV *Result = Rewriter.visit(S); 3898 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3899 } 3900 3901 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3902 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3903 3904 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3905 // Only allow AddRecExprs for this loop. 3906 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3907 Valid = false; 3908 return Expr; 3909 } 3910 3911 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3912 if (Expr->getLoop() == L && Expr->isAffine()) 3913 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3914 Valid = false; 3915 return Expr; 3916 } 3917 bool isValid() { return Valid; } 3918 3919 private: 3920 const Loop *L; 3921 bool Valid; 3922 }; 3923 } // end anonymous namespace 3924 3925 SCEV::NoWrapFlags 3926 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3927 if (!AR->isAffine()) 3928 return SCEV::FlagAnyWrap; 3929 3930 typedef OverflowingBinaryOperator OBO; 3931 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3932 3933 if (!AR->hasNoSignedWrap()) { 3934 ConstantRange AddRecRange = getSignedRange(AR); 3935 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3936 3937 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3938 Instruction::Add, IncRange, OBO::NoSignedWrap); 3939 if (NSWRegion.contains(AddRecRange)) 3940 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3941 } 3942 3943 if (!AR->hasNoUnsignedWrap()) { 3944 ConstantRange AddRecRange = getUnsignedRange(AR); 3945 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3946 3947 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3948 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3949 if (NUWRegion.contains(AddRecRange)) 3950 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3951 } 3952 3953 return Result; 3954 } 3955 3956 namespace { 3957 /// Represents an abstract binary operation. This may exist as a 3958 /// normal instruction or constant expression, or may have been 3959 /// derived from an expression tree. 3960 struct BinaryOp { 3961 unsigned Opcode; 3962 Value *LHS; 3963 Value *RHS; 3964 bool IsNSW; 3965 bool IsNUW; 3966 3967 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3968 /// constant expression. 3969 Operator *Op; 3970 3971 explicit BinaryOp(Operator *Op) 3972 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3973 IsNSW(false), IsNUW(false), Op(Op) { 3974 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3975 IsNSW = OBO->hasNoSignedWrap(); 3976 IsNUW = OBO->hasNoUnsignedWrap(); 3977 } 3978 } 3979 3980 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3981 bool IsNUW = false) 3982 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3983 Op(nullptr) {} 3984 }; 3985 } 3986 3987 3988 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3989 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3990 auto *Op = dyn_cast<Operator>(V); 3991 if (!Op) 3992 return None; 3993 3994 // Implementation detail: all the cleverness here should happen without 3995 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3996 // SCEV expressions when possible, and we should not break that. 3997 3998 switch (Op->getOpcode()) { 3999 case Instruction::Add: 4000 case Instruction::Sub: 4001 case Instruction::Mul: 4002 case Instruction::UDiv: 4003 case Instruction::And: 4004 case Instruction::Or: 4005 case Instruction::AShr: 4006 case Instruction::Shl: 4007 return BinaryOp(Op); 4008 4009 case Instruction::Xor: 4010 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4011 // If the RHS of the xor is a signmask, then this is just an add. 4012 // Instcombine turns add of signmask into xor as a strength reduction step. 4013 if (RHSC->getValue().isSignMask()) 4014 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4015 return BinaryOp(Op); 4016 4017 case Instruction::LShr: 4018 // Turn logical shift right of a constant into a unsigned divide. 4019 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4020 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4021 4022 // If the shift count is not less than the bitwidth, the result of 4023 // the shift is undefined. Don't try to analyze it, because the 4024 // resolution chosen here may differ from the resolution chosen in 4025 // other parts of the compiler. 4026 if (SA->getValue().ult(BitWidth)) { 4027 Constant *X = 4028 ConstantInt::get(SA->getContext(), 4029 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4030 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4031 } 4032 } 4033 return BinaryOp(Op); 4034 4035 case Instruction::ExtractValue: { 4036 auto *EVI = cast<ExtractValueInst>(Op); 4037 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4038 break; 4039 4040 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4041 if (!CI) 4042 break; 4043 4044 if (auto *F = CI->getCalledFunction()) 4045 switch (F->getIntrinsicID()) { 4046 case Intrinsic::sadd_with_overflow: 4047 case Intrinsic::uadd_with_overflow: { 4048 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4049 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4050 CI->getArgOperand(1)); 4051 4052 // Now that we know that all uses of the arithmetic-result component of 4053 // CI are guarded by the overflow check, we can go ahead and pretend 4054 // that the arithmetic is non-overflowing. 4055 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4056 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4057 CI->getArgOperand(1), /* IsNSW = */ true, 4058 /* IsNUW = */ false); 4059 else 4060 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4061 CI->getArgOperand(1), /* IsNSW = */ false, 4062 /* IsNUW*/ true); 4063 } 4064 4065 case Intrinsic::ssub_with_overflow: 4066 case Intrinsic::usub_with_overflow: 4067 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4068 CI->getArgOperand(1)); 4069 4070 case Intrinsic::smul_with_overflow: 4071 case Intrinsic::umul_with_overflow: 4072 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4073 CI->getArgOperand(1)); 4074 default: 4075 break; 4076 } 4077 } 4078 4079 default: 4080 break; 4081 } 4082 4083 return None; 4084 } 4085 4086 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4087 const Loop *L = LI.getLoopFor(PN->getParent()); 4088 if (!L || L->getHeader() != PN->getParent()) 4089 return nullptr; 4090 4091 // The loop may have multiple entrances or multiple exits; we can analyze 4092 // this phi as an addrec if it has a unique entry value and a unique 4093 // backedge value. 4094 Value *BEValueV = nullptr, *StartValueV = nullptr; 4095 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4096 Value *V = PN->getIncomingValue(i); 4097 if (L->contains(PN->getIncomingBlock(i))) { 4098 if (!BEValueV) { 4099 BEValueV = V; 4100 } else if (BEValueV != V) { 4101 BEValueV = nullptr; 4102 break; 4103 } 4104 } else if (!StartValueV) { 4105 StartValueV = V; 4106 } else if (StartValueV != V) { 4107 StartValueV = nullptr; 4108 break; 4109 } 4110 } 4111 if (BEValueV && StartValueV) { 4112 // While we are analyzing this PHI node, handle its value symbolically. 4113 const SCEV *SymbolicName = getUnknown(PN); 4114 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4115 "PHI node already processed?"); 4116 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4117 4118 // Using this symbolic name for the PHI, analyze the value coming around 4119 // the back-edge. 4120 const SCEV *BEValue = getSCEV(BEValueV); 4121 4122 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4123 // has a special value for the first iteration of the loop. 4124 4125 // If the value coming around the backedge is an add with the symbolic 4126 // value we just inserted, then we found a simple induction variable! 4127 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4128 // If there is a single occurrence of the symbolic value, replace it 4129 // with a recurrence. 4130 unsigned FoundIndex = Add->getNumOperands(); 4131 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4132 if (Add->getOperand(i) == SymbolicName) 4133 if (FoundIndex == e) { 4134 FoundIndex = i; 4135 break; 4136 } 4137 4138 if (FoundIndex != Add->getNumOperands()) { 4139 // Create an add with everything but the specified operand. 4140 SmallVector<const SCEV *, 8> Ops; 4141 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4142 if (i != FoundIndex) 4143 Ops.push_back(Add->getOperand(i)); 4144 const SCEV *Accum = getAddExpr(Ops); 4145 4146 // This is not a valid addrec if the step amount is varying each 4147 // loop iteration, but is not itself an addrec in this loop. 4148 if (isLoopInvariant(Accum, L) || 4149 (isa<SCEVAddRecExpr>(Accum) && 4150 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4151 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4152 4153 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4154 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4155 if (BO->IsNUW) 4156 Flags = setFlags(Flags, SCEV::FlagNUW); 4157 if (BO->IsNSW) 4158 Flags = setFlags(Flags, SCEV::FlagNSW); 4159 } 4160 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4161 // If the increment is an inbounds GEP, then we know the address 4162 // space cannot be wrapped around. We cannot make any guarantee 4163 // about signed or unsigned overflow because pointers are 4164 // unsigned but we may have a negative index from the base 4165 // pointer. We can guarantee that no unsigned wrap occurs if the 4166 // indices form a positive value. 4167 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4168 Flags = setFlags(Flags, SCEV::FlagNW); 4169 4170 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4171 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4172 Flags = setFlags(Flags, SCEV::FlagNUW); 4173 } 4174 4175 // We cannot transfer nuw and nsw flags from subtraction 4176 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4177 // for instance. 4178 } 4179 4180 const SCEV *StartVal = getSCEV(StartValueV); 4181 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4182 4183 // Okay, for the entire analysis of this edge we assumed the PHI 4184 // to be symbolic. We now need to go back and purge all of the 4185 // entries for the scalars that use the symbolic expression. 4186 forgetSymbolicName(PN, SymbolicName); 4187 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4188 4189 // We can add Flags to the post-inc expression only if we 4190 // know that it us *undefined behavior* for BEValueV to 4191 // overflow. 4192 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4193 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4194 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4195 4196 return PHISCEV; 4197 } 4198 } 4199 } else { 4200 // Otherwise, this could be a loop like this: 4201 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4202 // In this case, j = {1,+,1} and BEValue is j. 4203 // Because the other in-value of i (0) fits the evolution of BEValue 4204 // i really is an addrec evolution. 4205 // 4206 // We can generalize this saying that i is the shifted value of BEValue 4207 // by one iteration: 4208 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4209 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4210 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4211 if (Shifted != getCouldNotCompute() && 4212 Start != getCouldNotCompute()) { 4213 const SCEV *StartVal = getSCEV(StartValueV); 4214 if (Start == StartVal) { 4215 // Okay, for the entire analysis of this edge we assumed the PHI 4216 // to be symbolic. We now need to go back and purge all of the 4217 // entries for the scalars that use the symbolic expression. 4218 forgetSymbolicName(PN, SymbolicName); 4219 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4220 return Shifted; 4221 } 4222 } 4223 } 4224 4225 // Remove the temporary PHI node SCEV that has been inserted while intending 4226 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4227 // as it will prevent later (possibly simpler) SCEV expressions to be added 4228 // to the ValueExprMap. 4229 eraseValueFromMap(PN); 4230 } 4231 4232 return nullptr; 4233 } 4234 4235 // Checks if the SCEV S is available at BB. S is considered available at BB 4236 // if S can be materialized at BB without introducing a fault. 4237 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4238 BasicBlock *BB) { 4239 struct CheckAvailable { 4240 bool TraversalDone = false; 4241 bool Available = true; 4242 4243 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4244 BasicBlock *BB = nullptr; 4245 DominatorTree &DT; 4246 4247 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4248 : L(L), BB(BB), DT(DT) {} 4249 4250 bool setUnavailable() { 4251 TraversalDone = true; 4252 Available = false; 4253 return false; 4254 } 4255 4256 bool follow(const SCEV *S) { 4257 switch (S->getSCEVType()) { 4258 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4259 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4260 // These expressions are available if their operand(s) is/are. 4261 return true; 4262 4263 case scAddRecExpr: { 4264 // We allow add recurrences that are on the loop BB is in, or some 4265 // outer loop. This guarantees availability because the value of the 4266 // add recurrence at BB is simply the "current" value of the induction 4267 // variable. We can relax this in the future; for instance an add 4268 // recurrence on a sibling dominating loop is also available at BB. 4269 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4270 if (L && (ARLoop == L || ARLoop->contains(L))) 4271 return true; 4272 4273 return setUnavailable(); 4274 } 4275 4276 case scUnknown: { 4277 // For SCEVUnknown, we check for simple dominance. 4278 const auto *SU = cast<SCEVUnknown>(S); 4279 Value *V = SU->getValue(); 4280 4281 if (isa<Argument>(V)) 4282 return false; 4283 4284 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4285 return false; 4286 4287 return setUnavailable(); 4288 } 4289 4290 case scUDivExpr: 4291 case scCouldNotCompute: 4292 // We do not try to smart about these at all. 4293 return setUnavailable(); 4294 } 4295 llvm_unreachable("switch should be fully covered!"); 4296 } 4297 4298 bool isDone() { return TraversalDone; } 4299 }; 4300 4301 CheckAvailable CA(L, BB, DT); 4302 SCEVTraversal<CheckAvailable> ST(CA); 4303 4304 ST.visitAll(S); 4305 return CA.Available; 4306 } 4307 4308 // Try to match a control flow sequence that branches out at BI and merges back 4309 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4310 // match. 4311 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4312 Value *&C, Value *&LHS, Value *&RHS) { 4313 C = BI->getCondition(); 4314 4315 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4316 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4317 4318 if (!LeftEdge.isSingleEdge()) 4319 return false; 4320 4321 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4322 4323 Use &LeftUse = Merge->getOperandUse(0); 4324 Use &RightUse = Merge->getOperandUse(1); 4325 4326 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4327 LHS = LeftUse; 4328 RHS = RightUse; 4329 return true; 4330 } 4331 4332 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4333 LHS = RightUse; 4334 RHS = LeftUse; 4335 return true; 4336 } 4337 4338 return false; 4339 } 4340 4341 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4342 auto IsReachable = 4343 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4344 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4345 const Loop *L = LI.getLoopFor(PN->getParent()); 4346 4347 // We don't want to break LCSSA, even in a SCEV expression tree. 4348 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4349 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4350 return nullptr; 4351 4352 // Try to match 4353 // 4354 // br %cond, label %left, label %right 4355 // left: 4356 // br label %merge 4357 // right: 4358 // br label %merge 4359 // merge: 4360 // V = phi [ %x, %left ], [ %y, %right ] 4361 // 4362 // as "select %cond, %x, %y" 4363 4364 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4365 assert(IDom && "At least the entry block should dominate PN"); 4366 4367 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4368 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4369 4370 if (BI && BI->isConditional() && 4371 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4372 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4373 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4374 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4375 } 4376 4377 return nullptr; 4378 } 4379 4380 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4381 if (const SCEV *S = createAddRecFromPHI(PN)) 4382 return S; 4383 4384 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4385 return S; 4386 4387 // If the PHI has a single incoming value, follow that value, unless the 4388 // PHI's incoming blocks are in a different loop, in which case doing so 4389 // risks breaking LCSSA form. Instcombine would normally zap these, but 4390 // it doesn't have DominatorTree information, so it may miss cases. 4391 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 4392 if (LI.replacementPreservesLCSSAForm(PN, V)) 4393 return getSCEV(V); 4394 4395 // If it's not a loop phi, we can't handle it yet. 4396 return getUnknown(PN); 4397 } 4398 4399 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4400 Value *Cond, 4401 Value *TrueVal, 4402 Value *FalseVal) { 4403 // Handle "constant" branch or select. This can occur for instance when a 4404 // loop pass transforms an inner loop and moves on to process the outer loop. 4405 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4406 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4407 4408 // Try to match some simple smax or umax patterns. 4409 auto *ICI = dyn_cast<ICmpInst>(Cond); 4410 if (!ICI) 4411 return getUnknown(I); 4412 4413 Value *LHS = ICI->getOperand(0); 4414 Value *RHS = ICI->getOperand(1); 4415 4416 switch (ICI->getPredicate()) { 4417 case ICmpInst::ICMP_SLT: 4418 case ICmpInst::ICMP_SLE: 4419 std::swap(LHS, RHS); 4420 LLVM_FALLTHROUGH; 4421 case ICmpInst::ICMP_SGT: 4422 case ICmpInst::ICMP_SGE: 4423 // a >s b ? a+x : b+x -> smax(a, b)+x 4424 // a >s b ? b+x : a+x -> smin(a, b)+x 4425 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4426 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4427 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4428 const SCEV *LA = getSCEV(TrueVal); 4429 const SCEV *RA = getSCEV(FalseVal); 4430 const SCEV *LDiff = getMinusSCEV(LA, LS); 4431 const SCEV *RDiff = getMinusSCEV(RA, RS); 4432 if (LDiff == RDiff) 4433 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4434 LDiff = getMinusSCEV(LA, RS); 4435 RDiff = getMinusSCEV(RA, LS); 4436 if (LDiff == RDiff) 4437 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4438 } 4439 break; 4440 case ICmpInst::ICMP_ULT: 4441 case ICmpInst::ICMP_ULE: 4442 std::swap(LHS, RHS); 4443 LLVM_FALLTHROUGH; 4444 case ICmpInst::ICMP_UGT: 4445 case ICmpInst::ICMP_UGE: 4446 // a >u b ? a+x : b+x -> umax(a, b)+x 4447 // a >u b ? b+x : a+x -> umin(a, b)+x 4448 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4449 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4450 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4451 const SCEV *LA = getSCEV(TrueVal); 4452 const SCEV *RA = getSCEV(FalseVal); 4453 const SCEV *LDiff = getMinusSCEV(LA, LS); 4454 const SCEV *RDiff = getMinusSCEV(RA, RS); 4455 if (LDiff == RDiff) 4456 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4457 LDiff = getMinusSCEV(LA, RS); 4458 RDiff = getMinusSCEV(RA, LS); 4459 if (LDiff == RDiff) 4460 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4461 } 4462 break; 4463 case ICmpInst::ICMP_NE: 4464 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4465 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4466 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4467 const SCEV *One = getOne(I->getType()); 4468 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4469 const SCEV *LA = getSCEV(TrueVal); 4470 const SCEV *RA = getSCEV(FalseVal); 4471 const SCEV *LDiff = getMinusSCEV(LA, LS); 4472 const SCEV *RDiff = getMinusSCEV(RA, One); 4473 if (LDiff == RDiff) 4474 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4475 } 4476 break; 4477 case ICmpInst::ICMP_EQ: 4478 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4479 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4480 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4481 const SCEV *One = getOne(I->getType()); 4482 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4483 const SCEV *LA = getSCEV(TrueVal); 4484 const SCEV *RA = getSCEV(FalseVal); 4485 const SCEV *LDiff = getMinusSCEV(LA, One); 4486 const SCEV *RDiff = getMinusSCEV(RA, LS); 4487 if (LDiff == RDiff) 4488 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4489 } 4490 break; 4491 default: 4492 break; 4493 } 4494 4495 return getUnknown(I); 4496 } 4497 4498 /// Expand GEP instructions into add and multiply operations. This allows them 4499 /// to be analyzed by regular SCEV code. 4500 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4501 // Don't attempt to analyze GEPs over unsized objects. 4502 if (!GEP->getSourceElementType()->isSized()) 4503 return getUnknown(GEP); 4504 4505 SmallVector<const SCEV *, 4> IndexExprs; 4506 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4507 IndexExprs.push_back(getSCEV(*Index)); 4508 return getGEPExpr(GEP, IndexExprs); 4509 } 4510 4511 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 4512 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4513 return C->getAPInt().countTrailingZeros(); 4514 4515 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4516 return std::min(GetMinTrailingZeros(T->getOperand()), 4517 (uint32_t)getTypeSizeInBits(T->getType())); 4518 4519 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4520 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4521 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4522 ? getTypeSizeInBits(E->getType()) 4523 : OpRes; 4524 } 4525 4526 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4527 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4528 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4529 ? getTypeSizeInBits(E->getType()) 4530 : OpRes; 4531 } 4532 4533 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4534 // The result is the min of all operands results. 4535 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4536 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4537 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4538 return MinOpRes; 4539 } 4540 4541 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4542 // The result is the sum of all operands results. 4543 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4544 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4545 for (unsigned i = 1, e = M->getNumOperands(); 4546 SumOpRes != BitWidth && i != e; ++i) 4547 SumOpRes = 4548 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 4549 return SumOpRes; 4550 } 4551 4552 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4553 // The result is the min of all operands results. 4554 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4555 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4556 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4557 return MinOpRes; 4558 } 4559 4560 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4561 // The result is the min of all operands results. 4562 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4563 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4564 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4565 return MinOpRes; 4566 } 4567 4568 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4569 // The result is the min of all operands results. 4570 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4571 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4572 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4573 return MinOpRes; 4574 } 4575 4576 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4577 // For a SCEVUnknown, ask ValueTracking. 4578 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4579 KnownBits Known(BitWidth); 4580 computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC, 4581 nullptr, &DT); 4582 return Known.Zero.countTrailingOnes(); 4583 } 4584 4585 // SCEVUDivExpr 4586 return 0; 4587 } 4588 4589 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4590 auto I = MinTrailingZerosCache.find(S); 4591 if (I != MinTrailingZerosCache.end()) 4592 return I->second; 4593 4594 uint32_t Result = GetMinTrailingZerosImpl(S); 4595 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 4596 assert(InsertPair.second && "Should insert a new key"); 4597 return InsertPair.first->second; 4598 } 4599 4600 /// Helper method to assign a range to V from metadata present in the IR. 4601 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4602 if (Instruction *I = dyn_cast<Instruction>(V)) 4603 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4604 return getConstantRangeFromMetadata(*MD); 4605 4606 return None; 4607 } 4608 4609 /// Determine the range for a particular SCEV. If SignHint is 4610 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4611 /// with a "cleaner" unsigned (resp. signed) representation. 4612 ConstantRange 4613 ScalarEvolution::getRange(const SCEV *S, 4614 ScalarEvolution::RangeSignHint SignHint) { 4615 DenseMap<const SCEV *, ConstantRange> &Cache = 4616 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4617 : SignedRanges; 4618 4619 // See if we've computed this range already. 4620 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4621 if (I != Cache.end()) 4622 return I->second; 4623 4624 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4625 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4626 4627 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4628 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4629 4630 // If the value has known zeros, the maximum value will have those known zeros 4631 // as well. 4632 uint32_t TZ = GetMinTrailingZeros(S); 4633 if (TZ != 0) { 4634 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4635 ConservativeResult = 4636 ConstantRange(APInt::getMinValue(BitWidth), 4637 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4638 else 4639 ConservativeResult = ConstantRange( 4640 APInt::getSignedMinValue(BitWidth), 4641 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4642 } 4643 4644 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4645 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4646 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4647 X = X.add(getRange(Add->getOperand(i), SignHint)); 4648 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4649 } 4650 4651 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4652 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4653 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4654 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4655 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4656 } 4657 4658 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4659 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4660 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4661 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4662 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4663 } 4664 4665 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4666 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4667 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4668 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4669 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4670 } 4671 4672 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4673 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4674 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4675 return setRange(UDiv, SignHint, 4676 ConservativeResult.intersectWith(X.udiv(Y))); 4677 } 4678 4679 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4680 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4681 return setRange(ZExt, SignHint, 4682 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4683 } 4684 4685 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4686 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4687 return setRange(SExt, SignHint, 4688 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4689 } 4690 4691 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4692 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4693 return setRange(Trunc, SignHint, 4694 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4695 } 4696 4697 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4698 // If there's no unsigned wrap, the value will never be less than its 4699 // initial value. 4700 if (AddRec->hasNoUnsignedWrap()) 4701 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4702 if (!C->getValue()->isZero()) 4703 ConservativeResult = ConservativeResult.intersectWith( 4704 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4705 4706 // If there's no signed wrap, and all the operands have the same sign or 4707 // zero, the value won't ever change sign. 4708 if (AddRec->hasNoSignedWrap()) { 4709 bool AllNonNeg = true; 4710 bool AllNonPos = true; 4711 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4712 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4713 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4714 } 4715 if (AllNonNeg) 4716 ConservativeResult = ConservativeResult.intersectWith( 4717 ConstantRange(APInt(BitWidth, 0), 4718 APInt::getSignedMinValue(BitWidth))); 4719 else if (AllNonPos) 4720 ConservativeResult = ConservativeResult.intersectWith( 4721 ConstantRange(APInt::getSignedMinValue(BitWidth), 4722 APInt(BitWidth, 1))); 4723 } 4724 4725 // TODO: non-affine addrec 4726 if (AddRec->isAffine()) { 4727 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4728 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4729 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4730 auto RangeFromAffine = getRangeForAffineAR( 4731 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4732 BitWidth); 4733 if (!RangeFromAffine.isFullSet()) 4734 ConservativeResult = 4735 ConservativeResult.intersectWith(RangeFromAffine); 4736 4737 auto RangeFromFactoring = getRangeViaFactoring( 4738 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4739 BitWidth); 4740 if (!RangeFromFactoring.isFullSet()) 4741 ConservativeResult = 4742 ConservativeResult.intersectWith(RangeFromFactoring); 4743 } 4744 } 4745 4746 return setRange(AddRec, SignHint, ConservativeResult); 4747 } 4748 4749 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4750 // Check if the IR explicitly contains !range metadata. 4751 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4752 if (MDRange.hasValue()) 4753 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4754 4755 // Split here to avoid paying the compile-time cost of calling both 4756 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4757 // if needed. 4758 const DataLayout &DL = getDataLayout(); 4759 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4760 // For a SCEVUnknown, ask ValueTracking. 4761 KnownBits Known(BitWidth); 4762 computeKnownBits(U->getValue(), Known, DL, 0, &AC, nullptr, &DT); 4763 if (Known.One != ~Known.Zero + 1) 4764 ConservativeResult = 4765 ConservativeResult.intersectWith(ConstantRange(Known.One, 4766 ~Known.Zero + 1)); 4767 } else { 4768 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4769 "generalize as needed!"); 4770 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4771 if (NS > 1) 4772 ConservativeResult = ConservativeResult.intersectWith( 4773 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4774 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4775 } 4776 4777 return setRange(U, SignHint, ConservativeResult); 4778 } 4779 4780 return setRange(S, SignHint, ConservativeResult); 4781 } 4782 4783 // Given a StartRange, Step and MaxBECount for an expression compute a range of 4784 // values that the expression can take. Initially, the expression has a value 4785 // from StartRange and then is changed by Step up to MaxBECount times. Signed 4786 // argument defines if we treat Step as signed or unsigned. 4787 static ConstantRange getRangeForAffineARHelper(APInt Step, 4788 ConstantRange StartRange, 4789 APInt MaxBECount, 4790 unsigned BitWidth, bool Signed) { 4791 // If either Step or MaxBECount is 0, then the expression won't change, and we 4792 // just need to return the initial range. 4793 if (Step == 0 || MaxBECount == 0) 4794 return StartRange; 4795 4796 // If we don't know anything about the initial value (i.e. StartRange is 4797 // FullRange), then we don't know anything about the final range either. 4798 // Return FullRange. 4799 if (StartRange.isFullSet()) 4800 return ConstantRange(BitWidth, /* isFullSet = */ true); 4801 4802 // If Step is signed and negative, then we use its absolute value, but we also 4803 // note that we're moving in the opposite direction. 4804 bool Descending = Signed && Step.isNegative(); 4805 4806 if (Signed) 4807 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 4808 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 4809 // This equations hold true due to the well-defined wrap-around behavior of 4810 // APInt. 4811 Step = Step.abs(); 4812 4813 // Check if Offset is more than full span of BitWidth. If it is, the 4814 // expression is guaranteed to overflow. 4815 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 4816 return ConstantRange(BitWidth, /* isFullSet = */ true); 4817 4818 // Offset is by how much the expression can change. Checks above guarantee no 4819 // overflow here. 4820 APInt Offset = Step * MaxBECount; 4821 4822 // Minimum value of the final range will match the minimal value of StartRange 4823 // if the expression is increasing and will be decreased by Offset otherwise. 4824 // Maximum value of the final range will match the maximal value of StartRange 4825 // if the expression is decreasing and will be increased by Offset otherwise. 4826 APInt StartLower = StartRange.getLower(); 4827 APInt StartUpper = StartRange.getUpper() - 1; 4828 APInt MovedBoundary = 4829 Descending ? (StartLower - Offset) : (StartUpper + Offset); 4830 4831 // It's possible that the new minimum/maximum value will fall into the initial 4832 // range (due to wrap around). This means that the expression can take any 4833 // value in this bitwidth, and we have to return full range. 4834 if (StartRange.contains(MovedBoundary)) 4835 return ConstantRange(BitWidth, /* isFullSet = */ true); 4836 4837 APInt NewLower, NewUpper; 4838 if (Descending) { 4839 NewLower = MovedBoundary; 4840 NewUpper = StartUpper; 4841 } else { 4842 NewLower = StartLower; 4843 NewUpper = MovedBoundary; 4844 } 4845 4846 // If we end up with full range, return a proper full range. 4847 if (NewLower == NewUpper + 1) 4848 return ConstantRange(BitWidth, /* isFullSet = */ true); 4849 4850 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 4851 return ConstantRange(NewLower, NewUpper + 1); 4852 } 4853 4854 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4855 const SCEV *Step, 4856 const SCEV *MaxBECount, 4857 unsigned BitWidth) { 4858 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4859 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4860 "Precondition!"); 4861 4862 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4863 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4864 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax(); 4865 4866 // First, consider step signed. 4867 ConstantRange StartSRange = getSignedRange(Start); 4868 ConstantRange StepSRange = getSignedRange(Step); 4869 4870 // If Step can be both positive and negative, we need to find ranges for the 4871 // maximum absolute step values in both directions and union them. 4872 ConstantRange SR = 4873 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 4874 MaxBECountValue, BitWidth, /* Signed = */ true); 4875 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 4876 StartSRange, MaxBECountValue, 4877 BitWidth, /* Signed = */ true)); 4878 4879 // Next, consider step unsigned. 4880 ConstantRange UR = getRangeForAffineARHelper( 4881 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start), 4882 MaxBECountValue, BitWidth, /* Signed = */ false); 4883 4884 // Finally, intersect signed and unsigned ranges. 4885 return SR.intersectWith(UR); 4886 } 4887 4888 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4889 const SCEV *Step, 4890 const SCEV *MaxBECount, 4891 unsigned BitWidth) { 4892 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4893 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4894 4895 struct SelectPattern { 4896 Value *Condition = nullptr; 4897 APInt TrueValue; 4898 APInt FalseValue; 4899 4900 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4901 const SCEV *S) { 4902 Optional<unsigned> CastOp; 4903 APInt Offset(BitWidth, 0); 4904 4905 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4906 "Should be!"); 4907 4908 // Peel off a constant offset: 4909 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4910 // In the future we could consider being smarter here and handle 4911 // {Start+Step,+,Step} too. 4912 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4913 return; 4914 4915 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4916 S = SA->getOperand(1); 4917 } 4918 4919 // Peel off a cast operation 4920 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4921 CastOp = SCast->getSCEVType(); 4922 S = SCast->getOperand(); 4923 } 4924 4925 using namespace llvm::PatternMatch; 4926 4927 auto *SU = dyn_cast<SCEVUnknown>(S); 4928 const APInt *TrueVal, *FalseVal; 4929 if (!SU || 4930 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4931 m_APInt(FalseVal)))) { 4932 Condition = nullptr; 4933 return; 4934 } 4935 4936 TrueValue = *TrueVal; 4937 FalseValue = *FalseVal; 4938 4939 // Re-apply the cast we peeled off earlier 4940 if (CastOp.hasValue()) 4941 switch (*CastOp) { 4942 default: 4943 llvm_unreachable("Unknown SCEV cast type!"); 4944 4945 case scTruncate: 4946 TrueValue = TrueValue.trunc(BitWidth); 4947 FalseValue = FalseValue.trunc(BitWidth); 4948 break; 4949 case scZeroExtend: 4950 TrueValue = TrueValue.zext(BitWidth); 4951 FalseValue = FalseValue.zext(BitWidth); 4952 break; 4953 case scSignExtend: 4954 TrueValue = TrueValue.sext(BitWidth); 4955 FalseValue = FalseValue.sext(BitWidth); 4956 break; 4957 } 4958 4959 // Re-apply the constant offset we peeled off earlier 4960 TrueValue += Offset; 4961 FalseValue += Offset; 4962 } 4963 4964 bool isRecognized() { return Condition != nullptr; } 4965 }; 4966 4967 SelectPattern StartPattern(*this, BitWidth, Start); 4968 if (!StartPattern.isRecognized()) 4969 return ConstantRange(BitWidth, /* isFullSet = */ true); 4970 4971 SelectPattern StepPattern(*this, BitWidth, Step); 4972 if (!StepPattern.isRecognized()) 4973 return ConstantRange(BitWidth, /* isFullSet = */ true); 4974 4975 if (StartPattern.Condition != StepPattern.Condition) { 4976 // We don't handle this case today; but we could, by considering four 4977 // possibilities below instead of two. I'm not sure if there are cases where 4978 // that will help over what getRange already does, though. 4979 return ConstantRange(BitWidth, /* isFullSet = */ true); 4980 } 4981 4982 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4983 // construct arbitrary general SCEV expressions here. This function is called 4984 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4985 // say) can end up caching a suboptimal value. 4986 4987 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4988 // C2352 and C2512 (otherwise it isn't needed). 4989 4990 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4991 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4992 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4993 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4994 4995 ConstantRange TrueRange = 4996 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4997 ConstantRange FalseRange = 4998 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4999 5000 return TrueRange.unionWith(FalseRange); 5001 } 5002 5003 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5004 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5005 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5006 5007 // Return early if there are no flags to propagate to the SCEV. 5008 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5009 if (BinOp->hasNoUnsignedWrap()) 5010 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5011 if (BinOp->hasNoSignedWrap()) 5012 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5013 if (Flags == SCEV::FlagAnyWrap) 5014 return SCEV::FlagAnyWrap; 5015 5016 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5017 } 5018 5019 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5020 // Here we check that I is in the header of the innermost loop containing I, 5021 // since we only deal with instructions in the loop header. The actual loop we 5022 // need to check later will come from an add recurrence, but getting that 5023 // requires computing the SCEV of the operands, which can be expensive. This 5024 // check we can do cheaply to rule out some cases early. 5025 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5026 if (InnermostContainingLoop == nullptr || 5027 InnermostContainingLoop->getHeader() != I->getParent()) 5028 return false; 5029 5030 // Only proceed if we can prove that I does not yield poison. 5031 if (!isKnownNotFullPoison(I)) return false; 5032 5033 // At this point we know that if I is executed, then it does not wrap 5034 // according to at least one of NSW or NUW. If I is not executed, then we do 5035 // not know if the calculation that I represents would wrap. Multiple 5036 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5037 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5038 // derived from other instructions that map to the same SCEV. We cannot make 5039 // that guarantee for cases where I is not executed. So we need to find the 5040 // loop that I is considered in relation to and prove that I is executed for 5041 // every iteration of that loop. That implies that the value that I 5042 // calculates does not wrap anywhere in the loop, so then we can apply the 5043 // flags to the SCEV. 5044 // 5045 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5046 // from different loops, so that we know which loop to prove that I is 5047 // executed in. 5048 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5049 // I could be an extractvalue from a call to an overflow intrinsic. 5050 // TODO: We can do better here in some cases. 5051 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5052 return false; 5053 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5054 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5055 bool AllOtherOpsLoopInvariant = true; 5056 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5057 ++OtherOpIndex) { 5058 if (OtherOpIndex != OpIndex) { 5059 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5060 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5061 AllOtherOpsLoopInvariant = false; 5062 break; 5063 } 5064 } 5065 } 5066 if (AllOtherOpsLoopInvariant && 5067 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5068 return true; 5069 } 5070 } 5071 return false; 5072 } 5073 5074 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5075 // If we know that \c I can never be poison period, then that's enough. 5076 if (isSCEVExprNeverPoison(I)) 5077 return true; 5078 5079 // For an add recurrence specifically, we assume that infinite loops without 5080 // side effects are undefined behavior, and then reason as follows: 5081 // 5082 // If the add recurrence is poison in any iteration, it is poison on all 5083 // future iterations (since incrementing poison yields poison). If the result 5084 // of the add recurrence is fed into the loop latch condition and the loop 5085 // does not contain any throws or exiting blocks other than the latch, we now 5086 // have the ability to "choose" whether the backedge is taken or not (by 5087 // choosing a sufficiently evil value for the poison feeding into the branch) 5088 // for every iteration including and after the one in which \p I first became 5089 // poison. There are two possibilities (let's call the iteration in which \p 5090 // I first became poison as K): 5091 // 5092 // 1. In the set of iterations including and after K, the loop body executes 5093 // no side effects. In this case executing the backege an infinte number 5094 // of times will yield undefined behavior. 5095 // 5096 // 2. In the set of iterations including and after K, the loop body executes 5097 // at least one side effect. In this case, that specific instance of side 5098 // effect is control dependent on poison, which also yields undefined 5099 // behavior. 5100 5101 auto *ExitingBB = L->getExitingBlock(); 5102 auto *LatchBB = L->getLoopLatch(); 5103 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5104 return false; 5105 5106 SmallPtrSet<const Instruction *, 16> Pushed; 5107 SmallVector<const Instruction *, 8> PoisonStack; 5108 5109 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5110 // things that are known to be fully poison under that assumption go on the 5111 // PoisonStack. 5112 Pushed.insert(I); 5113 PoisonStack.push_back(I); 5114 5115 bool LatchControlDependentOnPoison = false; 5116 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5117 const Instruction *Poison = PoisonStack.pop_back_val(); 5118 5119 for (auto *PoisonUser : Poison->users()) { 5120 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5121 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5122 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5123 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5124 assert(BI->isConditional() && "Only possibility!"); 5125 if (BI->getParent() == LatchBB) { 5126 LatchControlDependentOnPoison = true; 5127 break; 5128 } 5129 } 5130 } 5131 } 5132 5133 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5134 } 5135 5136 ScalarEvolution::LoopProperties 5137 ScalarEvolution::getLoopProperties(const Loop *L) { 5138 typedef ScalarEvolution::LoopProperties LoopProperties; 5139 5140 auto Itr = LoopPropertiesCache.find(L); 5141 if (Itr == LoopPropertiesCache.end()) { 5142 auto HasSideEffects = [](Instruction *I) { 5143 if (auto *SI = dyn_cast<StoreInst>(I)) 5144 return !SI->isSimple(); 5145 5146 return I->mayHaveSideEffects(); 5147 }; 5148 5149 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5150 /*HasNoSideEffects*/ true}; 5151 5152 for (auto *BB : L->getBlocks()) 5153 for (auto &I : *BB) { 5154 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5155 LP.HasNoAbnormalExits = false; 5156 if (HasSideEffects(&I)) 5157 LP.HasNoSideEffects = false; 5158 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5159 break; // We're already as pessimistic as we can get. 5160 } 5161 5162 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5163 assert(InsertPair.second && "We just checked!"); 5164 Itr = InsertPair.first; 5165 } 5166 5167 return Itr->second; 5168 } 5169 5170 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5171 if (!isSCEVable(V->getType())) 5172 return getUnknown(V); 5173 5174 if (Instruction *I = dyn_cast<Instruction>(V)) { 5175 // Don't attempt to analyze instructions in blocks that aren't 5176 // reachable. Such instructions don't matter, and they aren't required 5177 // to obey basic rules for definitions dominating uses which this 5178 // analysis depends on. 5179 if (!DT.isReachableFromEntry(I->getParent())) 5180 return getUnknown(V); 5181 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5182 return getConstant(CI); 5183 else if (isa<ConstantPointerNull>(V)) 5184 return getZero(V->getType()); 5185 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5186 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5187 else if (!isa<ConstantExpr>(V)) 5188 return getUnknown(V); 5189 5190 Operator *U = cast<Operator>(V); 5191 if (auto BO = MatchBinaryOp(U, DT)) { 5192 switch (BO->Opcode) { 5193 case Instruction::Add: { 5194 // The simple thing to do would be to just call getSCEV on both operands 5195 // and call getAddExpr with the result. However if we're looking at a 5196 // bunch of things all added together, this can be quite inefficient, 5197 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5198 // Instead, gather up all the operands and make a single getAddExpr call. 5199 // LLVM IR canonical form means we need only traverse the left operands. 5200 SmallVector<const SCEV *, 4> AddOps; 5201 do { 5202 if (BO->Op) { 5203 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5204 AddOps.push_back(OpSCEV); 5205 break; 5206 } 5207 5208 // If a NUW or NSW flag can be applied to the SCEV for this 5209 // addition, then compute the SCEV for this addition by itself 5210 // with a separate call to getAddExpr. We need to do that 5211 // instead of pushing the operands of the addition onto AddOps, 5212 // since the flags are only known to apply to this particular 5213 // addition - they may not apply to other additions that can be 5214 // formed with operands from AddOps. 5215 const SCEV *RHS = getSCEV(BO->RHS); 5216 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5217 if (Flags != SCEV::FlagAnyWrap) { 5218 const SCEV *LHS = getSCEV(BO->LHS); 5219 if (BO->Opcode == Instruction::Sub) 5220 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5221 else 5222 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5223 break; 5224 } 5225 } 5226 5227 if (BO->Opcode == Instruction::Sub) 5228 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5229 else 5230 AddOps.push_back(getSCEV(BO->RHS)); 5231 5232 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5233 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5234 NewBO->Opcode != Instruction::Sub)) { 5235 AddOps.push_back(getSCEV(BO->LHS)); 5236 break; 5237 } 5238 BO = NewBO; 5239 } while (true); 5240 5241 return getAddExpr(AddOps); 5242 } 5243 5244 case Instruction::Mul: { 5245 SmallVector<const SCEV *, 4> MulOps; 5246 do { 5247 if (BO->Op) { 5248 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5249 MulOps.push_back(OpSCEV); 5250 break; 5251 } 5252 5253 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5254 if (Flags != SCEV::FlagAnyWrap) { 5255 MulOps.push_back( 5256 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5257 break; 5258 } 5259 } 5260 5261 MulOps.push_back(getSCEV(BO->RHS)); 5262 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5263 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5264 MulOps.push_back(getSCEV(BO->LHS)); 5265 break; 5266 } 5267 BO = NewBO; 5268 } while (true); 5269 5270 return getMulExpr(MulOps); 5271 } 5272 case Instruction::UDiv: 5273 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5274 case Instruction::Sub: { 5275 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5276 if (BO->Op) 5277 Flags = getNoWrapFlagsFromUB(BO->Op); 5278 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5279 } 5280 case Instruction::And: 5281 // For an expression like x&255 that merely masks off the high bits, 5282 // use zext(trunc(x)) as the SCEV expression. 5283 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5284 if (CI->isNullValue()) 5285 return getSCEV(BO->RHS); 5286 if (CI->isAllOnesValue()) 5287 return getSCEV(BO->LHS); 5288 const APInt &A = CI->getValue(); 5289 5290 // Instcombine's ShrinkDemandedConstant may strip bits out of 5291 // constants, obscuring what would otherwise be a low-bits mask. 5292 // Use computeKnownBits to compute what ShrinkDemandedConstant 5293 // knew about to reconstruct a low-bits mask value. 5294 unsigned LZ = A.countLeadingZeros(); 5295 unsigned TZ = A.countTrailingZeros(); 5296 unsigned BitWidth = A.getBitWidth(); 5297 KnownBits Known(BitWidth); 5298 computeKnownBits(BO->LHS, Known, getDataLayout(), 5299 0, &AC, nullptr, &DT); 5300 5301 APInt EffectiveMask = 5302 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5303 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 5304 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5305 const SCEV *LHS = getSCEV(BO->LHS); 5306 const SCEV *ShiftedLHS = nullptr; 5307 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5308 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5309 // For an expression like (x * 8) & 8, simplify the multiply. 5310 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5311 unsigned GCD = std::min(MulZeros, TZ); 5312 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5313 SmallVector<const SCEV*, 4> MulOps; 5314 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5315 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5316 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5317 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5318 } 5319 } 5320 if (!ShiftedLHS) 5321 ShiftedLHS = getUDivExpr(LHS, MulCount); 5322 return getMulExpr( 5323 getZeroExtendExpr( 5324 getTruncateExpr(ShiftedLHS, 5325 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5326 BO->LHS->getType()), 5327 MulCount); 5328 } 5329 } 5330 break; 5331 5332 case Instruction::Or: 5333 // If the RHS of the Or is a constant, we may have something like: 5334 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5335 // optimizations will transparently handle this case. 5336 // 5337 // In order for this transformation to be safe, the LHS must be of the 5338 // form X*(2^n) and the Or constant must be less than 2^n. 5339 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5340 const SCEV *LHS = getSCEV(BO->LHS); 5341 const APInt &CIVal = CI->getValue(); 5342 if (GetMinTrailingZeros(LHS) >= 5343 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5344 // Build a plain add SCEV. 5345 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5346 // If the LHS of the add was an addrec and it has no-wrap flags, 5347 // transfer the no-wrap flags, since an or won't introduce a wrap. 5348 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5349 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5350 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5351 OldAR->getNoWrapFlags()); 5352 } 5353 return S; 5354 } 5355 } 5356 break; 5357 5358 case Instruction::Xor: 5359 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5360 // If the RHS of xor is -1, then this is a not operation. 5361 if (CI->isAllOnesValue()) 5362 return getNotSCEV(getSCEV(BO->LHS)); 5363 5364 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5365 // This is a variant of the check for xor with -1, and it handles 5366 // the case where instcombine has trimmed non-demanded bits out 5367 // of an xor with -1. 5368 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5369 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5370 if (LBO->getOpcode() == Instruction::And && 5371 LCI->getValue() == CI->getValue()) 5372 if (const SCEVZeroExtendExpr *Z = 5373 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5374 Type *UTy = BO->LHS->getType(); 5375 const SCEV *Z0 = Z->getOperand(); 5376 Type *Z0Ty = Z0->getType(); 5377 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5378 5379 // If C is a low-bits mask, the zero extend is serving to 5380 // mask off the high bits. Complement the operand and 5381 // re-apply the zext. 5382 if (CI->getValue().isMask(Z0TySize)) 5383 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5384 5385 // If C is a single bit, it may be in the sign-bit position 5386 // before the zero-extend. In this case, represent the xor 5387 // using an add, which is equivalent, and re-apply the zext. 5388 APInt Trunc = CI->getValue().trunc(Z0TySize); 5389 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5390 Trunc.isSignMask()) 5391 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5392 UTy); 5393 } 5394 } 5395 break; 5396 5397 case Instruction::Shl: 5398 // Turn shift left of a constant amount into a multiply. 5399 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5400 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5401 5402 // If the shift count is not less than the bitwidth, the result of 5403 // the shift is undefined. Don't try to analyze it, because the 5404 // resolution chosen here may differ from the resolution chosen in 5405 // other parts of the compiler. 5406 if (SA->getValue().uge(BitWidth)) 5407 break; 5408 5409 // It is currently not resolved how to interpret NSW for left 5410 // shift by BitWidth - 1, so we avoid applying flags in that 5411 // case. Remove this check (or this comment) once the situation 5412 // is resolved. See 5413 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5414 // and http://reviews.llvm.org/D8890 . 5415 auto Flags = SCEV::FlagAnyWrap; 5416 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5417 Flags = getNoWrapFlagsFromUB(BO->Op); 5418 5419 Constant *X = ConstantInt::get(getContext(), 5420 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5421 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5422 } 5423 break; 5424 5425 case Instruction::AShr: 5426 // AShr X, C, where C is a constant. 5427 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5428 if (!CI) 5429 break; 5430 5431 Type *OuterTy = BO->LHS->getType(); 5432 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5433 // If the shift count is not less than the bitwidth, the result of 5434 // the shift is undefined. Don't try to analyze it, because the 5435 // resolution chosen here may differ from the resolution chosen in 5436 // other parts of the compiler. 5437 if (CI->getValue().uge(BitWidth)) 5438 break; 5439 5440 if (CI->isNullValue()) 5441 return getSCEV(BO->LHS); // shift by zero --> noop 5442 5443 uint64_t AShrAmt = CI->getZExtValue(); 5444 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5445 5446 Operator *L = dyn_cast<Operator>(BO->LHS); 5447 if (L && L->getOpcode() == Instruction::Shl) { 5448 // X = Shl A, n 5449 // Y = AShr X, m 5450 // Both n and m are constant. 5451 5452 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5453 if (L->getOperand(1) == BO->RHS) 5454 // For a two-shift sext-inreg, i.e. n = m, 5455 // use sext(trunc(x)) as the SCEV expression. 5456 return getSignExtendExpr( 5457 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5458 5459 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5460 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5461 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5462 if (ShlAmt > AShrAmt) { 5463 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5464 // expression. We already checked that ShlAmt < BitWidth, so 5465 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5466 // ShlAmt - AShrAmt < Amt. 5467 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5468 ShlAmt - AShrAmt); 5469 return getSignExtendExpr( 5470 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5471 getConstant(Mul)), OuterTy); 5472 } 5473 } 5474 } 5475 break; 5476 } 5477 } 5478 5479 switch (U->getOpcode()) { 5480 case Instruction::Trunc: 5481 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5482 5483 case Instruction::ZExt: 5484 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5485 5486 case Instruction::SExt: 5487 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5488 5489 case Instruction::BitCast: 5490 // BitCasts are no-op casts so we just eliminate the cast. 5491 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5492 return getSCEV(U->getOperand(0)); 5493 break; 5494 5495 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5496 // lead to pointer expressions which cannot safely be expanded to GEPs, 5497 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5498 // simplifying integer expressions. 5499 5500 case Instruction::GetElementPtr: 5501 return createNodeForGEP(cast<GEPOperator>(U)); 5502 5503 case Instruction::PHI: 5504 return createNodeForPHI(cast<PHINode>(U)); 5505 5506 case Instruction::Select: 5507 // U can also be a select constant expr, which let fall through. Since 5508 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5509 // constant expressions cannot have instructions as operands, we'd have 5510 // returned getUnknown for a select constant expressions anyway. 5511 if (isa<Instruction>(U)) 5512 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5513 U->getOperand(1), U->getOperand(2)); 5514 break; 5515 5516 case Instruction::Call: 5517 case Instruction::Invoke: 5518 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5519 return getSCEV(RV); 5520 break; 5521 } 5522 5523 return getUnknown(V); 5524 } 5525 5526 5527 5528 //===----------------------------------------------------------------------===// 5529 // Iteration Count Computation Code 5530 // 5531 5532 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5533 if (!ExitCount) 5534 return 0; 5535 5536 ConstantInt *ExitConst = ExitCount->getValue(); 5537 5538 // Guard against huge trip counts. 5539 if (ExitConst->getValue().getActiveBits() > 32) 5540 return 0; 5541 5542 // In case of integer overflow, this returns 0, which is correct. 5543 return ((unsigned)ExitConst->getZExtValue()) + 1; 5544 } 5545 5546 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 5547 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5548 return getSmallConstantTripCount(L, ExitingBB); 5549 5550 // No trip count information for multiple exits. 5551 return 0; 5552 } 5553 5554 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 5555 BasicBlock *ExitingBlock) { 5556 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5557 assert(L->isLoopExiting(ExitingBlock) && 5558 "Exiting block must actually branch out of the loop!"); 5559 const SCEVConstant *ExitCount = 5560 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5561 return getConstantTripCount(ExitCount); 5562 } 5563 5564 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 5565 const auto *MaxExitCount = 5566 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5567 return getConstantTripCount(MaxExitCount); 5568 } 5569 5570 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 5571 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5572 return getSmallConstantTripMultiple(L, ExitingBB); 5573 5574 // No trip multiple information for multiple exits. 5575 return 0; 5576 } 5577 5578 /// Returns the largest constant divisor of the trip count of this loop as a 5579 /// normal unsigned value, if possible. This means that the actual trip count is 5580 /// always a multiple of the returned value (don't forget the trip count could 5581 /// very well be zero as well!). 5582 /// 5583 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5584 /// multiple of a constant (which is also the case if the trip count is simply 5585 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5586 /// if the trip count is very large (>= 2^32). 5587 /// 5588 /// As explained in the comments for getSmallConstantTripCount, this assumes 5589 /// that control exits the loop via ExitingBlock. 5590 unsigned 5591 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 5592 BasicBlock *ExitingBlock) { 5593 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5594 assert(L->isLoopExiting(ExitingBlock) && 5595 "Exiting block must actually branch out of the loop!"); 5596 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5597 if (ExitCount == getCouldNotCompute()) 5598 return 1; 5599 5600 // Get the trip count from the BE count by adding 1. 5601 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5602 5603 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 5604 if (!TC) 5605 // Attempt to factor more general cases. Returns the greatest power of 5606 // two divisor. If overflow happens, the trip count expression is still 5607 // divisible by the greatest power of 2 divisor returned. 5608 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 5609 5610 ConstantInt *Result = TC->getValue(); 5611 5612 // Guard against huge trip counts (this requires checking 5613 // for zero to handle the case where the trip count == -1 and the 5614 // addition wraps). 5615 if (!Result || Result->getValue().getActiveBits() > 32 || 5616 Result->getValue().getActiveBits() == 0) 5617 return 1; 5618 5619 return (unsigned)Result->getZExtValue(); 5620 } 5621 5622 /// Get the expression for the number of loop iterations for which this loop is 5623 /// guaranteed not to exit via ExitingBlock. Otherwise return 5624 /// SCEVCouldNotCompute. 5625 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 5626 BasicBlock *ExitingBlock) { 5627 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5628 } 5629 5630 const SCEV * 5631 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5632 SCEVUnionPredicate &Preds) { 5633 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5634 } 5635 5636 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5637 return getBackedgeTakenInfo(L).getExact(this); 5638 } 5639 5640 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5641 /// known never to be less than the actual backedge taken count. 5642 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5643 return getBackedgeTakenInfo(L).getMax(this); 5644 } 5645 5646 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5647 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5648 } 5649 5650 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5651 static void 5652 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5653 BasicBlock *Header = L->getHeader(); 5654 5655 // Push all Loop-header PHIs onto the Worklist stack. 5656 for (BasicBlock::iterator I = Header->begin(); 5657 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5658 Worklist.push_back(PN); 5659 } 5660 5661 const ScalarEvolution::BackedgeTakenInfo & 5662 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5663 auto &BTI = getBackedgeTakenInfo(L); 5664 if (BTI.hasFullInfo()) 5665 return BTI; 5666 5667 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5668 5669 if (!Pair.second) 5670 return Pair.first->second; 5671 5672 BackedgeTakenInfo Result = 5673 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5674 5675 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5676 } 5677 5678 const ScalarEvolution::BackedgeTakenInfo & 5679 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5680 // Initially insert an invalid entry for this loop. If the insertion 5681 // succeeds, proceed to actually compute a backedge-taken count and 5682 // update the value. The temporary CouldNotCompute value tells SCEV 5683 // code elsewhere that it shouldn't attempt to request a new 5684 // backedge-taken count, which could result in infinite recursion. 5685 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5686 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5687 if (!Pair.second) 5688 return Pair.first->second; 5689 5690 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5691 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5692 // must be cleared in this scope. 5693 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5694 5695 if (Result.getExact(this) != getCouldNotCompute()) { 5696 assert(isLoopInvariant(Result.getExact(this), L) && 5697 isLoopInvariant(Result.getMax(this), L) && 5698 "Computed backedge-taken count isn't loop invariant for loop!"); 5699 ++NumTripCountsComputed; 5700 } 5701 else if (Result.getMax(this) == getCouldNotCompute() && 5702 isa<PHINode>(L->getHeader()->begin())) { 5703 // Only count loops that have phi nodes as not being computable. 5704 ++NumTripCountsNotComputed; 5705 } 5706 5707 // Now that we know more about the trip count for this loop, forget any 5708 // existing SCEV values for PHI nodes in this loop since they are only 5709 // conservative estimates made without the benefit of trip count 5710 // information. This is similar to the code in forgetLoop, except that 5711 // it handles SCEVUnknown PHI nodes specially. 5712 if (Result.hasAnyInfo()) { 5713 SmallVector<Instruction *, 16> Worklist; 5714 PushLoopPHIs(L, Worklist); 5715 5716 SmallPtrSet<Instruction *, 8> Visited; 5717 while (!Worklist.empty()) { 5718 Instruction *I = Worklist.pop_back_val(); 5719 if (!Visited.insert(I).second) 5720 continue; 5721 5722 ValueExprMapType::iterator It = 5723 ValueExprMap.find_as(static_cast<Value *>(I)); 5724 if (It != ValueExprMap.end()) { 5725 const SCEV *Old = It->second; 5726 5727 // SCEVUnknown for a PHI either means that it has an unrecognized 5728 // structure, or it's a PHI that's in the progress of being computed 5729 // by createNodeForPHI. In the former case, additional loop trip 5730 // count information isn't going to change anything. In the later 5731 // case, createNodeForPHI will perform the necessary updates on its 5732 // own when it gets to that point. 5733 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5734 eraseValueFromMap(It->first); 5735 forgetMemoizedResults(Old); 5736 } 5737 if (PHINode *PN = dyn_cast<PHINode>(I)) 5738 ConstantEvolutionLoopExitValue.erase(PN); 5739 } 5740 5741 PushDefUseChildren(I, Worklist); 5742 } 5743 } 5744 5745 // Re-lookup the insert position, since the call to 5746 // computeBackedgeTakenCount above could result in a 5747 // recusive call to getBackedgeTakenInfo (on a different 5748 // loop), which would invalidate the iterator computed 5749 // earlier. 5750 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5751 } 5752 5753 void ScalarEvolution::forgetLoop(const Loop *L) { 5754 // Drop any stored trip count value. 5755 auto RemoveLoopFromBackedgeMap = 5756 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5757 auto BTCPos = Map.find(L); 5758 if (BTCPos != Map.end()) { 5759 BTCPos->second.clear(); 5760 Map.erase(BTCPos); 5761 } 5762 }; 5763 5764 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5765 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5766 5767 // Drop information about expressions based on loop-header PHIs. 5768 SmallVector<Instruction *, 16> Worklist; 5769 PushLoopPHIs(L, Worklist); 5770 5771 SmallPtrSet<Instruction *, 8> Visited; 5772 while (!Worklist.empty()) { 5773 Instruction *I = Worklist.pop_back_val(); 5774 if (!Visited.insert(I).second) 5775 continue; 5776 5777 ValueExprMapType::iterator It = 5778 ValueExprMap.find_as(static_cast<Value *>(I)); 5779 if (It != ValueExprMap.end()) { 5780 eraseValueFromMap(It->first); 5781 forgetMemoizedResults(It->second); 5782 if (PHINode *PN = dyn_cast<PHINode>(I)) 5783 ConstantEvolutionLoopExitValue.erase(PN); 5784 } 5785 5786 PushDefUseChildren(I, Worklist); 5787 } 5788 5789 // Forget all contained loops too, to avoid dangling entries in the 5790 // ValuesAtScopes map. 5791 for (Loop *I : *L) 5792 forgetLoop(I); 5793 5794 LoopPropertiesCache.erase(L); 5795 } 5796 5797 void ScalarEvolution::forgetValue(Value *V) { 5798 Instruction *I = dyn_cast<Instruction>(V); 5799 if (!I) return; 5800 5801 // Drop information about expressions based on loop-header PHIs. 5802 SmallVector<Instruction *, 16> Worklist; 5803 Worklist.push_back(I); 5804 5805 SmallPtrSet<Instruction *, 8> Visited; 5806 while (!Worklist.empty()) { 5807 I = Worklist.pop_back_val(); 5808 if (!Visited.insert(I).second) 5809 continue; 5810 5811 ValueExprMapType::iterator It = 5812 ValueExprMap.find_as(static_cast<Value *>(I)); 5813 if (It != ValueExprMap.end()) { 5814 eraseValueFromMap(It->first); 5815 forgetMemoizedResults(It->second); 5816 if (PHINode *PN = dyn_cast<PHINode>(I)) 5817 ConstantEvolutionLoopExitValue.erase(PN); 5818 } 5819 5820 PushDefUseChildren(I, Worklist); 5821 } 5822 } 5823 5824 /// Get the exact loop backedge taken count considering all loop exits. A 5825 /// computable result can only be returned for loops with a single exit. 5826 /// Returning the minimum taken count among all exits is incorrect because one 5827 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5828 /// the limit of each loop test is never skipped. This is a valid assumption as 5829 /// long as the loop exits via that test. For precise results, it is the 5830 /// caller's responsibility to specify the relevant loop exit using 5831 /// getExact(ExitingBlock, SE). 5832 const SCEV * 5833 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5834 SCEVUnionPredicate *Preds) const { 5835 // If any exits were not computable, the loop is not computable. 5836 if (!isComplete() || ExitNotTaken.empty()) 5837 return SE->getCouldNotCompute(); 5838 5839 const SCEV *BECount = nullptr; 5840 for (auto &ENT : ExitNotTaken) { 5841 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5842 5843 if (!BECount) 5844 BECount = ENT.ExactNotTaken; 5845 else if (BECount != ENT.ExactNotTaken) 5846 return SE->getCouldNotCompute(); 5847 if (Preds && !ENT.hasAlwaysTruePredicate()) 5848 Preds->add(ENT.Predicate.get()); 5849 5850 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5851 "Predicate should be always true!"); 5852 } 5853 5854 assert(BECount && "Invalid not taken count for loop exit"); 5855 return BECount; 5856 } 5857 5858 /// Get the exact not taken count for this loop exit. 5859 const SCEV * 5860 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5861 ScalarEvolution *SE) const { 5862 for (auto &ENT : ExitNotTaken) 5863 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5864 return ENT.ExactNotTaken; 5865 5866 return SE->getCouldNotCompute(); 5867 } 5868 5869 /// getMax - Get the max backedge taken count for the loop. 5870 const SCEV * 5871 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5872 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5873 return !ENT.hasAlwaysTruePredicate(); 5874 }; 5875 5876 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5877 return SE->getCouldNotCompute(); 5878 5879 return getMax(); 5880 } 5881 5882 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5883 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5884 return !ENT.hasAlwaysTruePredicate(); 5885 }; 5886 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5887 } 5888 5889 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5890 ScalarEvolution *SE) const { 5891 if (getMax() && getMax() != SE->getCouldNotCompute() && 5892 SE->hasOperand(getMax(), S)) 5893 return true; 5894 5895 for (auto &ENT : ExitNotTaken) 5896 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5897 SE->hasOperand(ENT.ExactNotTaken, S)) 5898 return true; 5899 5900 return false; 5901 } 5902 5903 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5904 /// computable exit into a persistent ExitNotTakenInfo array. 5905 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5906 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5907 &&ExitCounts, 5908 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5909 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5910 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5911 ExitNotTaken.reserve(ExitCounts.size()); 5912 std::transform( 5913 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5914 [&](const EdgeExitInfo &EEI) { 5915 BasicBlock *ExitBB = EEI.first; 5916 const ExitLimit &EL = EEI.second; 5917 if (EL.Predicates.empty()) 5918 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5919 5920 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5921 for (auto *Pred : EL.Predicates) 5922 Predicate->add(Pred); 5923 5924 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5925 }); 5926 } 5927 5928 /// Invalidate this result and free the ExitNotTakenInfo array. 5929 void ScalarEvolution::BackedgeTakenInfo::clear() { 5930 ExitNotTaken.clear(); 5931 } 5932 5933 /// Compute the number of times the backedge of the specified loop will execute. 5934 ScalarEvolution::BackedgeTakenInfo 5935 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5936 bool AllowPredicates) { 5937 SmallVector<BasicBlock *, 8> ExitingBlocks; 5938 L->getExitingBlocks(ExitingBlocks); 5939 5940 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5941 5942 SmallVector<EdgeExitInfo, 4> ExitCounts; 5943 bool CouldComputeBECount = true; 5944 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5945 const SCEV *MustExitMaxBECount = nullptr; 5946 const SCEV *MayExitMaxBECount = nullptr; 5947 bool MustExitMaxOrZero = false; 5948 5949 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5950 // and compute maxBECount. 5951 // Do a union of all the predicates here. 5952 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5953 BasicBlock *ExitBB = ExitingBlocks[i]; 5954 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5955 5956 assert((AllowPredicates || EL.Predicates.empty()) && 5957 "Predicated exit limit when predicates are not allowed!"); 5958 5959 // 1. For each exit that can be computed, add an entry to ExitCounts. 5960 // CouldComputeBECount is true only if all exits can be computed. 5961 if (EL.ExactNotTaken == getCouldNotCompute()) 5962 // We couldn't compute an exact value for this exit, so 5963 // we won't be able to compute an exact value for the loop. 5964 CouldComputeBECount = false; 5965 else 5966 ExitCounts.emplace_back(ExitBB, EL); 5967 5968 // 2. Derive the loop's MaxBECount from each exit's max number of 5969 // non-exiting iterations. Partition the loop exits into two kinds: 5970 // LoopMustExits and LoopMayExits. 5971 // 5972 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5973 // is a LoopMayExit. If any computable LoopMustExit is found, then 5974 // MaxBECount is the minimum EL.MaxNotTaken of computable 5975 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5976 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5977 // computable EL.MaxNotTaken. 5978 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5979 DT.dominates(ExitBB, Latch)) { 5980 if (!MustExitMaxBECount) { 5981 MustExitMaxBECount = EL.MaxNotTaken; 5982 MustExitMaxOrZero = EL.MaxOrZero; 5983 } else { 5984 MustExitMaxBECount = 5985 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5986 } 5987 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5988 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5989 MayExitMaxBECount = EL.MaxNotTaken; 5990 else { 5991 MayExitMaxBECount = 5992 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5993 } 5994 } 5995 } 5996 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5997 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5998 // The loop backedge will be taken the maximum or zero times if there's 5999 // a single exit that must be taken the maximum or zero times. 6000 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6001 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6002 MaxBECount, MaxOrZero); 6003 } 6004 6005 ScalarEvolution::ExitLimit 6006 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6007 bool AllowPredicates) { 6008 6009 // Okay, we've chosen an exiting block. See what condition causes us to exit 6010 // at this block and remember the exit block and whether all other targets 6011 // lead to the loop header. 6012 bool MustExecuteLoopHeader = true; 6013 BasicBlock *Exit = nullptr; 6014 for (auto *SBB : successors(ExitingBlock)) 6015 if (!L->contains(SBB)) { 6016 if (Exit) // Multiple exit successors. 6017 return getCouldNotCompute(); 6018 Exit = SBB; 6019 } else if (SBB != L->getHeader()) { 6020 MustExecuteLoopHeader = false; 6021 } 6022 6023 // At this point, we know we have a conditional branch that determines whether 6024 // the loop is exited. However, we don't know if the branch is executed each 6025 // time through the loop. If not, then the execution count of the branch will 6026 // not be equal to the trip count of the loop. 6027 // 6028 // Currently we check for this by checking to see if the Exit branch goes to 6029 // the loop header. If so, we know it will always execute the same number of 6030 // times as the loop. We also handle the case where the exit block *is* the 6031 // loop header. This is common for un-rotated loops. 6032 // 6033 // If both of those tests fail, walk up the unique predecessor chain to the 6034 // header, stopping if there is an edge that doesn't exit the loop. If the 6035 // header is reached, the execution count of the branch will be equal to the 6036 // trip count of the loop. 6037 // 6038 // More extensive analysis could be done to handle more cases here. 6039 // 6040 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6041 // The simple checks failed, try climbing the unique predecessor chain 6042 // up to the header. 6043 bool Ok = false; 6044 for (BasicBlock *BB = ExitingBlock; BB; ) { 6045 BasicBlock *Pred = BB->getUniquePredecessor(); 6046 if (!Pred) 6047 return getCouldNotCompute(); 6048 TerminatorInst *PredTerm = Pred->getTerminator(); 6049 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6050 if (PredSucc == BB) 6051 continue; 6052 // If the predecessor has a successor that isn't BB and isn't 6053 // outside the loop, assume the worst. 6054 if (L->contains(PredSucc)) 6055 return getCouldNotCompute(); 6056 } 6057 if (Pred == L->getHeader()) { 6058 Ok = true; 6059 break; 6060 } 6061 BB = Pred; 6062 } 6063 if (!Ok) 6064 return getCouldNotCompute(); 6065 } 6066 6067 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6068 TerminatorInst *Term = ExitingBlock->getTerminator(); 6069 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6070 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6071 // Proceed to the next level to examine the exit condition expression. 6072 return computeExitLimitFromCond( 6073 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6074 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6075 } 6076 6077 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6078 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6079 /*ControlsExit=*/IsOnlyExit); 6080 6081 return getCouldNotCompute(); 6082 } 6083 6084 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6085 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6086 bool ControlsExit, bool AllowPredicates) { 6087 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6088 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6089 ControlsExit, AllowPredicates); 6090 } 6091 6092 Optional<ScalarEvolution::ExitLimit> 6093 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6094 BasicBlock *TBB, BasicBlock *FBB, 6095 bool ControlsExit, bool AllowPredicates) { 6096 (void)this->L; 6097 (void)this->TBB; 6098 (void)this->FBB; 6099 (void)this->AllowPredicates; 6100 6101 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6102 this->AllowPredicates == AllowPredicates && 6103 "Variance in assumed invariant key components!"); 6104 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6105 if (Itr == TripCountMap.end()) 6106 return None; 6107 return Itr->second; 6108 } 6109 6110 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6111 BasicBlock *TBB, BasicBlock *FBB, 6112 bool ControlsExit, 6113 bool AllowPredicates, 6114 const ExitLimit &EL) { 6115 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6116 this->AllowPredicates == AllowPredicates && 6117 "Variance in assumed invariant key components!"); 6118 6119 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6120 assert(InsertResult.second && "Expected successful insertion!"); 6121 (void)InsertResult; 6122 } 6123 6124 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6125 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6126 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6127 6128 if (auto MaybeEL = 6129 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6130 return *MaybeEL; 6131 6132 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6133 ControlsExit, AllowPredicates); 6134 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6135 return EL; 6136 } 6137 6138 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6139 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6140 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6141 // Check if the controlling expression for this loop is an And or Or. 6142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6143 if (BO->getOpcode() == Instruction::And) { 6144 // Recurse on the operands of the and. 6145 bool EitherMayExit = L->contains(TBB); 6146 ExitLimit EL0 = computeExitLimitFromCondCached( 6147 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6148 AllowPredicates); 6149 ExitLimit EL1 = computeExitLimitFromCondCached( 6150 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6151 AllowPredicates); 6152 const SCEV *BECount = getCouldNotCompute(); 6153 const SCEV *MaxBECount = getCouldNotCompute(); 6154 if (EitherMayExit) { 6155 // Both conditions must be true for the loop to continue executing. 6156 // Choose the less conservative count. 6157 if (EL0.ExactNotTaken == getCouldNotCompute() || 6158 EL1.ExactNotTaken == getCouldNotCompute()) 6159 BECount = getCouldNotCompute(); 6160 else 6161 BECount = 6162 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6163 if (EL0.MaxNotTaken == getCouldNotCompute()) 6164 MaxBECount = EL1.MaxNotTaken; 6165 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6166 MaxBECount = EL0.MaxNotTaken; 6167 else 6168 MaxBECount = 6169 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6170 } else { 6171 // Both conditions must be true at the same time for the loop to exit. 6172 // For now, be conservative. 6173 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6174 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6175 MaxBECount = EL0.MaxNotTaken; 6176 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6177 BECount = EL0.ExactNotTaken; 6178 } 6179 6180 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6181 // to be more aggressive when computing BECount than when computing 6182 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6183 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6184 // to not. 6185 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6186 !isa<SCEVCouldNotCompute>(BECount)) 6187 MaxBECount = BECount; 6188 6189 return ExitLimit(BECount, MaxBECount, false, 6190 {&EL0.Predicates, &EL1.Predicates}); 6191 } 6192 if (BO->getOpcode() == Instruction::Or) { 6193 // Recurse on the operands of the or. 6194 bool EitherMayExit = L->contains(FBB); 6195 ExitLimit EL0 = computeExitLimitFromCondCached( 6196 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6197 AllowPredicates); 6198 ExitLimit EL1 = computeExitLimitFromCondCached( 6199 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6200 AllowPredicates); 6201 const SCEV *BECount = getCouldNotCompute(); 6202 const SCEV *MaxBECount = getCouldNotCompute(); 6203 if (EitherMayExit) { 6204 // Both conditions must be false for the loop to continue executing. 6205 // Choose the less conservative count. 6206 if (EL0.ExactNotTaken == getCouldNotCompute() || 6207 EL1.ExactNotTaken == getCouldNotCompute()) 6208 BECount = getCouldNotCompute(); 6209 else 6210 BECount = 6211 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6212 if (EL0.MaxNotTaken == getCouldNotCompute()) 6213 MaxBECount = EL1.MaxNotTaken; 6214 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6215 MaxBECount = EL0.MaxNotTaken; 6216 else 6217 MaxBECount = 6218 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6219 } else { 6220 // Both conditions must be false at the same time for the loop to exit. 6221 // For now, be conservative. 6222 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6223 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6224 MaxBECount = EL0.MaxNotTaken; 6225 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6226 BECount = EL0.ExactNotTaken; 6227 } 6228 6229 return ExitLimit(BECount, MaxBECount, false, 6230 {&EL0.Predicates, &EL1.Predicates}); 6231 } 6232 } 6233 6234 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6235 // Proceed to the next level to examine the icmp. 6236 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6237 ExitLimit EL = 6238 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6239 if (EL.hasFullInfo() || !AllowPredicates) 6240 return EL; 6241 6242 // Try again, but use SCEV predicates this time. 6243 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6244 /*AllowPredicates=*/true); 6245 } 6246 6247 // Check for a constant condition. These are normally stripped out by 6248 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6249 // preserve the CFG and is temporarily leaving constant conditions 6250 // in place. 6251 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6252 if (L->contains(FBB) == !CI->getZExtValue()) 6253 // The backedge is always taken. 6254 return getCouldNotCompute(); 6255 else 6256 // The backedge is never taken. 6257 return getZero(CI->getType()); 6258 } 6259 6260 // If it's not an integer or pointer comparison then compute it the hard way. 6261 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6262 } 6263 6264 ScalarEvolution::ExitLimit 6265 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6266 ICmpInst *ExitCond, 6267 BasicBlock *TBB, 6268 BasicBlock *FBB, 6269 bool ControlsExit, 6270 bool AllowPredicates) { 6271 6272 // If the condition was exit on true, convert the condition to exit on false 6273 ICmpInst::Predicate Cond; 6274 if (!L->contains(FBB)) 6275 Cond = ExitCond->getPredicate(); 6276 else 6277 Cond = ExitCond->getInversePredicate(); 6278 6279 // Handle common loops like: for (X = "string"; *X; ++X) 6280 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6281 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6282 ExitLimit ItCnt = 6283 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6284 if (ItCnt.hasAnyInfo()) 6285 return ItCnt; 6286 } 6287 6288 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6289 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6290 6291 // Try to evaluate any dependencies out of the loop. 6292 LHS = getSCEVAtScope(LHS, L); 6293 RHS = getSCEVAtScope(RHS, L); 6294 6295 // At this point, we would like to compute how many iterations of the 6296 // loop the predicate will return true for these inputs. 6297 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6298 // If there is a loop-invariant, force it into the RHS. 6299 std::swap(LHS, RHS); 6300 Cond = ICmpInst::getSwappedPredicate(Cond); 6301 } 6302 6303 // Simplify the operands before analyzing them. 6304 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6305 6306 // If we have a comparison of a chrec against a constant, try to use value 6307 // ranges to answer this query. 6308 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6309 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6310 if (AddRec->getLoop() == L) { 6311 // Form the constant range. 6312 ConstantRange CompRange = 6313 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6314 6315 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6316 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6317 } 6318 6319 switch (Cond) { 6320 case ICmpInst::ICMP_NE: { // while (X != Y) 6321 // Convert to: while (X-Y != 0) 6322 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6323 AllowPredicates); 6324 if (EL.hasAnyInfo()) return EL; 6325 break; 6326 } 6327 case ICmpInst::ICMP_EQ: { // while (X == Y) 6328 // Convert to: while (X-Y == 0) 6329 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6330 if (EL.hasAnyInfo()) return EL; 6331 break; 6332 } 6333 case ICmpInst::ICMP_SLT: 6334 case ICmpInst::ICMP_ULT: { // while (X < Y) 6335 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6336 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6337 AllowPredicates); 6338 if (EL.hasAnyInfo()) return EL; 6339 break; 6340 } 6341 case ICmpInst::ICMP_SGT: 6342 case ICmpInst::ICMP_UGT: { // while (X > Y) 6343 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6344 ExitLimit EL = 6345 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6346 AllowPredicates); 6347 if (EL.hasAnyInfo()) return EL; 6348 break; 6349 } 6350 default: 6351 break; 6352 } 6353 6354 auto *ExhaustiveCount = 6355 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6356 6357 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6358 return ExhaustiveCount; 6359 6360 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6361 ExitCond->getOperand(1), L, Cond); 6362 } 6363 6364 ScalarEvolution::ExitLimit 6365 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6366 SwitchInst *Switch, 6367 BasicBlock *ExitingBlock, 6368 bool ControlsExit) { 6369 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6370 6371 // Give up if the exit is the default dest of a switch. 6372 if (Switch->getDefaultDest() == ExitingBlock) 6373 return getCouldNotCompute(); 6374 6375 assert(L->contains(Switch->getDefaultDest()) && 6376 "Default case must not exit the loop!"); 6377 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6378 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6379 6380 // while (X != Y) --> while (X-Y != 0) 6381 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6382 if (EL.hasAnyInfo()) 6383 return EL; 6384 6385 return getCouldNotCompute(); 6386 } 6387 6388 static ConstantInt * 6389 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6390 ScalarEvolution &SE) { 6391 const SCEV *InVal = SE.getConstant(C); 6392 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6393 assert(isa<SCEVConstant>(Val) && 6394 "Evaluation of SCEV at constant didn't fold correctly?"); 6395 return cast<SCEVConstant>(Val)->getValue(); 6396 } 6397 6398 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6399 /// compute the backedge execution count. 6400 ScalarEvolution::ExitLimit 6401 ScalarEvolution::computeLoadConstantCompareExitLimit( 6402 LoadInst *LI, 6403 Constant *RHS, 6404 const Loop *L, 6405 ICmpInst::Predicate predicate) { 6406 6407 if (LI->isVolatile()) return getCouldNotCompute(); 6408 6409 // Check to see if the loaded pointer is a getelementptr of a global. 6410 // TODO: Use SCEV instead of manually grubbing with GEPs. 6411 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6412 if (!GEP) return getCouldNotCompute(); 6413 6414 // Make sure that it is really a constant global we are gepping, with an 6415 // initializer, and make sure the first IDX is really 0. 6416 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6417 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6418 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6419 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6420 return getCouldNotCompute(); 6421 6422 // Okay, we allow one non-constant index into the GEP instruction. 6423 Value *VarIdx = nullptr; 6424 std::vector<Constant*> Indexes; 6425 unsigned VarIdxNum = 0; 6426 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6427 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6428 Indexes.push_back(CI); 6429 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6430 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6431 VarIdx = GEP->getOperand(i); 6432 VarIdxNum = i-2; 6433 Indexes.push_back(nullptr); 6434 } 6435 6436 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6437 if (!VarIdx) 6438 return getCouldNotCompute(); 6439 6440 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6441 // Check to see if X is a loop variant variable value now. 6442 const SCEV *Idx = getSCEV(VarIdx); 6443 Idx = getSCEVAtScope(Idx, L); 6444 6445 // We can only recognize very limited forms of loop index expressions, in 6446 // particular, only affine AddRec's like {C1,+,C2}. 6447 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6448 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6449 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6450 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6451 return getCouldNotCompute(); 6452 6453 unsigned MaxSteps = MaxBruteForceIterations; 6454 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6455 ConstantInt *ItCst = ConstantInt::get( 6456 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6457 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6458 6459 // Form the GEP offset. 6460 Indexes[VarIdxNum] = Val; 6461 6462 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6463 Indexes); 6464 if (!Result) break; // Cannot compute! 6465 6466 // Evaluate the condition for this iteration. 6467 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6468 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6469 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6470 ++NumArrayLenItCounts; 6471 return getConstant(ItCst); // Found terminating iteration! 6472 } 6473 } 6474 return getCouldNotCompute(); 6475 } 6476 6477 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6478 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6479 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6480 if (!RHS) 6481 return getCouldNotCompute(); 6482 6483 const BasicBlock *Latch = L->getLoopLatch(); 6484 if (!Latch) 6485 return getCouldNotCompute(); 6486 6487 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6488 if (!Predecessor) 6489 return getCouldNotCompute(); 6490 6491 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6492 // Return LHS in OutLHS and shift_opt in OutOpCode. 6493 auto MatchPositiveShift = 6494 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6495 6496 using namespace PatternMatch; 6497 6498 ConstantInt *ShiftAmt; 6499 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6500 OutOpCode = Instruction::LShr; 6501 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6502 OutOpCode = Instruction::AShr; 6503 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6504 OutOpCode = Instruction::Shl; 6505 else 6506 return false; 6507 6508 return ShiftAmt->getValue().isStrictlyPositive(); 6509 }; 6510 6511 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6512 // 6513 // loop: 6514 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6515 // %iv.shifted = lshr i32 %iv, <positive constant> 6516 // 6517 // Return true on a successful match. Return the corresponding PHI node (%iv 6518 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6519 auto MatchShiftRecurrence = 6520 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6521 Optional<Instruction::BinaryOps> PostShiftOpCode; 6522 6523 { 6524 Instruction::BinaryOps OpC; 6525 Value *V; 6526 6527 // If we encounter a shift instruction, "peel off" the shift operation, 6528 // and remember that we did so. Later when we inspect %iv's backedge 6529 // value, we will make sure that the backedge value uses the same 6530 // operation. 6531 // 6532 // Note: the peeled shift operation does not have to be the same 6533 // instruction as the one feeding into the PHI's backedge value. We only 6534 // really care about it being the same *kind* of shift instruction -- 6535 // that's all that is required for our later inferences to hold. 6536 if (MatchPositiveShift(LHS, V, OpC)) { 6537 PostShiftOpCode = OpC; 6538 LHS = V; 6539 } 6540 } 6541 6542 PNOut = dyn_cast<PHINode>(LHS); 6543 if (!PNOut || PNOut->getParent() != L->getHeader()) 6544 return false; 6545 6546 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6547 Value *OpLHS; 6548 6549 return 6550 // The backedge value for the PHI node must be a shift by a positive 6551 // amount 6552 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6553 6554 // of the PHI node itself 6555 OpLHS == PNOut && 6556 6557 // and the kind of shift should be match the kind of shift we peeled 6558 // off, if any. 6559 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6560 }; 6561 6562 PHINode *PN; 6563 Instruction::BinaryOps OpCode; 6564 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6565 return getCouldNotCompute(); 6566 6567 const DataLayout &DL = getDataLayout(); 6568 6569 // The key rationale for this optimization is that for some kinds of shift 6570 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6571 // within a finite number of iterations. If the condition guarding the 6572 // backedge (in the sense that the backedge is taken if the condition is true) 6573 // is false for the value the shift recurrence stabilizes to, then we know 6574 // that the backedge is taken only a finite number of times. 6575 6576 ConstantInt *StableValue = nullptr; 6577 switch (OpCode) { 6578 default: 6579 llvm_unreachable("Impossible case!"); 6580 6581 case Instruction::AShr: { 6582 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6583 // bitwidth(K) iterations. 6584 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6585 bool KnownZero, KnownOne; 6586 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6587 Predecessor->getTerminator(), &DT); 6588 auto *Ty = cast<IntegerType>(RHS->getType()); 6589 if (KnownZero) 6590 StableValue = ConstantInt::get(Ty, 0); 6591 else if (KnownOne) 6592 StableValue = ConstantInt::get(Ty, -1, true); 6593 else 6594 return getCouldNotCompute(); 6595 6596 break; 6597 } 6598 case Instruction::LShr: 6599 case Instruction::Shl: 6600 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6601 // stabilize to 0 in at most bitwidth(K) iterations. 6602 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6603 break; 6604 } 6605 6606 auto *Result = 6607 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6608 assert(Result->getType()->isIntegerTy(1) && 6609 "Otherwise cannot be an operand to a branch instruction"); 6610 6611 if (Result->isZeroValue()) { 6612 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6613 const SCEV *UpperBound = 6614 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6615 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6616 } 6617 6618 return getCouldNotCompute(); 6619 } 6620 6621 /// Return true if we can constant fold an instruction of the specified type, 6622 /// assuming that all operands were constants. 6623 static bool CanConstantFold(const Instruction *I) { 6624 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6625 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6626 isa<LoadInst>(I)) 6627 return true; 6628 6629 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6630 if (const Function *F = CI->getCalledFunction()) 6631 return canConstantFoldCallTo(F); 6632 return false; 6633 } 6634 6635 /// Determine whether this instruction can constant evolve within this loop 6636 /// assuming its operands can all constant evolve. 6637 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6638 // An instruction outside of the loop can't be derived from a loop PHI. 6639 if (!L->contains(I)) return false; 6640 6641 if (isa<PHINode>(I)) { 6642 // We don't currently keep track of the control flow needed to evaluate 6643 // PHIs, so we cannot handle PHIs inside of loops. 6644 return L->getHeader() == I->getParent(); 6645 } 6646 6647 // If we won't be able to constant fold this expression even if the operands 6648 // are constants, bail early. 6649 return CanConstantFold(I); 6650 } 6651 6652 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6653 /// recursing through each instruction operand until reaching a loop header phi. 6654 static PHINode * 6655 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6656 DenseMap<Instruction *, PHINode *> &PHIMap, 6657 unsigned Depth) { 6658 if (Depth > MaxConstantEvolvingDepth) 6659 return nullptr; 6660 6661 // Otherwise, we can evaluate this instruction if all of its operands are 6662 // constant or derived from a PHI node themselves. 6663 PHINode *PHI = nullptr; 6664 for (Value *Op : UseInst->operands()) { 6665 if (isa<Constant>(Op)) continue; 6666 6667 Instruction *OpInst = dyn_cast<Instruction>(Op); 6668 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6669 6670 PHINode *P = dyn_cast<PHINode>(OpInst); 6671 if (!P) 6672 // If this operand is already visited, reuse the prior result. 6673 // We may have P != PHI if this is the deepest point at which the 6674 // inconsistent paths meet. 6675 P = PHIMap.lookup(OpInst); 6676 if (!P) { 6677 // Recurse and memoize the results, whether a phi is found or not. 6678 // This recursive call invalidates pointers into PHIMap. 6679 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 6680 PHIMap[OpInst] = P; 6681 } 6682 if (!P) 6683 return nullptr; // Not evolving from PHI 6684 if (PHI && PHI != P) 6685 return nullptr; // Evolving from multiple different PHIs. 6686 PHI = P; 6687 } 6688 // This is a expression evolving from a constant PHI! 6689 return PHI; 6690 } 6691 6692 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6693 /// in the loop that V is derived from. We allow arbitrary operations along the 6694 /// way, but the operands of an operation must either be constants or a value 6695 /// derived from a constant PHI. If this expression does not fit with these 6696 /// constraints, return null. 6697 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6698 Instruction *I = dyn_cast<Instruction>(V); 6699 if (!I || !canConstantEvolve(I, L)) return nullptr; 6700 6701 if (PHINode *PN = dyn_cast<PHINode>(I)) 6702 return PN; 6703 6704 // Record non-constant instructions contained by the loop. 6705 DenseMap<Instruction *, PHINode *> PHIMap; 6706 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 6707 } 6708 6709 /// EvaluateExpression - Given an expression that passes the 6710 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6711 /// in the loop has the value PHIVal. If we can't fold this expression for some 6712 /// reason, return null. 6713 static Constant *EvaluateExpression(Value *V, const Loop *L, 6714 DenseMap<Instruction *, Constant *> &Vals, 6715 const DataLayout &DL, 6716 const TargetLibraryInfo *TLI) { 6717 // Convenient constant check, but redundant for recursive calls. 6718 if (Constant *C = dyn_cast<Constant>(V)) return C; 6719 Instruction *I = dyn_cast<Instruction>(V); 6720 if (!I) return nullptr; 6721 6722 if (Constant *C = Vals.lookup(I)) return C; 6723 6724 // An instruction inside the loop depends on a value outside the loop that we 6725 // weren't given a mapping for, or a value such as a call inside the loop. 6726 if (!canConstantEvolve(I, L)) return nullptr; 6727 6728 // An unmapped PHI can be due to a branch or another loop inside this loop, 6729 // or due to this not being the initial iteration through a loop where we 6730 // couldn't compute the evolution of this particular PHI last time. 6731 if (isa<PHINode>(I)) return nullptr; 6732 6733 std::vector<Constant*> Operands(I->getNumOperands()); 6734 6735 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6736 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6737 if (!Operand) { 6738 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6739 if (!Operands[i]) return nullptr; 6740 continue; 6741 } 6742 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6743 Vals[Operand] = C; 6744 if (!C) return nullptr; 6745 Operands[i] = C; 6746 } 6747 6748 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6749 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6750 Operands[1], DL, TLI); 6751 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6752 if (!LI->isVolatile()) 6753 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6754 } 6755 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6756 } 6757 6758 6759 // If every incoming value to PN except the one for BB is a specific Constant, 6760 // return that, else return nullptr. 6761 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6762 Constant *IncomingVal = nullptr; 6763 6764 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6765 if (PN->getIncomingBlock(i) == BB) 6766 continue; 6767 6768 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6769 if (!CurrentVal) 6770 return nullptr; 6771 6772 if (IncomingVal != CurrentVal) { 6773 if (IncomingVal) 6774 return nullptr; 6775 IncomingVal = CurrentVal; 6776 } 6777 } 6778 6779 return IncomingVal; 6780 } 6781 6782 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6783 /// in the header of its containing loop, we know the loop executes a 6784 /// constant number of times, and the PHI node is just a recurrence 6785 /// involving constants, fold it. 6786 Constant * 6787 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6788 const APInt &BEs, 6789 const Loop *L) { 6790 auto I = ConstantEvolutionLoopExitValue.find(PN); 6791 if (I != ConstantEvolutionLoopExitValue.end()) 6792 return I->second; 6793 6794 if (BEs.ugt(MaxBruteForceIterations)) 6795 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6796 6797 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6798 6799 DenseMap<Instruction *, Constant *> CurrentIterVals; 6800 BasicBlock *Header = L->getHeader(); 6801 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6802 6803 BasicBlock *Latch = L->getLoopLatch(); 6804 if (!Latch) 6805 return nullptr; 6806 6807 for (auto &I : *Header) { 6808 PHINode *PHI = dyn_cast<PHINode>(&I); 6809 if (!PHI) break; 6810 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6811 if (!StartCST) continue; 6812 CurrentIterVals[PHI] = StartCST; 6813 } 6814 if (!CurrentIterVals.count(PN)) 6815 return RetVal = nullptr; 6816 6817 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6818 6819 // Execute the loop symbolically to determine the exit value. 6820 if (BEs.getActiveBits() >= 32) 6821 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6822 6823 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6824 unsigned IterationNum = 0; 6825 const DataLayout &DL = getDataLayout(); 6826 for (; ; ++IterationNum) { 6827 if (IterationNum == NumIterations) 6828 return RetVal = CurrentIterVals[PN]; // Got exit value! 6829 6830 // Compute the value of the PHIs for the next iteration. 6831 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6832 DenseMap<Instruction *, Constant *> NextIterVals; 6833 Constant *NextPHI = 6834 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6835 if (!NextPHI) 6836 return nullptr; // Couldn't evaluate! 6837 NextIterVals[PN] = NextPHI; 6838 6839 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6840 6841 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6842 // cease to be able to evaluate one of them or if they stop evolving, 6843 // because that doesn't necessarily prevent us from computing PN. 6844 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6845 for (const auto &I : CurrentIterVals) { 6846 PHINode *PHI = dyn_cast<PHINode>(I.first); 6847 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6848 PHIsToCompute.emplace_back(PHI, I.second); 6849 } 6850 // We use two distinct loops because EvaluateExpression may invalidate any 6851 // iterators into CurrentIterVals. 6852 for (const auto &I : PHIsToCompute) { 6853 PHINode *PHI = I.first; 6854 Constant *&NextPHI = NextIterVals[PHI]; 6855 if (!NextPHI) { // Not already computed. 6856 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6857 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6858 } 6859 if (NextPHI != I.second) 6860 StoppedEvolving = false; 6861 } 6862 6863 // If all entries in CurrentIterVals == NextIterVals then we can stop 6864 // iterating, the loop can't continue to change. 6865 if (StoppedEvolving) 6866 return RetVal = CurrentIterVals[PN]; 6867 6868 CurrentIterVals.swap(NextIterVals); 6869 } 6870 } 6871 6872 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6873 Value *Cond, 6874 bool ExitWhen) { 6875 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6876 if (!PN) return getCouldNotCompute(); 6877 6878 // If the loop is canonicalized, the PHI will have exactly two entries. 6879 // That's the only form we support here. 6880 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6881 6882 DenseMap<Instruction *, Constant *> CurrentIterVals; 6883 BasicBlock *Header = L->getHeader(); 6884 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6885 6886 BasicBlock *Latch = L->getLoopLatch(); 6887 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6888 6889 for (auto &I : *Header) { 6890 PHINode *PHI = dyn_cast<PHINode>(&I); 6891 if (!PHI) 6892 break; 6893 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6894 if (!StartCST) continue; 6895 CurrentIterVals[PHI] = StartCST; 6896 } 6897 if (!CurrentIterVals.count(PN)) 6898 return getCouldNotCompute(); 6899 6900 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6901 // the loop symbolically to determine when the condition gets a value of 6902 // "ExitWhen". 6903 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6904 const DataLayout &DL = getDataLayout(); 6905 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6906 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6907 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6908 6909 // Couldn't symbolically evaluate. 6910 if (!CondVal) return getCouldNotCompute(); 6911 6912 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6913 ++NumBruteForceTripCountsComputed; 6914 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6915 } 6916 6917 // Update all the PHI nodes for the next iteration. 6918 DenseMap<Instruction *, Constant *> NextIterVals; 6919 6920 // Create a list of which PHIs we need to compute. We want to do this before 6921 // calling EvaluateExpression on them because that may invalidate iterators 6922 // into CurrentIterVals. 6923 SmallVector<PHINode *, 8> PHIsToCompute; 6924 for (const auto &I : CurrentIterVals) { 6925 PHINode *PHI = dyn_cast<PHINode>(I.first); 6926 if (!PHI || PHI->getParent() != Header) continue; 6927 PHIsToCompute.push_back(PHI); 6928 } 6929 for (PHINode *PHI : PHIsToCompute) { 6930 Constant *&NextPHI = NextIterVals[PHI]; 6931 if (NextPHI) continue; // Already computed! 6932 6933 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6934 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6935 } 6936 CurrentIterVals.swap(NextIterVals); 6937 } 6938 6939 // Too many iterations were needed to evaluate. 6940 return getCouldNotCompute(); 6941 } 6942 6943 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6944 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6945 ValuesAtScopes[V]; 6946 // Check to see if we've folded this expression at this loop before. 6947 for (auto &LS : Values) 6948 if (LS.first == L) 6949 return LS.second ? LS.second : V; 6950 6951 Values.emplace_back(L, nullptr); 6952 6953 // Otherwise compute it. 6954 const SCEV *C = computeSCEVAtScope(V, L); 6955 for (auto &LS : reverse(ValuesAtScopes[V])) 6956 if (LS.first == L) { 6957 LS.second = C; 6958 break; 6959 } 6960 return C; 6961 } 6962 6963 /// This builds up a Constant using the ConstantExpr interface. That way, we 6964 /// will return Constants for objects which aren't represented by a 6965 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6966 /// Returns NULL if the SCEV isn't representable as a Constant. 6967 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6968 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6969 case scCouldNotCompute: 6970 case scAddRecExpr: 6971 break; 6972 case scConstant: 6973 return cast<SCEVConstant>(V)->getValue(); 6974 case scUnknown: 6975 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6976 case scSignExtend: { 6977 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6978 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6979 return ConstantExpr::getSExt(CastOp, SS->getType()); 6980 break; 6981 } 6982 case scZeroExtend: { 6983 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6984 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6985 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6986 break; 6987 } 6988 case scTruncate: { 6989 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6990 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6991 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6992 break; 6993 } 6994 case scAddExpr: { 6995 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6996 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6997 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6998 unsigned AS = PTy->getAddressSpace(); 6999 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7000 C = ConstantExpr::getBitCast(C, DestPtrTy); 7001 } 7002 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7003 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7004 if (!C2) return nullptr; 7005 7006 // First pointer! 7007 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7008 unsigned AS = C2->getType()->getPointerAddressSpace(); 7009 std::swap(C, C2); 7010 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7011 // The offsets have been converted to bytes. We can add bytes to an 7012 // i8* by GEP with the byte count in the first index. 7013 C = ConstantExpr::getBitCast(C, DestPtrTy); 7014 } 7015 7016 // Don't bother trying to sum two pointers. We probably can't 7017 // statically compute a load that results from it anyway. 7018 if (C2->getType()->isPointerTy()) 7019 return nullptr; 7020 7021 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7022 if (PTy->getElementType()->isStructTy()) 7023 C2 = ConstantExpr::getIntegerCast( 7024 C2, Type::getInt32Ty(C->getContext()), true); 7025 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7026 } else 7027 C = ConstantExpr::getAdd(C, C2); 7028 } 7029 return C; 7030 } 7031 break; 7032 } 7033 case scMulExpr: { 7034 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7035 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7036 // Don't bother with pointers at all. 7037 if (C->getType()->isPointerTy()) return nullptr; 7038 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7039 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7040 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7041 C = ConstantExpr::getMul(C, C2); 7042 } 7043 return C; 7044 } 7045 break; 7046 } 7047 case scUDivExpr: { 7048 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7049 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7050 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7051 if (LHS->getType() == RHS->getType()) 7052 return ConstantExpr::getUDiv(LHS, RHS); 7053 break; 7054 } 7055 case scSMaxExpr: 7056 case scUMaxExpr: 7057 break; // TODO: smax, umax. 7058 } 7059 return nullptr; 7060 } 7061 7062 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7063 if (isa<SCEVConstant>(V)) return V; 7064 7065 // If this instruction is evolved from a constant-evolving PHI, compute the 7066 // exit value from the loop without using SCEVs. 7067 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7068 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7069 const Loop *LI = this->LI[I->getParent()]; 7070 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7071 if (PHINode *PN = dyn_cast<PHINode>(I)) 7072 if (PN->getParent() == LI->getHeader()) { 7073 // Okay, there is no closed form solution for the PHI node. Check 7074 // to see if the loop that contains it has a known backedge-taken 7075 // count. If so, we may be able to force computation of the exit 7076 // value. 7077 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7078 if (const SCEVConstant *BTCC = 7079 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7080 // Okay, we know how many times the containing loop executes. If 7081 // this is a constant evolving PHI node, get the final value at 7082 // the specified iteration number. 7083 Constant *RV = 7084 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7085 if (RV) return getSCEV(RV); 7086 } 7087 } 7088 7089 // Okay, this is an expression that we cannot symbolically evaluate 7090 // into a SCEV. Check to see if it's possible to symbolically evaluate 7091 // the arguments into constants, and if so, try to constant propagate the 7092 // result. This is particularly useful for computing loop exit values. 7093 if (CanConstantFold(I)) { 7094 SmallVector<Constant *, 4> Operands; 7095 bool MadeImprovement = false; 7096 for (Value *Op : I->operands()) { 7097 if (Constant *C = dyn_cast<Constant>(Op)) { 7098 Operands.push_back(C); 7099 continue; 7100 } 7101 7102 // If any of the operands is non-constant and if they are 7103 // non-integer and non-pointer, don't even try to analyze them 7104 // with scev techniques. 7105 if (!isSCEVable(Op->getType())) 7106 return V; 7107 7108 const SCEV *OrigV = getSCEV(Op); 7109 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7110 MadeImprovement |= OrigV != OpV; 7111 7112 Constant *C = BuildConstantFromSCEV(OpV); 7113 if (!C) return V; 7114 if (C->getType() != Op->getType()) 7115 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7116 Op->getType(), 7117 false), 7118 C, Op->getType()); 7119 Operands.push_back(C); 7120 } 7121 7122 // Check to see if getSCEVAtScope actually made an improvement. 7123 if (MadeImprovement) { 7124 Constant *C = nullptr; 7125 const DataLayout &DL = getDataLayout(); 7126 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7127 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7128 Operands[1], DL, &TLI); 7129 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7130 if (!LI->isVolatile()) 7131 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7132 } else 7133 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7134 if (!C) return V; 7135 return getSCEV(C); 7136 } 7137 } 7138 } 7139 7140 // This is some other type of SCEVUnknown, just return it. 7141 return V; 7142 } 7143 7144 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7145 // Avoid performing the look-up in the common case where the specified 7146 // expression has no loop-variant portions. 7147 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7148 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7149 if (OpAtScope != Comm->getOperand(i)) { 7150 // Okay, at least one of these operands is loop variant but might be 7151 // foldable. Build a new instance of the folded commutative expression. 7152 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7153 Comm->op_begin()+i); 7154 NewOps.push_back(OpAtScope); 7155 7156 for (++i; i != e; ++i) { 7157 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7158 NewOps.push_back(OpAtScope); 7159 } 7160 if (isa<SCEVAddExpr>(Comm)) 7161 return getAddExpr(NewOps); 7162 if (isa<SCEVMulExpr>(Comm)) 7163 return getMulExpr(NewOps); 7164 if (isa<SCEVSMaxExpr>(Comm)) 7165 return getSMaxExpr(NewOps); 7166 if (isa<SCEVUMaxExpr>(Comm)) 7167 return getUMaxExpr(NewOps); 7168 llvm_unreachable("Unknown commutative SCEV type!"); 7169 } 7170 } 7171 // If we got here, all operands are loop invariant. 7172 return Comm; 7173 } 7174 7175 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7176 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7177 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7178 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7179 return Div; // must be loop invariant 7180 return getUDivExpr(LHS, RHS); 7181 } 7182 7183 // If this is a loop recurrence for a loop that does not contain L, then we 7184 // are dealing with the final value computed by the loop. 7185 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7186 // First, attempt to evaluate each operand. 7187 // Avoid performing the look-up in the common case where the specified 7188 // expression has no loop-variant portions. 7189 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7190 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7191 if (OpAtScope == AddRec->getOperand(i)) 7192 continue; 7193 7194 // Okay, at least one of these operands is loop variant but might be 7195 // foldable. Build a new instance of the folded commutative expression. 7196 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7197 AddRec->op_begin()+i); 7198 NewOps.push_back(OpAtScope); 7199 for (++i; i != e; ++i) 7200 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7201 7202 const SCEV *FoldedRec = 7203 getAddRecExpr(NewOps, AddRec->getLoop(), 7204 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7205 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7206 // The addrec may be folded to a nonrecurrence, for example, if the 7207 // induction variable is multiplied by zero after constant folding. Go 7208 // ahead and return the folded value. 7209 if (!AddRec) 7210 return FoldedRec; 7211 break; 7212 } 7213 7214 // If the scope is outside the addrec's loop, evaluate it by using the 7215 // loop exit value of the addrec. 7216 if (!AddRec->getLoop()->contains(L)) { 7217 // To evaluate this recurrence, we need to know how many times the AddRec 7218 // loop iterates. Compute this now. 7219 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7220 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7221 7222 // Then, evaluate the AddRec. 7223 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7224 } 7225 7226 return AddRec; 7227 } 7228 7229 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7230 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7231 if (Op == Cast->getOperand()) 7232 return Cast; // must be loop invariant 7233 return getZeroExtendExpr(Op, Cast->getType()); 7234 } 7235 7236 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7237 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7238 if (Op == Cast->getOperand()) 7239 return Cast; // must be loop invariant 7240 return getSignExtendExpr(Op, Cast->getType()); 7241 } 7242 7243 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7244 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7245 if (Op == Cast->getOperand()) 7246 return Cast; // must be loop invariant 7247 return getTruncateExpr(Op, Cast->getType()); 7248 } 7249 7250 llvm_unreachable("Unknown SCEV type!"); 7251 } 7252 7253 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7254 return getSCEVAtScope(getSCEV(V), L); 7255 } 7256 7257 /// Finds the minimum unsigned root of the following equation: 7258 /// 7259 /// A * X = B (mod N) 7260 /// 7261 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7262 /// A and B isn't important. 7263 /// 7264 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7265 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7266 ScalarEvolution &SE) { 7267 uint32_t BW = A.getBitWidth(); 7268 assert(BW == SE.getTypeSizeInBits(B->getType())); 7269 assert(A != 0 && "A must be non-zero."); 7270 7271 // 1. D = gcd(A, N) 7272 // 7273 // The gcd of A and N may have only one prime factor: 2. The number of 7274 // trailing zeros in A is its multiplicity 7275 uint32_t Mult2 = A.countTrailingZeros(); 7276 // D = 2^Mult2 7277 7278 // 2. Check if B is divisible by D. 7279 // 7280 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7281 // is not less than multiplicity of this prime factor for D. 7282 if (SE.GetMinTrailingZeros(B) < Mult2) 7283 return SE.getCouldNotCompute(); 7284 7285 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7286 // modulo (N / D). 7287 // 7288 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7289 // (N / D) in general. The inverse itself always fits into BW bits, though, 7290 // so we immediately truncate it. 7291 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7292 APInt Mod(BW + 1, 0); 7293 Mod.setBit(BW - Mult2); // Mod = N / D 7294 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7295 7296 // 4. Compute the minimum unsigned root of the equation: 7297 // I * (B / D) mod (N / D) 7298 // To simplify the computation, we factor out the divide by D: 7299 // (I * B mod N) / D 7300 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7301 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7302 } 7303 7304 /// Find the roots of the quadratic equation for the given quadratic chrec 7305 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7306 /// two SCEVCouldNotCompute objects. 7307 /// 7308 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7309 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7310 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7311 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7312 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7313 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7314 7315 // We currently can only solve this if the coefficients are constants. 7316 if (!LC || !MC || !NC) 7317 return None; 7318 7319 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7320 const APInt &L = LC->getAPInt(); 7321 const APInt &M = MC->getAPInt(); 7322 const APInt &N = NC->getAPInt(); 7323 APInt Two(BitWidth, 2); 7324 APInt Four(BitWidth, 4); 7325 7326 { 7327 using namespace APIntOps; 7328 const APInt& C = L; 7329 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7330 // The B coefficient is M-N/2 7331 APInt B(M); 7332 B -= N.sdiv(Two); 7333 7334 // The A coefficient is N/2 7335 APInt A(N.sdiv(Two)); 7336 7337 // Compute the B^2-4ac term. 7338 APInt SqrtTerm(B); 7339 SqrtTerm *= B; 7340 SqrtTerm -= Four * (A * C); 7341 7342 if (SqrtTerm.isNegative()) { 7343 // The loop is provably infinite. 7344 return None; 7345 } 7346 7347 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7348 // integer value or else APInt::sqrt() will assert. 7349 APInt SqrtVal(SqrtTerm.sqrt()); 7350 7351 // Compute the two solutions for the quadratic formula. 7352 // The divisions must be performed as signed divisions. 7353 APInt NegB(-B); 7354 APInt TwoA(A << 1); 7355 if (TwoA.isMinValue()) 7356 return None; 7357 7358 LLVMContext &Context = SE.getContext(); 7359 7360 ConstantInt *Solution1 = 7361 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7362 ConstantInt *Solution2 = 7363 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7364 7365 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7366 cast<SCEVConstant>(SE.getConstant(Solution2))); 7367 } // end APIntOps namespace 7368 } 7369 7370 ScalarEvolution::ExitLimit 7371 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7372 bool AllowPredicates) { 7373 7374 // This is only used for loops with a "x != y" exit test. The exit condition 7375 // is now expressed as a single expression, V = x-y. So the exit test is 7376 // effectively V != 0. We know and take advantage of the fact that this 7377 // expression only being used in a comparison by zero context. 7378 7379 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7380 // If the value is a constant 7381 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7382 // If the value is already zero, the branch will execute zero times. 7383 if (C->getValue()->isZero()) return C; 7384 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7385 } 7386 7387 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7388 if (!AddRec && AllowPredicates) 7389 // Try to make this an AddRec using runtime tests, in the first X 7390 // iterations of this loop, where X is the SCEV expression found by the 7391 // algorithm below. 7392 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7393 7394 if (!AddRec || AddRec->getLoop() != L) 7395 return getCouldNotCompute(); 7396 7397 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7398 // the quadratic equation to solve it. 7399 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7400 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7401 const SCEVConstant *R1 = Roots->first; 7402 const SCEVConstant *R2 = Roots->second; 7403 // Pick the smallest positive root value. 7404 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7405 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7406 if (!CB->getZExtValue()) 7407 std::swap(R1, R2); // R1 is the minimum root now. 7408 7409 // We can only use this value if the chrec ends up with an exact zero 7410 // value at this index. When solving for "X*X != 5", for example, we 7411 // should not accept a root of 2. 7412 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7413 if (Val->isZero()) 7414 // We found a quadratic root! 7415 return ExitLimit(R1, R1, false, Predicates); 7416 } 7417 } 7418 return getCouldNotCompute(); 7419 } 7420 7421 // Otherwise we can only handle this if it is affine. 7422 if (!AddRec->isAffine()) 7423 return getCouldNotCompute(); 7424 7425 // If this is an affine expression, the execution count of this branch is 7426 // the minimum unsigned root of the following equation: 7427 // 7428 // Start + Step*N = 0 (mod 2^BW) 7429 // 7430 // equivalent to: 7431 // 7432 // Step*N = -Start (mod 2^BW) 7433 // 7434 // where BW is the common bit width of Start and Step. 7435 7436 // Get the initial value for the loop. 7437 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7438 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7439 7440 // For now we handle only constant steps. 7441 // 7442 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7443 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7444 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7445 // We have not yet seen any such cases. 7446 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7447 if (!StepC || StepC->getValue()->equalsInt(0)) 7448 return getCouldNotCompute(); 7449 7450 // For positive steps (counting up until unsigned overflow): 7451 // N = -Start/Step (as unsigned) 7452 // For negative steps (counting down to zero): 7453 // N = Start/-Step 7454 // First compute the unsigned distance from zero in the direction of Step. 7455 bool CountDown = StepC->getAPInt().isNegative(); 7456 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7457 7458 // Handle unitary steps, which cannot wraparound. 7459 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7460 // N = Distance (as unsigned) 7461 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7462 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); 7463 7464 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7465 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7466 // case, and see if we can improve the bound. 7467 // 7468 // Explicitly handling this here is necessary because getUnsignedRange 7469 // isn't context-sensitive; it doesn't know that we only care about the 7470 // range inside the loop. 7471 const SCEV *Zero = getZero(Distance->getType()); 7472 const SCEV *One = getOne(Distance->getType()); 7473 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7474 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7475 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7476 // as "unsigned_max(Distance + 1) - 1". 7477 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7478 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7479 } 7480 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7481 } 7482 7483 // If the condition controls loop exit (the loop exits only if the expression 7484 // is true) and the addition is no-wrap we can use unsigned divide to 7485 // compute the backedge count. In this case, the step may not divide the 7486 // distance, but we don't care because if the condition is "missed" the loop 7487 // will have undefined behavior due to wrapping. 7488 if (ControlsExit && AddRec->hasNoSelfWrap() && 7489 loopHasNoAbnormalExits(AddRec->getLoop())) { 7490 const SCEV *Exact = 7491 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7492 return ExitLimit(Exact, Exact, false, Predicates); 7493 } 7494 7495 // Solve the general equation. 7496 const SCEV *E = SolveLinEquationWithOverflow( 7497 StepC->getAPInt(), getNegativeSCEV(Start), *this); 7498 return ExitLimit(E, E, false, Predicates); 7499 } 7500 7501 ScalarEvolution::ExitLimit 7502 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7503 // Loops that look like: while (X == 0) are very strange indeed. We don't 7504 // handle them yet except for the trivial case. This could be expanded in the 7505 // future as needed. 7506 7507 // If the value is a constant, check to see if it is known to be non-zero 7508 // already. If so, the backedge will execute zero times. 7509 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7510 if (!C->getValue()->isNullValue()) 7511 return getZero(C->getType()); 7512 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7513 } 7514 7515 // We could implement others, but I really doubt anyone writes loops like 7516 // this, and if they did, they would already be constant folded. 7517 return getCouldNotCompute(); 7518 } 7519 7520 std::pair<BasicBlock *, BasicBlock *> 7521 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7522 // If the block has a unique predecessor, then there is no path from the 7523 // predecessor to the block that does not go through the direct edge 7524 // from the predecessor to the block. 7525 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7526 return {Pred, BB}; 7527 7528 // A loop's header is defined to be a block that dominates the loop. 7529 // If the header has a unique predecessor outside the loop, it must be 7530 // a block that has exactly one successor that can reach the loop. 7531 if (Loop *L = LI.getLoopFor(BB)) 7532 return {L->getLoopPredecessor(), L->getHeader()}; 7533 7534 return {nullptr, nullptr}; 7535 } 7536 7537 /// SCEV structural equivalence is usually sufficient for testing whether two 7538 /// expressions are equal, however for the purposes of looking for a condition 7539 /// guarding a loop, it can be useful to be a little more general, since a 7540 /// front-end may have replicated the controlling expression. 7541 /// 7542 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7543 // Quick check to see if they are the same SCEV. 7544 if (A == B) return true; 7545 7546 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7547 // Not all instructions that are "identical" compute the same value. For 7548 // instance, two distinct alloca instructions allocating the same type are 7549 // identical and do not read memory; but compute distinct values. 7550 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7551 }; 7552 7553 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7554 // two different instructions with the same value. Check for this case. 7555 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7556 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7557 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7558 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7559 if (ComputesEqualValues(AI, BI)) 7560 return true; 7561 7562 // Otherwise assume they may have a different value. 7563 return false; 7564 } 7565 7566 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7567 const SCEV *&LHS, const SCEV *&RHS, 7568 unsigned Depth) { 7569 bool Changed = false; 7570 7571 // If we hit the max recursion limit bail out. 7572 if (Depth >= 3) 7573 return false; 7574 7575 // Canonicalize a constant to the right side. 7576 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7577 // Check for both operands constant. 7578 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7579 if (ConstantExpr::getICmp(Pred, 7580 LHSC->getValue(), 7581 RHSC->getValue())->isNullValue()) 7582 goto trivially_false; 7583 else 7584 goto trivially_true; 7585 } 7586 // Otherwise swap the operands to put the constant on the right. 7587 std::swap(LHS, RHS); 7588 Pred = ICmpInst::getSwappedPredicate(Pred); 7589 Changed = true; 7590 } 7591 7592 // If we're comparing an addrec with a value which is loop-invariant in the 7593 // addrec's loop, put the addrec on the left. Also make a dominance check, 7594 // as both operands could be addrecs loop-invariant in each other's loop. 7595 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7596 const Loop *L = AR->getLoop(); 7597 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7598 std::swap(LHS, RHS); 7599 Pred = ICmpInst::getSwappedPredicate(Pred); 7600 Changed = true; 7601 } 7602 } 7603 7604 // If there's a constant operand, canonicalize comparisons with boundary 7605 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7606 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7607 const APInt &RA = RC->getAPInt(); 7608 7609 bool SimplifiedByConstantRange = false; 7610 7611 if (!ICmpInst::isEquality(Pred)) { 7612 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7613 if (ExactCR.isFullSet()) 7614 goto trivially_true; 7615 else if (ExactCR.isEmptySet()) 7616 goto trivially_false; 7617 7618 APInt NewRHS; 7619 CmpInst::Predicate NewPred; 7620 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7621 ICmpInst::isEquality(NewPred)) { 7622 // We were able to convert an inequality to an equality. 7623 Pred = NewPred; 7624 RHS = getConstant(NewRHS); 7625 Changed = SimplifiedByConstantRange = true; 7626 } 7627 } 7628 7629 if (!SimplifiedByConstantRange) { 7630 switch (Pred) { 7631 default: 7632 break; 7633 case ICmpInst::ICMP_EQ: 7634 case ICmpInst::ICMP_NE: 7635 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7636 if (!RA) 7637 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7638 if (const SCEVMulExpr *ME = 7639 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7640 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7641 ME->getOperand(0)->isAllOnesValue()) { 7642 RHS = AE->getOperand(1); 7643 LHS = ME->getOperand(1); 7644 Changed = true; 7645 } 7646 break; 7647 7648 7649 // The "Should have been caught earlier!" messages refer to the fact 7650 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7651 // should have fired on the corresponding cases, and canonicalized the 7652 // check to trivially_true or trivially_false. 7653 7654 case ICmpInst::ICMP_UGE: 7655 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7656 Pred = ICmpInst::ICMP_UGT; 7657 RHS = getConstant(RA - 1); 7658 Changed = true; 7659 break; 7660 case ICmpInst::ICMP_ULE: 7661 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7662 Pred = ICmpInst::ICMP_ULT; 7663 RHS = getConstant(RA + 1); 7664 Changed = true; 7665 break; 7666 case ICmpInst::ICMP_SGE: 7667 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7668 Pred = ICmpInst::ICMP_SGT; 7669 RHS = getConstant(RA - 1); 7670 Changed = true; 7671 break; 7672 case ICmpInst::ICMP_SLE: 7673 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7674 Pred = ICmpInst::ICMP_SLT; 7675 RHS = getConstant(RA + 1); 7676 Changed = true; 7677 break; 7678 } 7679 } 7680 } 7681 7682 // Check for obvious equality. 7683 if (HasSameValue(LHS, RHS)) { 7684 if (ICmpInst::isTrueWhenEqual(Pred)) 7685 goto trivially_true; 7686 if (ICmpInst::isFalseWhenEqual(Pred)) 7687 goto trivially_false; 7688 } 7689 7690 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7691 // adding or subtracting 1 from one of the operands. 7692 switch (Pred) { 7693 case ICmpInst::ICMP_SLE: 7694 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7695 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7696 SCEV::FlagNSW); 7697 Pred = ICmpInst::ICMP_SLT; 7698 Changed = true; 7699 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7700 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7701 SCEV::FlagNSW); 7702 Pred = ICmpInst::ICMP_SLT; 7703 Changed = true; 7704 } 7705 break; 7706 case ICmpInst::ICMP_SGE: 7707 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7708 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7709 SCEV::FlagNSW); 7710 Pred = ICmpInst::ICMP_SGT; 7711 Changed = true; 7712 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7713 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7714 SCEV::FlagNSW); 7715 Pred = ICmpInst::ICMP_SGT; 7716 Changed = true; 7717 } 7718 break; 7719 case ICmpInst::ICMP_ULE: 7720 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7721 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7722 SCEV::FlagNUW); 7723 Pred = ICmpInst::ICMP_ULT; 7724 Changed = true; 7725 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7726 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7727 Pred = ICmpInst::ICMP_ULT; 7728 Changed = true; 7729 } 7730 break; 7731 case ICmpInst::ICMP_UGE: 7732 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7733 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7734 Pred = ICmpInst::ICMP_UGT; 7735 Changed = true; 7736 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7737 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7738 SCEV::FlagNUW); 7739 Pred = ICmpInst::ICMP_UGT; 7740 Changed = true; 7741 } 7742 break; 7743 default: 7744 break; 7745 } 7746 7747 // TODO: More simplifications are possible here. 7748 7749 // Recursively simplify until we either hit a recursion limit or nothing 7750 // changes. 7751 if (Changed) 7752 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7753 7754 return Changed; 7755 7756 trivially_true: 7757 // Return 0 == 0. 7758 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7759 Pred = ICmpInst::ICMP_EQ; 7760 return true; 7761 7762 trivially_false: 7763 // Return 0 != 0. 7764 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7765 Pred = ICmpInst::ICMP_NE; 7766 return true; 7767 } 7768 7769 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7770 return getSignedRange(S).getSignedMax().isNegative(); 7771 } 7772 7773 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7774 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7775 } 7776 7777 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7778 return !getSignedRange(S).getSignedMin().isNegative(); 7779 } 7780 7781 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7782 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7783 } 7784 7785 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7786 return isKnownNegative(S) || isKnownPositive(S); 7787 } 7788 7789 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7790 const SCEV *LHS, const SCEV *RHS) { 7791 // Canonicalize the inputs first. 7792 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7793 7794 // If LHS or RHS is an addrec, check to see if the condition is true in 7795 // every iteration of the loop. 7796 // If LHS and RHS are both addrec, both conditions must be true in 7797 // every iteration of the loop. 7798 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7799 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7800 bool LeftGuarded = false; 7801 bool RightGuarded = false; 7802 if (LAR) { 7803 const Loop *L = LAR->getLoop(); 7804 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7805 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7806 if (!RAR) return true; 7807 LeftGuarded = true; 7808 } 7809 } 7810 if (RAR) { 7811 const Loop *L = RAR->getLoop(); 7812 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7813 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7814 if (!LAR) return true; 7815 RightGuarded = true; 7816 } 7817 } 7818 if (LeftGuarded && RightGuarded) 7819 return true; 7820 7821 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7822 return true; 7823 7824 // Otherwise see what can be done with known constant ranges. 7825 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7826 } 7827 7828 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7829 ICmpInst::Predicate Pred, 7830 bool &Increasing) { 7831 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7832 7833 #ifndef NDEBUG 7834 // Verify an invariant: inverting the predicate should turn a monotonically 7835 // increasing change to a monotonically decreasing one, and vice versa. 7836 bool IncreasingSwapped; 7837 bool ResultSwapped = isMonotonicPredicateImpl( 7838 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7839 7840 assert(Result == ResultSwapped && "should be able to analyze both!"); 7841 if (ResultSwapped) 7842 assert(Increasing == !IncreasingSwapped && 7843 "monotonicity should flip as we flip the predicate"); 7844 #endif 7845 7846 return Result; 7847 } 7848 7849 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7850 ICmpInst::Predicate Pred, 7851 bool &Increasing) { 7852 7853 // A zero step value for LHS means the induction variable is essentially a 7854 // loop invariant value. We don't really depend on the predicate actually 7855 // flipping from false to true (for increasing predicates, and the other way 7856 // around for decreasing predicates), all we care about is that *if* the 7857 // predicate changes then it only changes from false to true. 7858 // 7859 // A zero step value in itself is not very useful, but there may be places 7860 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7861 // as general as possible. 7862 7863 switch (Pred) { 7864 default: 7865 return false; // Conservative answer 7866 7867 case ICmpInst::ICMP_UGT: 7868 case ICmpInst::ICMP_UGE: 7869 case ICmpInst::ICMP_ULT: 7870 case ICmpInst::ICMP_ULE: 7871 if (!LHS->hasNoUnsignedWrap()) 7872 return false; 7873 7874 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7875 return true; 7876 7877 case ICmpInst::ICMP_SGT: 7878 case ICmpInst::ICMP_SGE: 7879 case ICmpInst::ICMP_SLT: 7880 case ICmpInst::ICMP_SLE: { 7881 if (!LHS->hasNoSignedWrap()) 7882 return false; 7883 7884 const SCEV *Step = LHS->getStepRecurrence(*this); 7885 7886 if (isKnownNonNegative(Step)) { 7887 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7888 return true; 7889 } 7890 7891 if (isKnownNonPositive(Step)) { 7892 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7893 return true; 7894 } 7895 7896 return false; 7897 } 7898 7899 } 7900 7901 llvm_unreachable("switch has default clause!"); 7902 } 7903 7904 bool ScalarEvolution::isLoopInvariantPredicate( 7905 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7906 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7907 const SCEV *&InvariantRHS) { 7908 7909 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7910 if (!isLoopInvariant(RHS, L)) { 7911 if (!isLoopInvariant(LHS, L)) 7912 return false; 7913 7914 std::swap(LHS, RHS); 7915 Pred = ICmpInst::getSwappedPredicate(Pred); 7916 } 7917 7918 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7919 if (!ArLHS || ArLHS->getLoop() != L) 7920 return false; 7921 7922 bool Increasing; 7923 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7924 return false; 7925 7926 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7927 // true as the loop iterates, and the backedge is control dependent on 7928 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7929 // 7930 // * if the predicate was false in the first iteration then the predicate 7931 // is never evaluated again, since the loop exits without taking the 7932 // backedge. 7933 // * if the predicate was true in the first iteration then it will 7934 // continue to be true for all future iterations since it is 7935 // monotonically increasing. 7936 // 7937 // For both the above possibilities, we can replace the loop varying 7938 // predicate with its value on the first iteration of the loop (which is 7939 // loop invariant). 7940 // 7941 // A similar reasoning applies for a monotonically decreasing predicate, by 7942 // replacing true with false and false with true in the above two bullets. 7943 7944 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7945 7946 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7947 return false; 7948 7949 InvariantPred = Pred; 7950 InvariantLHS = ArLHS->getStart(); 7951 InvariantRHS = RHS; 7952 return true; 7953 } 7954 7955 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7956 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7957 if (HasSameValue(LHS, RHS)) 7958 return ICmpInst::isTrueWhenEqual(Pred); 7959 7960 // This code is split out from isKnownPredicate because it is called from 7961 // within isLoopEntryGuardedByCond. 7962 7963 auto CheckRanges = 7964 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7965 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7966 .contains(RangeLHS); 7967 }; 7968 7969 // The check at the top of the function catches the case where the values are 7970 // known to be equal. 7971 if (Pred == CmpInst::ICMP_EQ) 7972 return false; 7973 7974 if (Pred == CmpInst::ICMP_NE) 7975 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7976 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7977 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7978 7979 if (CmpInst::isSigned(Pred)) 7980 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7981 7982 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7983 } 7984 7985 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7986 const SCEV *LHS, 7987 const SCEV *RHS) { 7988 7989 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7990 // Return Y via OutY. 7991 auto MatchBinaryAddToConst = 7992 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7993 SCEV::NoWrapFlags ExpectedFlags) { 7994 const SCEV *NonConstOp, *ConstOp; 7995 SCEV::NoWrapFlags FlagsPresent; 7996 7997 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7998 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7999 return false; 8000 8001 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8002 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8003 }; 8004 8005 APInt C; 8006 8007 switch (Pred) { 8008 default: 8009 break; 8010 8011 case ICmpInst::ICMP_SGE: 8012 std::swap(LHS, RHS); 8013 case ICmpInst::ICMP_SLE: 8014 // X s<= (X + C)<nsw> if C >= 0 8015 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8016 return true; 8017 8018 // (X + C)<nsw> s<= X if C <= 0 8019 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8020 !C.isStrictlyPositive()) 8021 return true; 8022 break; 8023 8024 case ICmpInst::ICMP_SGT: 8025 std::swap(LHS, RHS); 8026 case ICmpInst::ICMP_SLT: 8027 // X s< (X + C)<nsw> if C > 0 8028 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8029 C.isStrictlyPositive()) 8030 return true; 8031 8032 // (X + C)<nsw> s< X if C < 0 8033 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8034 return true; 8035 break; 8036 } 8037 8038 return false; 8039 } 8040 8041 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8042 const SCEV *LHS, 8043 const SCEV *RHS) { 8044 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8045 return false; 8046 8047 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8048 // the stack can result in exponential time complexity. 8049 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8050 8051 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8052 // 8053 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8054 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8055 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8056 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8057 // use isKnownPredicate later if needed. 8058 return isKnownNonNegative(RHS) && 8059 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8060 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8061 } 8062 8063 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8064 ICmpInst::Predicate Pred, 8065 const SCEV *LHS, const SCEV *RHS) { 8066 // No need to even try if we know the module has no guards. 8067 if (!HasGuards) 8068 return false; 8069 8070 return any_of(*BB, [&](Instruction &I) { 8071 using namespace llvm::PatternMatch; 8072 8073 Value *Condition; 8074 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8075 m_Value(Condition))) && 8076 isImpliedCond(Pred, LHS, RHS, Condition, false); 8077 }); 8078 } 8079 8080 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8081 /// protected by a conditional between LHS and RHS. This is used to 8082 /// to eliminate casts. 8083 bool 8084 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8085 ICmpInst::Predicate Pred, 8086 const SCEV *LHS, const SCEV *RHS) { 8087 // Interpret a null as meaning no loop, where there is obviously no guard 8088 // (interprocedural conditions notwithstanding). 8089 if (!L) return true; 8090 8091 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8092 return true; 8093 8094 BasicBlock *Latch = L->getLoopLatch(); 8095 if (!Latch) 8096 return false; 8097 8098 BranchInst *LoopContinuePredicate = 8099 dyn_cast<BranchInst>(Latch->getTerminator()); 8100 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8101 isImpliedCond(Pred, LHS, RHS, 8102 LoopContinuePredicate->getCondition(), 8103 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8104 return true; 8105 8106 // We don't want more than one activation of the following loops on the stack 8107 // -- that can lead to O(n!) time complexity. 8108 if (WalkingBEDominatingConds) 8109 return false; 8110 8111 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8112 8113 // See if we can exploit a trip count to prove the predicate. 8114 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8115 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8116 if (LatchBECount != getCouldNotCompute()) { 8117 // We know that Latch branches back to the loop header exactly 8118 // LatchBECount times. This means the backdege condition at Latch is 8119 // equivalent to "{0,+,1} u< LatchBECount". 8120 Type *Ty = LatchBECount->getType(); 8121 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8122 const SCEV *LoopCounter = 8123 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8124 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8125 LatchBECount)) 8126 return true; 8127 } 8128 8129 // Check conditions due to any @llvm.assume intrinsics. 8130 for (auto &AssumeVH : AC.assumptions()) { 8131 if (!AssumeVH) 8132 continue; 8133 auto *CI = cast<CallInst>(AssumeVH); 8134 if (!DT.dominates(CI, Latch->getTerminator())) 8135 continue; 8136 8137 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8138 return true; 8139 } 8140 8141 // If the loop is not reachable from the entry block, we risk running into an 8142 // infinite loop as we walk up into the dom tree. These loops do not matter 8143 // anyway, so we just return a conservative answer when we see them. 8144 if (!DT.isReachableFromEntry(L->getHeader())) 8145 return false; 8146 8147 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8148 return true; 8149 8150 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8151 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8152 8153 assert(DTN && "should reach the loop header before reaching the root!"); 8154 8155 BasicBlock *BB = DTN->getBlock(); 8156 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8157 return true; 8158 8159 BasicBlock *PBB = BB->getSinglePredecessor(); 8160 if (!PBB) 8161 continue; 8162 8163 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8164 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8165 continue; 8166 8167 Value *Condition = ContinuePredicate->getCondition(); 8168 8169 // If we have an edge `E` within the loop body that dominates the only 8170 // latch, the condition guarding `E` also guards the backedge. This 8171 // reasoning works only for loops with a single latch. 8172 8173 BasicBlockEdge DominatingEdge(PBB, BB); 8174 if (DominatingEdge.isSingleEdge()) { 8175 // We're constructively (and conservatively) enumerating edges within the 8176 // loop body that dominate the latch. The dominator tree better agree 8177 // with us on this: 8178 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8179 8180 if (isImpliedCond(Pred, LHS, RHS, Condition, 8181 BB != ContinuePredicate->getSuccessor(0))) 8182 return true; 8183 } 8184 } 8185 8186 return false; 8187 } 8188 8189 bool 8190 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8191 ICmpInst::Predicate Pred, 8192 const SCEV *LHS, const SCEV *RHS) { 8193 // Interpret a null as meaning no loop, where there is obviously no guard 8194 // (interprocedural conditions notwithstanding). 8195 if (!L) return false; 8196 8197 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8198 return true; 8199 8200 // Starting at the loop predecessor, climb up the predecessor chain, as long 8201 // as there are predecessors that can be found that have unique successors 8202 // leading to the original header. 8203 for (std::pair<BasicBlock *, BasicBlock *> 8204 Pair(L->getLoopPredecessor(), L->getHeader()); 8205 Pair.first; 8206 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8207 8208 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8209 return true; 8210 8211 BranchInst *LoopEntryPredicate = 8212 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8213 if (!LoopEntryPredicate || 8214 LoopEntryPredicate->isUnconditional()) 8215 continue; 8216 8217 if (isImpliedCond(Pred, LHS, RHS, 8218 LoopEntryPredicate->getCondition(), 8219 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8220 return true; 8221 } 8222 8223 // Check conditions due to any @llvm.assume intrinsics. 8224 for (auto &AssumeVH : AC.assumptions()) { 8225 if (!AssumeVH) 8226 continue; 8227 auto *CI = cast<CallInst>(AssumeVH); 8228 if (!DT.dominates(CI, L->getHeader())) 8229 continue; 8230 8231 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8232 return true; 8233 } 8234 8235 return false; 8236 } 8237 8238 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8239 const SCEV *LHS, const SCEV *RHS, 8240 Value *FoundCondValue, 8241 bool Inverse) { 8242 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8243 return false; 8244 8245 auto ClearOnExit = 8246 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8247 8248 // Recursively handle And and Or conditions. 8249 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8250 if (BO->getOpcode() == Instruction::And) { 8251 if (!Inverse) 8252 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8253 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8254 } else if (BO->getOpcode() == Instruction::Or) { 8255 if (Inverse) 8256 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8257 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8258 } 8259 } 8260 8261 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8262 if (!ICI) return false; 8263 8264 // Now that we found a conditional branch that dominates the loop or controls 8265 // the loop latch. Check to see if it is the comparison we are looking for. 8266 ICmpInst::Predicate FoundPred; 8267 if (Inverse) 8268 FoundPred = ICI->getInversePredicate(); 8269 else 8270 FoundPred = ICI->getPredicate(); 8271 8272 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8273 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8274 8275 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8276 } 8277 8278 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8279 const SCEV *RHS, 8280 ICmpInst::Predicate FoundPred, 8281 const SCEV *FoundLHS, 8282 const SCEV *FoundRHS) { 8283 // Balance the types. 8284 if (getTypeSizeInBits(LHS->getType()) < 8285 getTypeSizeInBits(FoundLHS->getType())) { 8286 if (CmpInst::isSigned(Pred)) { 8287 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8288 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8289 } else { 8290 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8291 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8292 } 8293 } else if (getTypeSizeInBits(LHS->getType()) > 8294 getTypeSizeInBits(FoundLHS->getType())) { 8295 if (CmpInst::isSigned(FoundPred)) { 8296 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8297 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8298 } else { 8299 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8300 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8301 } 8302 } 8303 8304 // Canonicalize the query to match the way instcombine will have 8305 // canonicalized the comparison. 8306 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8307 if (LHS == RHS) 8308 return CmpInst::isTrueWhenEqual(Pred); 8309 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8310 if (FoundLHS == FoundRHS) 8311 return CmpInst::isFalseWhenEqual(FoundPred); 8312 8313 // Check to see if we can make the LHS or RHS match. 8314 if (LHS == FoundRHS || RHS == FoundLHS) { 8315 if (isa<SCEVConstant>(RHS)) { 8316 std::swap(FoundLHS, FoundRHS); 8317 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8318 } else { 8319 std::swap(LHS, RHS); 8320 Pred = ICmpInst::getSwappedPredicate(Pred); 8321 } 8322 } 8323 8324 // Check whether the found predicate is the same as the desired predicate. 8325 if (FoundPred == Pred) 8326 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8327 8328 // Check whether swapping the found predicate makes it the same as the 8329 // desired predicate. 8330 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8331 if (isa<SCEVConstant>(RHS)) 8332 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8333 else 8334 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8335 RHS, LHS, FoundLHS, FoundRHS); 8336 } 8337 8338 // Unsigned comparison is the same as signed comparison when both the operands 8339 // are non-negative. 8340 if (CmpInst::isUnsigned(FoundPred) && 8341 CmpInst::getSignedPredicate(FoundPred) == Pred && 8342 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8343 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8344 8345 // Check if we can make progress by sharpening ranges. 8346 if (FoundPred == ICmpInst::ICMP_NE && 8347 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8348 8349 const SCEVConstant *C = nullptr; 8350 const SCEV *V = nullptr; 8351 8352 if (isa<SCEVConstant>(FoundLHS)) { 8353 C = cast<SCEVConstant>(FoundLHS); 8354 V = FoundRHS; 8355 } else { 8356 C = cast<SCEVConstant>(FoundRHS); 8357 V = FoundLHS; 8358 } 8359 8360 // The guarding predicate tells us that C != V. If the known range 8361 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8362 // range we consider has to correspond to same signedness as the 8363 // predicate we're interested in folding. 8364 8365 APInt Min = ICmpInst::isSigned(Pred) ? 8366 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8367 8368 if (Min == C->getAPInt()) { 8369 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8370 // This is true even if (Min + 1) wraps around -- in case of 8371 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8372 8373 APInt SharperMin = Min + 1; 8374 8375 switch (Pred) { 8376 case ICmpInst::ICMP_SGE: 8377 case ICmpInst::ICMP_UGE: 8378 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8379 // RHS, we're done. 8380 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8381 getConstant(SharperMin))) 8382 return true; 8383 8384 case ICmpInst::ICMP_SGT: 8385 case ICmpInst::ICMP_UGT: 8386 // We know from the range information that (V `Pred` Min || 8387 // V == Min). We know from the guarding condition that !(V 8388 // == Min). This gives us 8389 // 8390 // V `Pred` Min || V == Min && !(V == Min) 8391 // => V `Pred` Min 8392 // 8393 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8394 8395 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8396 return true; 8397 8398 default: 8399 // No change 8400 break; 8401 } 8402 } 8403 } 8404 8405 // Check whether the actual condition is beyond sufficient. 8406 if (FoundPred == ICmpInst::ICMP_EQ) 8407 if (ICmpInst::isTrueWhenEqual(Pred)) 8408 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8409 return true; 8410 if (Pred == ICmpInst::ICMP_NE) 8411 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8412 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8413 return true; 8414 8415 // Otherwise assume the worst. 8416 return false; 8417 } 8418 8419 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8420 const SCEV *&L, const SCEV *&R, 8421 SCEV::NoWrapFlags &Flags) { 8422 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8423 if (!AE || AE->getNumOperands() != 2) 8424 return false; 8425 8426 L = AE->getOperand(0); 8427 R = AE->getOperand(1); 8428 Flags = AE->getNoWrapFlags(); 8429 return true; 8430 } 8431 8432 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8433 const SCEV *Less) { 8434 // We avoid subtracting expressions here because this function is usually 8435 // fairly deep in the call stack (i.e. is called many times). 8436 8437 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8438 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8439 const auto *MAR = cast<SCEVAddRecExpr>(More); 8440 8441 if (LAR->getLoop() != MAR->getLoop()) 8442 return None; 8443 8444 // We look at affine expressions only; not for correctness but to keep 8445 // getStepRecurrence cheap. 8446 if (!LAR->isAffine() || !MAR->isAffine()) 8447 return None; 8448 8449 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8450 return None; 8451 8452 Less = LAR->getStart(); 8453 More = MAR->getStart(); 8454 8455 // fall through 8456 } 8457 8458 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8459 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8460 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8461 return M - L; 8462 } 8463 8464 const SCEV *L, *R; 8465 SCEV::NoWrapFlags Flags; 8466 if (splitBinaryAdd(Less, L, R, Flags)) 8467 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8468 if (R == More) 8469 return -(LC->getAPInt()); 8470 8471 if (splitBinaryAdd(More, L, R, Flags)) 8472 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8473 if (R == Less) 8474 return LC->getAPInt(); 8475 8476 return None; 8477 } 8478 8479 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8480 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8481 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8482 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8483 return false; 8484 8485 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8486 if (!AddRecLHS) 8487 return false; 8488 8489 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8490 if (!AddRecFoundLHS) 8491 return false; 8492 8493 // We'd like to let SCEV reason about control dependencies, so we constrain 8494 // both the inequalities to be about add recurrences on the same loop. This 8495 // way we can use isLoopEntryGuardedByCond later. 8496 8497 const Loop *L = AddRecFoundLHS->getLoop(); 8498 if (L != AddRecLHS->getLoop()) 8499 return false; 8500 8501 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8502 // 8503 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8504 // ... (2) 8505 // 8506 // Informal proof for (2), assuming (1) [*]: 8507 // 8508 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8509 // 8510 // Then 8511 // 8512 // FoundLHS s< FoundRHS s< INT_MIN - C 8513 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8514 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8515 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8516 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8517 // <=> FoundLHS + C s< FoundRHS + C 8518 // 8519 // [*]: (1) can be proved by ruling out overflow. 8520 // 8521 // [**]: This can be proved by analyzing all the four possibilities: 8522 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8523 // (A s>= 0, B s>= 0). 8524 // 8525 // Note: 8526 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8527 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8528 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8529 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8530 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8531 // C)". 8532 8533 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8534 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8535 if (!LDiff || !RDiff || *LDiff != *RDiff) 8536 return false; 8537 8538 if (LDiff->isMinValue()) 8539 return true; 8540 8541 APInt FoundRHSLimit; 8542 8543 if (Pred == CmpInst::ICMP_ULT) { 8544 FoundRHSLimit = -(*RDiff); 8545 } else { 8546 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8547 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8548 } 8549 8550 // Try to prove (1) or (2), as needed. 8551 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8552 getConstant(FoundRHSLimit)); 8553 } 8554 8555 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8556 const SCEV *LHS, const SCEV *RHS, 8557 const SCEV *FoundLHS, 8558 const SCEV *FoundRHS) { 8559 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8560 return true; 8561 8562 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8563 return true; 8564 8565 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8566 FoundLHS, FoundRHS) || 8567 // ~x < ~y --> x > y 8568 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8569 getNotSCEV(FoundRHS), 8570 getNotSCEV(FoundLHS)); 8571 } 8572 8573 8574 /// If Expr computes ~A, return A else return nullptr 8575 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8576 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8577 if (!Add || Add->getNumOperands() != 2 || 8578 !Add->getOperand(0)->isAllOnesValue()) 8579 return nullptr; 8580 8581 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8582 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8583 !AddRHS->getOperand(0)->isAllOnesValue()) 8584 return nullptr; 8585 8586 return AddRHS->getOperand(1); 8587 } 8588 8589 8590 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8591 template<typename MaxExprType> 8592 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8593 const SCEV *Candidate) { 8594 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8595 if (!MaxExpr) return false; 8596 8597 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8598 } 8599 8600 8601 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8602 template<typename MaxExprType> 8603 static bool IsMinConsistingOf(ScalarEvolution &SE, 8604 const SCEV *MaybeMinExpr, 8605 const SCEV *Candidate) { 8606 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8607 if (!MaybeMaxExpr) 8608 return false; 8609 8610 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8611 } 8612 8613 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8614 ICmpInst::Predicate Pred, 8615 const SCEV *LHS, const SCEV *RHS) { 8616 8617 // If both sides are affine addrecs for the same loop, with equal 8618 // steps, and we know the recurrences don't wrap, then we only 8619 // need to check the predicate on the starting values. 8620 8621 if (!ICmpInst::isRelational(Pred)) 8622 return false; 8623 8624 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8625 if (!LAR) 8626 return false; 8627 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8628 if (!RAR) 8629 return false; 8630 if (LAR->getLoop() != RAR->getLoop()) 8631 return false; 8632 if (!LAR->isAffine() || !RAR->isAffine()) 8633 return false; 8634 8635 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8636 return false; 8637 8638 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8639 SCEV::FlagNSW : SCEV::FlagNUW; 8640 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8641 return false; 8642 8643 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8644 } 8645 8646 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8647 /// expression? 8648 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8649 ICmpInst::Predicate Pred, 8650 const SCEV *LHS, const SCEV *RHS) { 8651 switch (Pred) { 8652 default: 8653 return false; 8654 8655 case ICmpInst::ICMP_SGE: 8656 std::swap(LHS, RHS); 8657 LLVM_FALLTHROUGH; 8658 case ICmpInst::ICMP_SLE: 8659 return 8660 // min(A, ...) <= A 8661 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8662 // A <= max(A, ...) 8663 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8664 8665 case ICmpInst::ICMP_UGE: 8666 std::swap(LHS, RHS); 8667 LLVM_FALLTHROUGH; 8668 case ICmpInst::ICMP_ULE: 8669 return 8670 // min(A, ...) <= A 8671 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8672 // A <= max(A, ...) 8673 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8674 } 8675 8676 llvm_unreachable("covered switch fell through?!"); 8677 } 8678 8679 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 8680 const SCEV *LHS, const SCEV *RHS, 8681 const SCEV *FoundLHS, 8682 const SCEV *FoundRHS, 8683 unsigned Depth) { 8684 assert(getTypeSizeInBits(LHS->getType()) == 8685 getTypeSizeInBits(RHS->getType()) && 8686 "LHS and RHS have different sizes?"); 8687 assert(getTypeSizeInBits(FoundLHS->getType()) == 8688 getTypeSizeInBits(FoundRHS->getType()) && 8689 "FoundLHS and FoundRHS have different sizes?"); 8690 // We want to avoid hurting the compile time with analysis of too big trees. 8691 if (Depth > MaxSCEVOperationsImplicationDepth) 8692 return false; 8693 // We only want to work with ICMP_SGT comparison so far. 8694 // TODO: Extend to ICMP_UGT? 8695 if (Pred == ICmpInst::ICMP_SLT) { 8696 Pred = ICmpInst::ICMP_SGT; 8697 std::swap(LHS, RHS); 8698 std::swap(FoundLHS, FoundRHS); 8699 } 8700 if (Pred != ICmpInst::ICMP_SGT) 8701 return false; 8702 8703 auto GetOpFromSExt = [&](const SCEV *S) { 8704 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 8705 return Ext->getOperand(); 8706 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 8707 // the constant in some cases. 8708 return S; 8709 }; 8710 8711 // Acquire values from extensions. 8712 auto *OrigFoundLHS = FoundLHS; 8713 LHS = GetOpFromSExt(LHS); 8714 FoundLHS = GetOpFromSExt(FoundLHS); 8715 8716 // Is the SGT predicate can be proved trivially or using the found context. 8717 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 8718 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 8719 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 8720 FoundRHS, Depth + 1); 8721 }; 8722 8723 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 8724 // We want to avoid creation of any new non-constant SCEV. Since we are 8725 // going to compare the operands to RHS, we should be certain that we don't 8726 // need any size extensions for this. So let's decline all cases when the 8727 // sizes of types of LHS and RHS do not match. 8728 // TODO: Maybe try to get RHS from sext to catch more cases? 8729 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 8730 return false; 8731 8732 // Should not overflow. 8733 if (!LHSAddExpr->hasNoSignedWrap()) 8734 return false; 8735 8736 auto *LL = LHSAddExpr->getOperand(0); 8737 auto *LR = LHSAddExpr->getOperand(1); 8738 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 8739 8740 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 8741 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 8742 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 8743 }; 8744 // Try to prove the following rule: 8745 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 8746 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 8747 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 8748 return true; 8749 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 8750 Value *LL, *LR; 8751 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 8752 using namespace llvm::PatternMatch; 8753 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 8754 // Rules for division. 8755 // We are going to perform some comparisons with Denominator and its 8756 // derivative expressions. In general case, creating a SCEV for it may 8757 // lead to a complex analysis of the entire graph, and in particular it 8758 // can request trip count recalculation for the same loop. This would 8759 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 8760 // this, we only want to create SCEVs that are constants in this section. 8761 // So we bail if Denominator is not a constant. 8762 if (!isa<ConstantInt>(LR)) 8763 return false; 8764 8765 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 8766 8767 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 8768 // then a SCEV for the numerator already exists and matches with FoundLHS. 8769 auto *Numerator = getExistingSCEV(LL); 8770 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 8771 return false; 8772 8773 // Make sure that the numerator matches with FoundLHS and the denominator 8774 // is positive. 8775 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 8776 return false; 8777 8778 auto *DTy = Denominator->getType(); 8779 auto *FRHSTy = FoundRHS->getType(); 8780 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 8781 // One of types is a pointer and another one is not. We cannot extend 8782 // them properly to a wider type, so let us just reject this case. 8783 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 8784 // to avoid this check. 8785 return false; 8786 8787 // Given that: 8788 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 8789 auto *WTy = getWiderType(DTy, FRHSTy); 8790 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 8791 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 8792 8793 // Try to prove the following rule: 8794 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 8795 // For example, given that FoundLHS > 2. It means that FoundLHS is at 8796 // least 3. If we divide it by Denominator < 4, we will have at least 1. 8797 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 8798 if (isKnownNonPositive(RHS) && 8799 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 8800 return true; 8801 8802 // Try to prove the following rule: 8803 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 8804 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 8805 // If we divide it by Denominator > 2, then: 8806 // 1. If FoundLHS is negative, then the result is 0. 8807 // 2. If FoundLHS is non-negative, then the result is non-negative. 8808 // Anyways, the result is non-negative. 8809 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 8810 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 8811 if (isKnownNegative(RHS) && 8812 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 8813 return true; 8814 } 8815 } 8816 8817 return false; 8818 } 8819 8820 bool 8821 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 8822 const SCEV *LHS, const SCEV *RHS) { 8823 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8824 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8825 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8826 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8827 } 8828 8829 bool 8830 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8831 const SCEV *LHS, const SCEV *RHS, 8832 const SCEV *FoundLHS, 8833 const SCEV *FoundRHS) { 8834 switch (Pred) { 8835 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8836 case ICmpInst::ICMP_EQ: 8837 case ICmpInst::ICMP_NE: 8838 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8839 return true; 8840 break; 8841 case ICmpInst::ICMP_SLT: 8842 case ICmpInst::ICMP_SLE: 8843 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8844 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8845 return true; 8846 break; 8847 case ICmpInst::ICMP_SGT: 8848 case ICmpInst::ICMP_SGE: 8849 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8850 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8851 return true; 8852 break; 8853 case ICmpInst::ICMP_ULT: 8854 case ICmpInst::ICMP_ULE: 8855 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8856 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8857 return true; 8858 break; 8859 case ICmpInst::ICMP_UGT: 8860 case ICmpInst::ICMP_UGE: 8861 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8862 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8863 return true; 8864 break; 8865 } 8866 8867 // Maybe it can be proved via operations? 8868 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8869 return true; 8870 8871 return false; 8872 } 8873 8874 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8875 const SCEV *LHS, 8876 const SCEV *RHS, 8877 const SCEV *FoundLHS, 8878 const SCEV *FoundRHS) { 8879 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8880 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8881 // reduce the compile time impact of this optimization. 8882 return false; 8883 8884 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8885 if (!Addend) 8886 return false; 8887 8888 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8889 8890 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8891 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8892 ConstantRange FoundLHSRange = 8893 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8894 8895 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8896 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8897 8898 // We can also compute the range of values for `LHS` that satisfy the 8899 // consequent, "`LHS` `Pred` `RHS`": 8900 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8901 ConstantRange SatisfyingLHSRange = 8902 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8903 8904 // The antecedent implies the consequent if every value of `LHS` that 8905 // satisfies the antecedent also satisfies the consequent. 8906 return SatisfyingLHSRange.contains(LHSRange); 8907 } 8908 8909 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8910 bool IsSigned, bool NoWrap) { 8911 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8912 8913 if (NoWrap) return false; 8914 8915 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8916 const SCEV *One = getOne(Stride->getType()); 8917 8918 if (IsSigned) { 8919 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8920 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8921 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8922 .getSignedMax(); 8923 8924 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8925 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8926 } 8927 8928 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8929 APInt MaxValue = APInt::getMaxValue(BitWidth); 8930 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8931 .getUnsignedMax(); 8932 8933 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8934 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8935 } 8936 8937 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8938 bool IsSigned, bool NoWrap) { 8939 if (NoWrap) return false; 8940 8941 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8942 const SCEV *One = getOne(Stride->getType()); 8943 8944 if (IsSigned) { 8945 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8946 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8947 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8948 .getSignedMax(); 8949 8950 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8951 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8952 } 8953 8954 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8955 APInt MinValue = APInt::getMinValue(BitWidth); 8956 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8957 .getUnsignedMax(); 8958 8959 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8960 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8961 } 8962 8963 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8964 bool Equality) { 8965 const SCEV *One = getOne(Step->getType()); 8966 Delta = Equality ? getAddExpr(Delta, Step) 8967 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8968 return getUDivExpr(Delta, Step); 8969 } 8970 8971 ScalarEvolution::ExitLimit 8972 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8973 const Loop *L, bool IsSigned, 8974 bool ControlsExit, bool AllowPredicates) { 8975 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8976 // We handle only IV < Invariant 8977 if (!isLoopInvariant(RHS, L)) 8978 return getCouldNotCompute(); 8979 8980 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8981 bool PredicatedIV = false; 8982 8983 if (!IV && AllowPredicates) { 8984 // Try to make this an AddRec using runtime tests, in the first X 8985 // iterations of this loop, where X is the SCEV expression found by the 8986 // algorithm below. 8987 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8988 PredicatedIV = true; 8989 } 8990 8991 // Avoid weird loops 8992 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8993 return getCouldNotCompute(); 8994 8995 bool NoWrap = ControlsExit && 8996 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8997 8998 const SCEV *Stride = IV->getStepRecurrence(*this); 8999 9000 bool PositiveStride = isKnownPositive(Stride); 9001 9002 // Avoid negative or zero stride values. 9003 if (!PositiveStride) { 9004 // We can compute the correct backedge taken count for loops with unknown 9005 // strides if we can prove that the loop is not an infinite loop with side 9006 // effects. Here's the loop structure we are trying to handle - 9007 // 9008 // i = start 9009 // do { 9010 // A[i] = i; 9011 // i += s; 9012 // } while (i < end); 9013 // 9014 // The backedge taken count for such loops is evaluated as - 9015 // (max(end, start + stride) - start - 1) /u stride 9016 // 9017 // The additional preconditions that we need to check to prove correctness 9018 // of the above formula is as follows - 9019 // 9020 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9021 // NoWrap flag). 9022 // b) loop is single exit with no side effects. 9023 // 9024 // 9025 // Precondition a) implies that if the stride is negative, this is a single 9026 // trip loop. The backedge taken count formula reduces to zero in this case. 9027 // 9028 // Precondition b) implies that the unknown stride cannot be zero otherwise 9029 // we have UB. 9030 // 9031 // The positive stride case is the same as isKnownPositive(Stride) returning 9032 // true (original behavior of the function). 9033 // 9034 // We want to make sure that the stride is truly unknown as there are edge 9035 // cases where ScalarEvolution propagates no wrap flags to the 9036 // post-increment/decrement IV even though the increment/decrement operation 9037 // itself is wrapping. The computed backedge taken count may be wrong in 9038 // such cases. This is prevented by checking that the stride is not known to 9039 // be either positive or non-positive. For example, no wrap flags are 9040 // propagated to the post-increment IV of this loop with a trip count of 2 - 9041 // 9042 // unsigned char i; 9043 // for(i=127; i<128; i+=129) 9044 // A[i] = i; 9045 // 9046 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9047 !loopHasNoSideEffects(L)) 9048 return getCouldNotCompute(); 9049 9050 } else if (!Stride->isOne() && 9051 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9052 // Avoid proven overflow cases: this will ensure that the backedge taken 9053 // count will not generate any unsigned overflow. Relaxed no-overflow 9054 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9055 // undefined behaviors like the case of C language. 9056 return getCouldNotCompute(); 9057 9058 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9059 : ICmpInst::ICMP_ULT; 9060 const SCEV *Start = IV->getStart(); 9061 const SCEV *End = RHS; 9062 // If the backedge is taken at least once, then it will be taken 9063 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9064 // is the LHS value of the less-than comparison the first time it is evaluated 9065 // and End is the RHS. 9066 const SCEV *BECountIfBackedgeTaken = 9067 computeBECount(getMinusSCEV(End, Start), Stride, false); 9068 // If the loop entry is guarded by the result of the backedge test of the 9069 // first loop iteration, then we know the backedge will be taken at least 9070 // once and so the backedge taken count is as above. If not then we use the 9071 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9072 // as if the backedge is taken at least once max(End,Start) is End and so the 9073 // result is as above, and if not max(End,Start) is Start so we get a backedge 9074 // count of zero. 9075 const SCEV *BECount; 9076 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9077 BECount = BECountIfBackedgeTaken; 9078 else { 9079 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9080 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9081 } 9082 9083 const SCEV *MaxBECount; 9084 bool MaxOrZero = false; 9085 if (isa<SCEVConstant>(BECount)) 9086 MaxBECount = BECount; 9087 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9088 // If we know exactly how many times the backedge will be taken if it's 9089 // taken at least once, then the backedge count will either be that or 9090 // zero. 9091 MaxBECount = BECountIfBackedgeTaken; 9092 MaxOrZero = true; 9093 } else { 9094 // Calculate the maximum backedge count based on the range of values 9095 // permitted by Start, End, and Stride. 9096 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 9097 : getUnsignedRange(Start).getUnsignedMin(); 9098 9099 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9100 9101 APInt StrideForMaxBECount; 9102 9103 if (PositiveStride) 9104 StrideForMaxBECount = 9105 IsSigned ? getSignedRange(Stride).getSignedMin() 9106 : getUnsignedRange(Stride).getUnsignedMin(); 9107 else 9108 // Using a stride of 1 is safe when computing max backedge taken count for 9109 // a loop with unknown stride. 9110 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9111 9112 APInt Limit = 9113 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9114 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9115 9116 // Although End can be a MAX expression we estimate MaxEnd considering only 9117 // the case End = RHS. This is safe because in the other case (End - Start) 9118 // is zero, leading to a zero maximum backedge taken count. 9119 APInt MaxEnd = 9120 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 9121 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 9122 9123 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9124 getConstant(StrideForMaxBECount), false); 9125 } 9126 9127 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9128 MaxBECount = BECount; 9129 9130 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9131 } 9132 9133 ScalarEvolution::ExitLimit 9134 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9135 const Loop *L, bool IsSigned, 9136 bool ControlsExit, bool AllowPredicates) { 9137 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9138 // We handle only IV > Invariant 9139 if (!isLoopInvariant(RHS, L)) 9140 return getCouldNotCompute(); 9141 9142 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9143 if (!IV && AllowPredicates) 9144 // Try to make this an AddRec using runtime tests, in the first X 9145 // iterations of this loop, where X is the SCEV expression found by the 9146 // algorithm below. 9147 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9148 9149 // Avoid weird loops 9150 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9151 return getCouldNotCompute(); 9152 9153 bool NoWrap = ControlsExit && 9154 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9155 9156 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9157 9158 // Avoid negative or zero stride values 9159 if (!isKnownPositive(Stride)) 9160 return getCouldNotCompute(); 9161 9162 // Avoid proven overflow cases: this will ensure that the backedge taken count 9163 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9164 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9165 // behaviors like the case of C language. 9166 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9167 return getCouldNotCompute(); 9168 9169 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9170 : ICmpInst::ICMP_UGT; 9171 9172 const SCEV *Start = IV->getStart(); 9173 const SCEV *End = RHS; 9174 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9175 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9176 9177 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9178 9179 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 9180 : getUnsignedRange(Start).getUnsignedMax(); 9181 9182 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 9183 : getUnsignedRange(Stride).getUnsignedMin(); 9184 9185 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9186 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9187 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9188 9189 // Although End can be a MIN expression we estimate MinEnd considering only 9190 // the case End = RHS. This is safe because in the other case (Start - End) 9191 // is zero, leading to a zero maximum backedge taken count. 9192 APInt MinEnd = 9193 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 9194 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 9195 9196 9197 const SCEV *MaxBECount = getCouldNotCompute(); 9198 if (isa<SCEVConstant>(BECount)) 9199 MaxBECount = BECount; 9200 else 9201 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9202 getConstant(MinStride), false); 9203 9204 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9205 MaxBECount = BECount; 9206 9207 return ExitLimit(BECount, MaxBECount, false, Predicates); 9208 } 9209 9210 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9211 ScalarEvolution &SE) const { 9212 if (Range.isFullSet()) // Infinite loop. 9213 return SE.getCouldNotCompute(); 9214 9215 // If the start is a non-zero constant, shift the range to simplify things. 9216 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9217 if (!SC->getValue()->isZero()) { 9218 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9219 Operands[0] = SE.getZero(SC->getType()); 9220 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9221 getNoWrapFlags(FlagNW)); 9222 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9223 return ShiftedAddRec->getNumIterationsInRange( 9224 Range.subtract(SC->getAPInt()), SE); 9225 // This is strange and shouldn't happen. 9226 return SE.getCouldNotCompute(); 9227 } 9228 9229 // The only time we can solve this is when we have all constant indices. 9230 // Otherwise, we cannot determine the overflow conditions. 9231 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9232 return SE.getCouldNotCompute(); 9233 9234 // Okay at this point we know that all elements of the chrec are constants and 9235 // that the start element is zero. 9236 9237 // First check to see if the range contains zero. If not, the first 9238 // iteration exits. 9239 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9240 if (!Range.contains(APInt(BitWidth, 0))) 9241 return SE.getZero(getType()); 9242 9243 if (isAffine()) { 9244 // If this is an affine expression then we have this situation: 9245 // Solve {0,+,A} in Range === Ax in Range 9246 9247 // We know that zero is in the range. If A is positive then we know that 9248 // the upper value of the range must be the first possible exit value. 9249 // If A is negative then the lower of the range is the last possible loop 9250 // value. Also note that we already checked for a full range. 9251 APInt One(BitWidth,1); 9252 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9253 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 9254 9255 // The exit value should be (End+A)/A. 9256 APInt ExitVal = (End + A).udiv(A); 9257 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9258 9259 // Evaluate at the exit value. If we really did fall out of the valid 9260 // range, then we computed our trip count, otherwise wrap around or other 9261 // things must have happened. 9262 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9263 if (Range.contains(Val->getValue())) 9264 return SE.getCouldNotCompute(); // Something strange happened 9265 9266 // Ensure that the previous value is in the range. This is a sanity check. 9267 assert(Range.contains( 9268 EvaluateConstantChrecAtConstant(this, 9269 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 9270 "Linear scev computation is off in a bad way!"); 9271 return SE.getConstant(ExitValue); 9272 } else if (isQuadratic()) { 9273 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9274 // quadratic equation to solve it. To do this, we must frame our problem in 9275 // terms of figuring out when zero is crossed, instead of when 9276 // Range.getUpper() is crossed. 9277 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9278 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9279 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9280 9281 // Next, solve the constructed addrec 9282 if (auto Roots = 9283 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9284 const SCEVConstant *R1 = Roots->first; 9285 const SCEVConstant *R2 = Roots->second; 9286 // Pick the smallest positive root value. 9287 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9288 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9289 if (!CB->getZExtValue()) 9290 std::swap(R1, R2); // R1 is the minimum root now. 9291 9292 // Make sure the root is not off by one. The returned iteration should 9293 // not be in the range, but the previous one should be. When solving 9294 // for "X*X < 5", for example, we should not return a root of 2. 9295 ConstantInt *R1Val = 9296 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9297 if (Range.contains(R1Val->getValue())) { 9298 // The next iteration must be out of the range... 9299 ConstantInt *NextVal = 9300 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9301 9302 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9303 if (!Range.contains(R1Val->getValue())) 9304 return SE.getConstant(NextVal); 9305 return SE.getCouldNotCompute(); // Something strange happened 9306 } 9307 9308 // If R1 was not in the range, then it is a good return value. Make 9309 // sure that R1-1 WAS in the range though, just in case. 9310 ConstantInt *NextVal = 9311 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9312 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9313 if (Range.contains(R1Val->getValue())) 9314 return R1; 9315 return SE.getCouldNotCompute(); // Something strange happened 9316 } 9317 } 9318 } 9319 9320 return SE.getCouldNotCompute(); 9321 } 9322 9323 // Return true when S contains at least an undef value. 9324 static inline bool containsUndefs(const SCEV *S) { 9325 return SCEVExprContains(S, [](const SCEV *S) { 9326 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9327 return isa<UndefValue>(SU->getValue()); 9328 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9329 return isa<UndefValue>(SC->getValue()); 9330 return false; 9331 }); 9332 } 9333 9334 namespace { 9335 // Collect all steps of SCEV expressions. 9336 struct SCEVCollectStrides { 9337 ScalarEvolution &SE; 9338 SmallVectorImpl<const SCEV *> &Strides; 9339 9340 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9341 : SE(SE), Strides(S) {} 9342 9343 bool follow(const SCEV *S) { 9344 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9345 Strides.push_back(AR->getStepRecurrence(SE)); 9346 return true; 9347 } 9348 bool isDone() const { return false; } 9349 }; 9350 9351 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9352 struct SCEVCollectTerms { 9353 SmallVectorImpl<const SCEV *> &Terms; 9354 9355 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9356 : Terms(T) {} 9357 9358 bool follow(const SCEV *S) { 9359 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9360 isa<SCEVSignExtendExpr>(S)) { 9361 if (!containsUndefs(S)) 9362 Terms.push_back(S); 9363 9364 // Stop recursion: once we collected a term, do not walk its operands. 9365 return false; 9366 } 9367 9368 // Keep looking. 9369 return true; 9370 } 9371 bool isDone() const { return false; } 9372 }; 9373 9374 // Check if a SCEV contains an AddRecExpr. 9375 struct SCEVHasAddRec { 9376 bool &ContainsAddRec; 9377 9378 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9379 ContainsAddRec = false; 9380 } 9381 9382 bool follow(const SCEV *S) { 9383 if (isa<SCEVAddRecExpr>(S)) { 9384 ContainsAddRec = true; 9385 9386 // Stop recursion: once we collected a term, do not walk its operands. 9387 return false; 9388 } 9389 9390 // Keep looking. 9391 return true; 9392 } 9393 bool isDone() const { return false; } 9394 }; 9395 9396 // Find factors that are multiplied with an expression that (possibly as a 9397 // subexpression) contains an AddRecExpr. In the expression: 9398 // 9399 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9400 // 9401 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9402 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9403 // parameters as they form a product with an induction variable. 9404 // 9405 // This collector expects all array size parameters to be in the same MulExpr. 9406 // It might be necessary to later add support for collecting parameters that are 9407 // spread over different nested MulExpr. 9408 struct SCEVCollectAddRecMultiplies { 9409 SmallVectorImpl<const SCEV *> &Terms; 9410 ScalarEvolution &SE; 9411 9412 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9413 : Terms(T), SE(SE) {} 9414 9415 bool follow(const SCEV *S) { 9416 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9417 bool HasAddRec = false; 9418 SmallVector<const SCEV *, 0> Operands; 9419 for (auto Op : Mul->operands()) { 9420 if (isa<SCEVUnknown>(Op)) { 9421 Operands.push_back(Op); 9422 } else { 9423 bool ContainsAddRec; 9424 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9425 visitAll(Op, ContiansAddRec); 9426 HasAddRec |= ContainsAddRec; 9427 } 9428 } 9429 if (Operands.size() == 0) 9430 return true; 9431 9432 if (!HasAddRec) 9433 return false; 9434 9435 Terms.push_back(SE.getMulExpr(Operands)); 9436 // Stop recursion: once we collected a term, do not walk its operands. 9437 return false; 9438 } 9439 9440 // Keep looking. 9441 return true; 9442 } 9443 bool isDone() const { return false; } 9444 }; 9445 } 9446 9447 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9448 /// two places: 9449 /// 1) The strides of AddRec expressions. 9450 /// 2) Unknowns that are multiplied with AddRec expressions. 9451 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9452 SmallVectorImpl<const SCEV *> &Terms) { 9453 SmallVector<const SCEV *, 4> Strides; 9454 SCEVCollectStrides StrideCollector(*this, Strides); 9455 visitAll(Expr, StrideCollector); 9456 9457 DEBUG({ 9458 dbgs() << "Strides:\n"; 9459 for (const SCEV *S : Strides) 9460 dbgs() << *S << "\n"; 9461 }); 9462 9463 for (const SCEV *S : Strides) { 9464 SCEVCollectTerms TermCollector(Terms); 9465 visitAll(S, TermCollector); 9466 } 9467 9468 DEBUG({ 9469 dbgs() << "Terms:\n"; 9470 for (const SCEV *T : Terms) 9471 dbgs() << *T << "\n"; 9472 }); 9473 9474 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9475 visitAll(Expr, MulCollector); 9476 } 9477 9478 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9479 SmallVectorImpl<const SCEV *> &Terms, 9480 SmallVectorImpl<const SCEV *> &Sizes) { 9481 int Last = Terms.size() - 1; 9482 const SCEV *Step = Terms[Last]; 9483 9484 // End of recursion. 9485 if (Last == 0) { 9486 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9487 SmallVector<const SCEV *, 2> Qs; 9488 for (const SCEV *Op : M->operands()) 9489 if (!isa<SCEVConstant>(Op)) 9490 Qs.push_back(Op); 9491 9492 Step = SE.getMulExpr(Qs); 9493 } 9494 9495 Sizes.push_back(Step); 9496 return true; 9497 } 9498 9499 for (const SCEV *&Term : Terms) { 9500 // Normalize the terms before the next call to findArrayDimensionsRec. 9501 const SCEV *Q, *R; 9502 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9503 9504 // Bail out when GCD does not evenly divide one of the terms. 9505 if (!R->isZero()) 9506 return false; 9507 9508 Term = Q; 9509 } 9510 9511 // Remove all SCEVConstants. 9512 Terms.erase( 9513 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9514 Terms.end()); 9515 9516 if (Terms.size() > 0) 9517 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9518 return false; 9519 9520 Sizes.push_back(Step); 9521 return true; 9522 } 9523 9524 9525 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9526 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9527 for (const SCEV *T : Terms) 9528 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9529 return true; 9530 return false; 9531 } 9532 9533 // Return the number of product terms in S. 9534 static inline int numberOfTerms(const SCEV *S) { 9535 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9536 return Expr->getNumOperands(); 9537 return 1; 9538 } 9539 9540 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9541 if (isa<SCEVConstant>(T)) 9542 return nullptr; 9543 9544 if (isa<SCEVUnknown>(T)) 9545 return T; 9546 9547 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9548 SmallVector<const SCEV *, 2> Factors; 9549 for (const SCEV *Op : M->operands()) 9550 if (!isa<SCEVConstant>(Op)) 9551 Factors.push_back(Op); 9552 9553 return SE.getMulExpr(Factors); 9554 } 9555 9556 return T; 9557 } 9558 9559 /// Return the size of an element read or written by Inst. 9560 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9561 Type *Ty; 9562 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9563 Ty = Store->getValueOperand()->getType(); 9564 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9565 Ty = Load->getType(); 9566 else 9567 return nullptr; 9568 9569 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9570 return getSizeOfExpr(ETy, Ty); 9571 } 9572 9573 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9574 SmallVectorImpl<const SCEV *> &Sizes, 9575 const SCEV *ElementSize) const { 9576 if (Terms.size() < 1 || !ElementSize) 9577 return; 9578 9579 // Early return when Terms do not contain parameters: we do not delinearize 9580 // non parametric SCEVs. 9581 if (!containsParameters(Terms)) 9582 return; 9583 9584 DEBUG({ 9585 dbgs() << "Terms:\n"; 9586 for (const SCEV *T : Terms) 9587 dbgs() << *T << "\n"; 9588 }); 9589 9590 // Remove duplicates. 9591 std::sort(Terms.begin(), Terms.end()); 9592 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9593 9594 // Put larger terms first. 9595 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9596 return numberOfTerms(LHS) > numberOfTerms(RHS); 9597 }); 9598 9599 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9600 9601 // Try to divide all terms by the element size. If term is not divisible by 9602 // element size, proceed with the original term. 9603 for (const SCEV *&Term : Terms) { 9604 const SCEV *Q, *R; 9605 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9606 if (!Q->isZero()) 9607 Term = Q; 9608 } 9609 9610 SmallVector<const SCEV *, 4> NewTerms; 9611 9612 // Remove constant factors. 9613 for (const SCEV *T : Terms) 9614 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9615 NewTerms.push_back(NewT); 9616 9617 DEBUG({ 9618 dbgs() << "Terms after sorting:\n"; 9619 for (const SCEV *T : NewTerms) 9620 dbgs() << *T << "\n"; 9621 }); 9622 9623 if (NewTerms.empty() || 9624 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9625 Sizes.clear(); 9626 return; 9627 } 9628 9629 // The last element to be pushed into Sizes is the size of an element. 9630 Sizes.push_back(ElementSize); 9631 9632 DEBUG({ 9633 dbgs() << "Sizes:\n"; 9634 for (const SCEV *S : Sizes) 9635 dbgs() << *S << "\n"; 9636 }); 9637 } 9638 9639 void ScalarEvolution::computeAccessFunctions( 9640 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9641 SmallVectorImpl<const SCEV *> &Sizes) { 9642 9643 // Early exit in case this SCEV is not an affine multivariate function. 9644 if (Sizes.empty()) 9645 return; 9646 9647 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9648 if (!AR->isAffine()) 9649 return; 9650 9651 const SCEV *Res = Expr; 9652 int Last = Sizes.size() - 1; 9653 for (int i = Last; i >= 0; i--) { 9654 const SCEV *Q, *R; 9655 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9656 9657 DEBUG({ 9658 dbgs() << "Res: " << *Res << "\n"; 9659 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9660 dbgs() << "Res divided by Sizes[i]:\n"; 9661 dbgs() << "Quotient: " << *Q << "\n"; 9662 dbgs() << "Remainder: " << *R << "\n"; 9663 }); 9664 9665 Res = Q; 9666 9667 // Do not record the last subscript corresponding to the size of elements in 9668 // the array. 9669 if (i == Last) { 9670 9671 // Bail out if the remainder is too complex. 9672 if (isa<SCEVAddRecExpr>(R)) { 9673 Subscripts.clear(); 9674 Sizes.clear(); 9675 return; 9676 } 9677 9678 continue; 9679 } 9680 9681 // Record the access function for the current subscript. 9682 Subscripts.push_back(R); 9683 } 9684 9685 // Also push in last position the remainder of the last division: it will be 9686 // the access function of the innermost dimension. 9687 Subscripts.push_back(Res); 9688 9689 std::reverse(Subscripts.begin(), Subscripts.end()); 9690 9691 DEBUG({ 9692 dbgs() << "Subscripts:\n"; 9693 for (const SCEV *S : Subscripts) 9694 dbgs() << *S << "\n"; 9695 }); 9696 } 9697 9698 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9699 /// sizes of an array access. Returns the remainder of the delinearization that 9700 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9701 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9702 /// expressions in the stride and base of a SCEV corresponding to the 9703 /// computation of a GCD (greatest common divisor) of base and stride. When 9704 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9705 /// 9706 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9707 /// 9708 /// void foo(long n, long m, long o, double A[n][m][o]) { 9709 /// 9710 /// for (long i = 0; i < n; i++) 9711 /// for (long j = 0; j < m; j++) 9712 /// for (long k = 0; k < o; k++) 9713 /// A[i][j][k] = 1.0; 9714 /// } 9715 /// 9716 /// the delinearization input is the following AddRec SCEV: 9717 /// 9718 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9719 /// 9720 /// From this SCEV, we are able to say that the base offset of the access is %A 9721 /// because it appears as an offset that does not divide any of the strides in 9722 /// the loops: 9723 /// 9724 /// CHECK: Base offset: %A 9725 /// 9726 /// and then SCEV->delinearize determines the size of some of the dimensions of 9727 /// the array as these are the multiples by which the strides are happening: 9728 /// 9729 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9730 /// 9731 /// Note that the outermost dimension remains of UnknownSize because there are 9732 /// no strides that would help identifying the size of the last dimension: when 9733 /// the array has been statically allocated, one could compute the size of that 9734 /// dimension by dividing the overall size of the array by the size of the known 9735 /// dimensions: %m * %o * 8. 9736 /// 9737 /// Finally delinearize provides the access functions for the array reference 9738 /// that does correspond to A[i][j][k] of the above C testcase: 9739 /// 9740 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9741 /// 9742 /// The testcases are checking the output of a function pass: 9743 /// DelinearizationPass that walks through all loads and stores of a function 9744 /// asking for the SCEV of the memory access with respect to all enclosing 9745 /// loops, calling SCEV->delinearize on that and printing the results. 9746 9747 void ScalarEvolution::delinearize(const SCEV *Expr, 9748 SmallVectorImpl<const SCEV *> &Subscripts, 9749 SmallVectorImpl<const SCEV *> &Sizes, 9750 const SCEV *ElementSize) { 9751 // First step: collect parametric terms. 9752 SmallVector<const SCEV *, 4> Terms; 9753 collectParametricTerms(Expr, Terms); 9754 9755 if (Terms.empty()) 9756 return; 9757 9758 // Second step: find subscript sizes. 9759 findArrayDimensions(Terms, Sizes, ElementSize); 9760 9761 if (Sizes.empty()) 9762 return; 9763 9764 // Third step: compute the access functions for each subscript. 9765 computeAccessFunctions(Expr, Subscripts, Sizes); 9766 9767 if (Subscripts.empty()) 9768 return; 9769 9770 DEBUG({ 9771 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9772 dbgs() << "ArrayDecl[UnknownSize]"; 9773 for (const SCEV *S : Sizes) 9774 dbgs() << "[" << *S << "]"; 9775 9776 dbgs() << "\nArrayRef"; 9777 for (const SCEV *S : Subscripts) 9778 dbgs() << "[" << *S << "]"; 9779 dbgs() << "\n"; 9780 }); 9781 } 9782 9783 //===----------------------------------------------------------------------===// 9784 // SCEVCallbackVH Class Implementation 9785 //===----------------------------------------------------------------------===// 9786 9787 void ScalarEvolution::SCEVCallbackVH::deleted() { 9788 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9789 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9790 SE->ConstantEvolutionLoopExitValue.erase(PN); 9791 SE->eraseValueFromMap(getValPtr()); 9792 // this now dangles! 9793 } 9794 9795 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9796 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9797 9798 // Forget all the expressions associated with users of the old value, 9799 // so that future queries will recompute the expressions using the new 9800 // value. 9801 Value *Old = getValPtr(); 9802 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9803 SmallPtrSet<User *, 8> Visited; 9804 while (!Worklist.empty()) { 9805 User *U = Worklist.pop_back_val(); 9806 // Deleting the Old value will cause this to dangle. Postpone 9807 // that until everything else is done. 9808 if (U == Old) 9809 continue; 9810 if (!Visited.insert(U).second) 9811 continue; 9812 if (PHINode *PN = dyn_cast<PHINode>(U)) 9813 SE->ConstantEvolutionLoopExitValue.erase(PN); 9814 SE->eraseValueFromMap(U); 9815 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9816 } 9817 // Delete the Old value. 9818 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9819 SE->ConstantEvolutionLoopExitValue.erase(PN); 9820 SE->eraseValueFromMap(Old); 9821 // this now dangles! 9822 } 9823 9824 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9825 : CallbackVH(V), SE(se) {} 9826 9827 //===----------------------------------------------------------------------===// 9828 // ScalarEvolution Class Implementation 9829 //===----------------------------------------------------------------------===// 9830 9831 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9832 AssumptionCache &AC, DominatorTree &DT, 9833 LoopInfo &LI) 9834 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9835 CouldNotCompute(new SCEVCouldNotCompute()), 9836 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9837 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9838 FirstUnknown(nullptr) { 9839 9840 // To use guards for proving predicates, we need to scan every instruction in 9841 // relevant basic blocks, and not just terminators. Doing this is a waste of 9842 // time if the IR does not actually contain any calls to 9843 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9844 // 9845 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9846 // to _add_ guards to the module when there weren't any before, and wants 9847 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9848 // efficient in lieu of being smart in that rather obscure case. 9849 9850 auto *GuardDecl = F.getParent()->getFunction( 9851 Intrinsic::getName(Intrinsic::experimental_guard)); 9852 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9853 } 9854 9855 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9856 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9857 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9858 ValueExprMap(std::move(Arg.ValueExprMap)), 9859 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9860 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9861 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 9862 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9863 PredicatedBackedgeTakenCounts( 9864 std::move(Arg.PredicatedBackedgeTakenCounts)), 9865 ConstantEvolutionLoopExitValue( 9866 std::move(Arg.ConstantEvolutionLoopExitValue)), 9867 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9868 LoopDispositions(std::move(Arg.LoopDispositions)), 9869 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9870 BlockDispositions(std::move(Arg.BlockDispositions)), 9871 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9872 SignedRanges(std::move(Arg.SignedRanges)), 9873 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9874 UniquePreds(std::move(Arg.UniquePreds)), 9875 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9876 FirstUnknown(Arg.FirstUnknown) { 9877 Arg.FirstUnknown = nullptr; 9878 } 9879 9880 ScalarEvolution::~ScalarEvolution() { 9881 // Iterate through all the SCEVUnknown instances and call their 9882 // destructors, so that they release their references to their values. 9883 for (SCEVUnknown *U = FirstUnknown; U;) { 9884 SCEVUnknown *Tmp = U; 9885 U = U->Next; 9886 Tmp->~SCEVUnknown(); 9887 } 9888 FirstUnknown = nullptr; 9889 9890 ExprValueMap.clear(); 9891 ValueExprMap.clear(); 9892 HasRecMap.clear(); 9893 9894 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9895 // that a loop had multiple computable exits. 9896 for (auto &BTCI : BackedgeTakenCounts) 9897 BTCI.second.clear(); 9898 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9899 BTCI.second.clear(); 9900 9901 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9902 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9903 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9904 } 9905 9906 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9907 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9908 } 9909 9910 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9911 const Loop *L) { 9912 // Print all inner loops first 9913 for (Loop *I : *L) 9914 PrintLoopInfo(OS, SE, I); 9915 9916 OS << "Loop "; 9917 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9918 OS << ": "; 9919 9920 SmallVector<BasicBlock *, 8> ExitBlocks; 9921 L->getExitBlocks(ExitBlocks); 9922 if (ExitBlocks.size() != 1) 9923 OS << "<multiple exits> "; 9924 9925 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9926 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9927 } else { 9928 OS << "Unpredictable backedge-taken count. "; 9929 } 9930 9931 OS << "\n" 9932 "Loop "; 9933 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9934 OS << ": "; 9935 9936 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9937 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9938 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9939 OS << ", actual taken count either this or zero."; 9940 } else { 9941 OS << "Unpredictable max backedge-taken count. "; 9942 } 9943 9944 OS << "\n" 9945 "Loop "; 9946 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9947 OS << ": "; 9948 9949 SCEVUnionPredicate Pred; 9950 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9951 if (!isa<SCEVCouldNotCompute>(PBT)) { 9952 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9953 OS << " Predicates:\n"; 9954 Pred.print(OS, 4); 9955 } else { 9956 OS << "Unpredictable predicated backedge-taken count. "; 9957 } 9958 OS << "\n"; 9959 9960 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9961 OS << "Loop "; 9962 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9963 OS << ": "; 9964 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 9965 } 9966 } 9967 9968 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9969 switch (LD) { 9970 case ScalarEvolution::LoopVariant: 9971 return "Variant"; 9972 case ScalarEvolution::LoopInvariant: 9973 return "Invariant"; 9974 case ScalarEvolution::LoopComputable: 9975 return "Computable"; 9976 } 9977 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9978 } 9979 9980 void ScalarEvolution::print(raw_ostream &OS) const { 9981 // ScalarEvolution's implementation of the print method is to print 9982 // out SCEV values of all instructions that are interesting. Doing 9983 // this potentially causes it to create new SCEV objects though, 9984 // which technically conflicts with the const qualifier. This isn't 9985 // observable from outside the class though, so casting away the 9986 // const isn't dangerous. 9987 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9988 9989 OS << "Classifying expressions for: "; 9990 F.printAsOperand(OS, /*PrintType=*/false); 9991 OS << "\n"; 9992 for (Instruction &I : instructions(F)) 9993 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9994 OS << I << '\n'; 9995 OS << " --> "; 9996 const SCEV *SV = SE.getSCEV(&I); 9997 SV->print(OS); 9998 if (!isa<SCEVCouldNotCompute>(SV)) { 9999 OS << " U: "; 10000 SE.getUnsignedRange(SV).print(OS); 10001 OS << " S: "; 10002 SE.getSignedRange(SV).print(OS); 10003 } 10004 10005 const Loop *L = LI.getLoopFor(I.getParent()); 10006 10007 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10008 if (AtUse != SV) { 10009 OS << " --> "; 10010 AtUse->print(OS); 10011 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10012 OS << " U: "; 10013 SE.getUnsignedRange(AtUse).print(OS); 10014 OS << " S: "; 10015 SE.getSignedRange(AtUse).print(OS); 10016 } 10017 } 10018 10019 if (L) { 10020 OS << "\t\t" "Exits: "; 10021 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10022 if (!SE.isLoopInvariant(ExitValue, L)) { 10023 OS << "<<Unknown>>"; 10024 } else { 10025 OS << *ExitValue; 10026 } 10027 10028 bool First = true; 10029 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10030 if (First) { 10031 OS << "\t\t" "LoopDispositions: { "; 10032 First = false; 10033 } else { 10034 OS << ", "; 10035 } 10036 10037 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10038 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10039 } 10040 10041 for (auto *InnerL : depth_first(L)) { 10042 if (InnerL == L) 10043 continue; 10044 if (First) { 10045 OS << "\t\t" "LoopDispositions: { "; 10046 First = false; 10047 } else { 10048 OS << ", "; 10049 } 10050 10051 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10052 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10053 } 10054 10055 OS << " }"; 10056 } 10057 10058 OS << "\n"; 10059 } 10060 10061 OS << "Determining loop execution counts for: "; 10062 F.printAsOperand(OS, /*PrintType=*/false); 10063 OS << "\n"; 10064 for (Loop *I : LI) 10065 PrintLoopInfo(OS, &SE, I); 10066 } 10067 10068 ScalarEvolution::LoopDisposition 10069 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10070 auto &Values = LoopDispositions[S]; 10071 for (auto &V : Values) { 10072 if (V.getPointer() == L) 10073 return V.getInt(); 10074 } 10075 Values.emplace_back(L, LoopVariant); 10076 LoopDisposition D = computeLoopDisposition(S, L); 10077 auto &Values2 = LoopDispositions[S]; 10078 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10079 if (V.getPointer() == L) { 10080 V.setInt(D); 10081 break; 10082 } 10083 } 10084 return D; 10085 } 10086 10087 ScalarEvolution::LoopDisposition 10088 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10089 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10090 case scConstant: 10091 return LoopInvariant; 10092 case scTruncate: 10093 case scZeroExtend: 10094 case scSignExtend: 10095 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10096 case scAddRecExpr: { 10097 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10098 10099 // If L is the addrec's loop, it's computable. 10100 if (AR->getLoop() == L) 10101 return LoopComputable; 10102 10103 // Add recurrences are never invariant in the function-body (null loop). 10104 if (!L) 10105 return LoopVariant; 10106 10107 // This recurrence is variant w.r.t. L if L contains AR's loop. 10108 if (L->contains(AR->getLoop())) 10109 return LoopVariant; 10110 10111 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10112 if (AR->getLoop()->contains(L)) 10113 return LoopInvariant; 10114 10115 // This recurrence is variant w.r.t. L if any of its operands 10116 // are variant. 10117 for (auto *Op : AR->operands()) 10118 if (!isLoopInvariant(Op, L)) 10119 return LoopVariant; 10120 10121 // Otherwise it's loop-invariant. 10122 return LoopInvariant; 10123 } 10124 case scAddExpr: 10125 case scMulExpr: 10126 case scUMaxExpr: 10127 case scSMaxExpr: { 10128 bool HasVarying = false; 10129 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10130 LoopDisposition D = getLoopDisposition(Op, L); 10131 if (D == LoopVariant) 10132 return LoopVariant; 10133 if (D == LoopComputable) 10134 HasVarying = true; 10135 } 10136 return HasVarying ? LoopComputable : LoopInvariant; 10137 } 10138 case scUDivExpr: { 10139 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10140 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10141 if (LD == LoopVariant) 10142 return LoopVariant; 10143 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10144 if (RD == LoopVariant) 10145 return LoopVariant; 10146 return (LD == LoopInvariant && RD == LoopInvariant) ? 10147 LoopInvariant : LoopComputable; 10148 } 10149 case scUnknown: 10150 // All non-instruction values are loop invariant. All instructions are loop 10151 // invariant if they are not contained in the specified loop. 10152 // Instructions are never considered invariant in the function body 10153 // (null loop) because they are defined within the "loop". 10154 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10155 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10156 return LoopInvariant; 10157 case scCouldNotCompute: 10158 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10159 } 10160 llvm_unreachable("Unknown SCEV kind!"); 10161 } 10162 10163 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10164 return getLoopDisposition(S, L) == LoopInvariant; 10165 } 10166 10167 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10168 return getLoopDisposition(S, L) == LoopComputable; 10169 } 10170 10171 ScalarEvolution::BlockDisposition 10172 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10173 auto &Values = BlockDispositions[S]; 10174 for (auto &V : Values) { 10175 if (V.getPointer() == BB) 10176 return V.getInt(); 10177 } 10178 Values.emplace_back(BB, DoesNotDominateBlock); 10179 BlockDisposition D = computeBlockDisposition(S, BB); 10180 auto &Values2 = BlockDispositions[S]; 10181 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10182 if (V.getPointer() == BB) { 10183 V.setInt(D); 10184 break; 10185 } 10186 } 10187 return D; 10188 } 10189 10190 ScalarEvolution::BlockDisposition 10191 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10192 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10193 case scConstant: 10194 return ProperlyDominatesBlock; 10195 case scTruncate: 10196 case scZeroExtend: 10197 case scSignExtend: 10198 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10199 case scAddRecExpr: { 10200 // This uses a "dominates" query instead of "properly dominates" query 10201 // to test for proper dominance too, because the instruction which 10202 // produces the addrec's value is a PHI, and a PHI effectively properly 10203 // dominates its entire containing block. 10204 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10205 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10206 return DoesNotDominateBlock; 10207 10208 // Fall through into SCEVNAryExpr handling. 10209 LLVM_FALLTHROUGH; 10210 } 10211 case scAddExpr: 10212 case scMulExpr: 10213 case scUMaxExpr: 10214 case scSMaxExpr: { 10215 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10216 bool Proper = true; 10217 for (const SCEV *NAryOp : NAry->operands()) { 10218 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10219 if (D == DoesNotDominateBlock) 10220 return DoesNotDominateBlock; 10221 if (D == DominatesBlock) 10222 Proper = false; 10223 } 10224 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10225 } 10226 case scUDivExpr: { 10227 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10228 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10229 BlockDisposition LD = getBlockDisposition(LHS, BB); 10230 if (LD == DoesNotDominateBlock) 10231 return DoesNotDominateBlock; 10232 BlockDisposition RD = getBlockDisposition(RHS, BB); 10233 if (RD == DoesNotDominateBlock) 10234 return DoesNotDominateBlock; 10235 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10236 ProperlyDominatesBlock : DominatesBlock; 10237 } 10238 case scUnknown: 10239 if (Instruction *I = 10240 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10241 if (I->getParent() == BB) 10242 return DominatesBlock; 10243 if (DT.properlyDominates(I->getParent(), BB)) 10244 return ProperlyDominatesBlock; 10245 return DoesNotDominateBlock; 10246 } 10247 return ProperlyDominatesBlock; 10248 case scCouldNotCompute: 10249 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10250 } 10251 llvm_unreachable("Unknown SCEV kind!"); 10252 } 10253 10254 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10255 return getBlockDisposition(S, BB) >= DominatesBlock; 10256 } 10257 10258 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10259 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10260 } 10261 10262 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10263 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10264 } 10265 10266 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10267 ValuesAtScopes.erase(S); 10268 LoopDispositions.erase(S); 10269 BlockDispositions.erase(S); 10270 UnsignedRanges.erase(S); 10271 SignedRanges.erase(S); 10272 ExprValueMap.erase(S); 10273 HasRecMap.erase(S); 10274 MinTrailingZerosCache.erase(S); 10275 10276 auto RemoveSCEVFromBackedgeMap = 10277 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10278 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10279 BackedgeTakenInfo &BEInfo = I->second; 10280 if (BEInfo.hasOperand(S, this)) { 10281 BEInfo.clear(); 10282 Map.erase(I++); 10283 } else 10284 ++I; 10285 } 10286 }; 10287 10288 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10289 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10290 } 10291 10292 void ScalarEvolution::verify() const { 10293 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10294 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10295 10296 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 10297 10298 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 10299 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 10300 const SCEV *visitConstant(const SCEVConstant *Constant) { 10301 return SE.getConstant(Constant->getAPInt()); 10302 } 10303 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10304 return SE.getUnknown(Expr->getValue()); 10305 } 10306 10307 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 10308 return SE.getCouldNotCompute(); 10309 } 10310 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 10311 }; 10312 10313 SCEVMapper SCM(SE2); 10314 10315 while (!LoopStack.empty()) { 10316 auto *L = LoopStack.pop_back_val(); 10317 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 10318 10319 auto *CurBECount = SCM.visit( 10320 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 10321 auto *NewBECount = SE2.getBackedgeTakenCount(L); 10322 10323 if (CurBECount == SE2.getCouldNotCompute() || 10324 NewBECount == SE2.getCouldNotCompute()) { 10325 // NB! This situation is legal, but is very suspicious -- whatever pass 10326 // change the loop to make a trip count go from could not compute to 10327 // computable or vice-versa *should have* invalidated SCEV. However, we 10328 // choose not to assert here (for now) since we don't want false 10329 // positives. 10330 continue; 10331 } 10332 10333 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 10334 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 10335 // not propagate undef aggressively). This means we can (and do) fail 10336 // verification in cases where a transform makes the trip count of a loop 10337 // go from "undef" to "undef+1" (say). The transform is fine, since in 10338 // both cases the loop iterates "undef" times, but SCEV thinks we 10339 // increased the trip count of the loop by 1 incorrectly. 10340 continue; 10341 } 10342 10343 if (SE.getTypeSizeInBits(CurBECount->getType()) > 10344 SE.getTypeSizeInBits(NewBECount->getType())) 10345 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 10346 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 10347 SE.getTypeSizeInBits(NewBECount->getType())) 10348 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 10349 10350 auto *ConstantDelta = 10351 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 10352 10353 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 10354 dbgs() << "Trip Count Changed!\n"; 10355 dbgs() << "Old: " << *CurBECount << "\n"; 10356 dbgs() << "New: " << *NewBECount << "\n"; 10357 dbgs() << "Delta: " << *ConstantDelta << "\n"; 10358 std::abort(); 10359 } 10360 } 10361 } 10362 10363 bool ScalarEvolution::invalidate( 10364 Function &F, const PreservedAnalyses &PA, 10365 FunctionAnalysisManager::Invalidator &Inv) { 10366 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10367 // of its dependencies is invalidated. 10368 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10369 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10370 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10371 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10372 Inv.invalidate<LoopAnalysis>(F, PA); 10373 } 10374 10375 AnalysisKey ScalarEvolutionAnalysis::Key; 10376 10377 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10378 FunctionAnalysisManager &AM) { 10379 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10380 AM.getResult<AssumptionAnalysis>(F), 10381 AM.getResult<DominatorTreeAnalysis>(F), 10382 AM.getResult<LoopAnalysis>(F)); 10383 } 10384 10385 PreservedAnalyses 10386 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10387 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10388 return PreservedAnalyses::all(); 10389 } 10390 10391 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10392 "Scalar Evolution Analysis", false, true) 10393 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10394 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10395 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10396 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10397 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10398 "Scalar Evolution Analysis", false, true) 10399 char ScalarEvolutionWrapperPass::ID = 0; 10400 10401 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10402 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10403 } 10404 10405 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10406 SE.reset(new ScalarEvolution( 10407 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10408 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10409 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10410 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10411 return false; 10412 } 10413 10414 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10415 10416 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10417 SE->print(OS); 10418 } 10419 10420 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10421 if (!VerifySCEV) 10422 return; 10423 10424 SE->verify(); 10425 } 10426 10427 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10428 AU.setPreservesAll(); 10429 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10430 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10431 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10432 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10433 } 10434 10435 const SCEVPredicate * 10436 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10437 const SCEVConstant *RHS) { 10438 FoldingSetNodeID ID; 10439 // Unique this node based on the arguments 10440 ID.AddInteger(SCEVPredicate::P_Equal); 10441 ID.AddPointer(LHS); 10442 ID.AddPointer(RHS); 10443 void *IP = nullptr; 10444 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10445 return S; 10446 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10447 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10448 UniquePreds.InsertNode(Eq, IP); 10449 return Eq; 10450 } 10451 10452 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10453 const SCEVAddRecExpr *AR, 10454 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10455 FoldingSetNodeID ID; 10456 // Unique this node based on the arguments 10457 ID.AddInteger(SCEVPredicate::P_Wrap); 10458 ID.AddPointer(AR); 10459 ID.AddInteger(AddedFlags); 10460 void *IP = nullptr; 10461 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10462 return S; 10463 auto *OF = new (SCEVAllocator) 10464 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10465 UniquePreds.InsertNode(OF, IP); 10466 return OF; 10467 } 10468 10469 namespace { 10470 10471 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10472 public: 10473 /// Rewrites \p S in the context of a loop L and the SCEV predication 10474 /// infrastructure. 10475 /// 10476 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10477 /// equivalences present in \p Pred. 10478 /// 10479 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10480 /// \p NewPreds such that the result will be an AddRecExpr. 10481 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10482 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10483 SCEVUnionPredicate *Pred) { 10484 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10485 return Rewriter.visit(S); 10486 } 10487 10488 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10489 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10490 SCEVUnionPredicate *Pred) 10491 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10492 10493 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10494 if (Pred) { 10495 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10496 for (auto *Pred : ExprPreds) 10497 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10498 if (IPred->getLHS() == Expr) 10499 return IPred->getRHS(); 10500 } 10501 10502 return Expr; 10503 } 10504 10505 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10506 const SCEV *Operand = visit(Expr->getOperand()); 10507 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10508 if (AR && AR->getLoop() == L && AR->isAffine()) { 10509 // This couldn't be folded because the operand didn't have the nuw 10510 // flag. Add the nusw flag as an assumption that we could make. 10511 const SCEV *Step = AR->getStepRecurrence(SE); 10512 Type *Ty = Expr->getType(); 10513 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10514 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10515 SE.getSignExtendExpr(Step, Ty), L, 10516 AR->getNoWrapFlags()); 10517 } 10518 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10519 } 10520 10521 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10522 const SCEV *Operand = visit(Expr->getOperand()); 10523 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10524 if (AR && AR->getLoop() == L && AR->isAffine()) { 10525 // This couldn't be folded because the operand didn't have the nsw 10526 // flag. Add the nssw flag as an assumption that we could make. 10527 const SCEV *Step = AR->getStepRecurrence(SE); 10528 Type *Ty = Expr->getType(); 10529 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10530 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10531 SE.getSignExtendExpr(Step, Ty), L, 10532 AR->getNoWrapFlags()); 10533 } 10534 return SE.getSignExtendExpr(Operand, Expr->getType()); 10535 } 10536 10537 private: 10538 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10539 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10540 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10541 if (!NewPreds) { 10542 // Check if we've already made this assumption. 10543 return Pred && Pred->implies(A); 10544 } 10545 NewPreds->insert(A); 10546 return true; 10547 } 10548 10549 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10550 SCEVUnionPredicate *Pred; 10551 const Loop *L; 10552 }; 10553 } // end anonymous namespace 10554 10555 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10556 SCEVUnionPredicate &Preds) { 10557 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10558 } 10559 10560 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10561 const SCEV *S, const Loop *L, 10562 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10563 10564 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10565 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10566 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10567 10568 if (!AddRec) 10569 return nullptr; 10570 10571 // Since the transformation was successful, we can now transfer the SCEV 10572 // predicates. 10573 for (auto *P : TransformPreds) 10574 Preds.insert(P); 10575 10576 return AddRec; 10577 } 10578 10579 /// SCEV predicates 10580 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10581 SCEVPredicateKind Kind) 10582 : FastID(ID), Kind(Kind) {} 10583 10584 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10585 const SCEVUnknown *LHS, 10586 const SCEVConstant *RHS) 10587 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10588 10589 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10590 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10591 10592 if (!Op) 10593 return false; 10594 10595 return Op->LHS == LHS && Op->RHS == RHS; 10596 } 10597 10598 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10599 10600 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10601 10602 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10603 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10604 } 10605 10606 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10607 const SCEVAddRecExpr *AR, 10608 IncrementWrapFlags Flags) 10609 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10610 10611 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10612 10613 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10614 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10615 10616 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10617 } 10618 10619 bool SCEVWrapPredicate::isAlwaysTrue() const { 10620 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10621 IncrementWrapFlags IFlags = Flags; 10622 10623 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10624 IFlags = clearFlags(IFlags, IncrementNSSW); 10625 10626 return IFlags == IncrementAnyWrap; 10627 } 10628 10629 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10630 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10631 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10632 OS << "<nusw>"; 10633 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10634 OS << "<nssw>"; 10635 OS << "\n"; 10636 } 10637 10638 SCEVWrapPredicate::IncrementWrapFlags 10639 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10640 ScalarEvolution &SE) { 10641 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10642 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10643 10644 // We can safely transfer the NSW flag as NSSW. 10645 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10646 ImpliedFlags = IncrementNSSW; 10647 10648 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10649 // If the increment is positive, the SCEV NUW flag will also imply the 10650 // WrapPredicate NUSW flag. 10651 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10652 if (Step->getValue()->getValue().isNonNegative()) 10653 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10654 } 10655 10656 return ImpliedFlags; 10657 } 10658 10659 /// Union predicates don't get cached so create a dummy set ID for it. 10660 SCEVUnionPredicate::SCEVUnionPredicate() 10661 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10662 10663 bool SCEVUnionPredicate::isAlwaysTrue() const { 10664 return all_of(Preds, 10665 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10666 } 10667 10668 ArrayRef<const SCEVPredicate *> 10669 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10670 auto I = SCEVToPreds.find(Expr); 10671 if (I == SCEVToPreds.end()) 10672 return ArrayRef<const SCEVPredicate *>(); 10673 return I->second; 10674 } 10675 10676 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10677 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10678 return all_of(Set->Preds, 10679 [this](const SCEVPredicate *I) { return this->implies(I); }); 10680 10681 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10682 if (ScevPredsIt == SCEVToPreds.end()) 10683 return false; 10684 auto &SCEVPreds = ScevPredsIt->second; 10685 10686 return any_of(SCEVPreds, 10687 [N](const SCEVPredicate *I) { return I->implies(N); }); 10688 } 10689 10690 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10691 10692 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10693 for (auto Pred : Preds) 10694 Pred->print(OS, Depth); 10695 } 10696 10697 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10698 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10699 for (auto Pred : Set->Preds) 10700 add(Pred); 10701 return; 10702 } 10703 10704 if (implies(N)) 10705 return; 10706 10707 const SCEV *Key = N->getExpr(); 10708 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10709 " associated expression!"); 10710 10711 SCEVToPreds[Key].push_back(N); 10712 Preds.push_back(N); 10713 } 10714 10715 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10716 Loop &L) 10717 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10718 10719 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10720 const SCEV *Expr = SE.getSCEV(V); 10721 RewriteEntry &Entry = RewriteMap[Expr]; 10722 10723 // If we already have an entry and the version matches, return it. 10724 if (Entry.second && Generation == Entry.first) 10725 return Entry.second; 10726 10727 // We found an entry but it's stale. Rewrite the stale entry 10728 // according to the current predicate. 10729 if (Entry.second) 10730 Expr = Entry.second; 10731 10732 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10733 Entry = {Generation, NewSCEV}; 10734 10735 return NewSCEV; 10736 } 10737 10738 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10739 if (!BackedgeCount) { 10740 SCEVUnionPredicate BackedgePred; 10741 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10742 addPredicate(BackedgePred); 10743 } 10744 return BackedgeCount; 10745 } 10746 10747 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10748 if (Preds.implies(&Pred)) 10749 return; 10750 Preds.add(&Pred); 10751 updateGeneration(); 10752 } 10753 10754 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10755 return Preds; 10756 } 10757 10758 void PredicatedScalarEvolution::updateGeneration() { 10759 // If the generation number wrapped recompute everything. 10760 if (++Generation == 0) { 10761 for (auto &II : RewriteMap) { 10762 const SCEV *Rewritten = II.second.second; 10763 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10764 } 10765 } 10766 } 10767 10768 void PredicatedScalarEvolution::setNoOverflow( 10769 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10770 const SCEV *Expr = getSCEV(V); 10771 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10772 10773 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10774 10775 // Clear the statically implied flags. 10776 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10777 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10778 10779 auto II = FlagsMap.insert({V, Flags}); 10780 if (!II.second) 10781 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10782 } 10783 10784 bool PredicatedScalarEvolution::hasNoOverflow( 10785 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10786 const SCEV *Expr = getSCEV(V); 10787 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10788 10789 Flags = SCEVWrapPredicate::clearFlags( 10790 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10791 10792 auto II = FlagsMap.find(V); 10793 10794 if (II != FlagsMap.end()) 10795 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10796 10797 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10798 } 10799 10800 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10801 const SCEV *Expr = this->getSCEV(V); 10802 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10803 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10804 10805 if (!New) 10806 return nullptr; 10807 10808 for (auto *P : NewPreds) 10809 Preds.add(P); 10810 10811 updateGeneration(); 10812 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10813 return New; 10814 } 10815 10816 PredicatedScalarEvolution::PredicatedScalarEvolution( 10817 const PredicatedScalarEvolution &Init) 10818 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10819 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10820 for (const auto &I : Init.FlagsMap) 10821 FlagsMap.insert(I); 10822 } 10823 10824 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10825 // For each block. 10826 for (auto *BB : L.getBlocks()) 10827 for (auto &I : *BB) { 10828 if (!SE.isSCEVable(I.getType())) 10829 continue; 10830 10831 auto *Expr = SE.getSCEV(&I); 10832 auto II = RewriteMap.find(Expr); 10833 10834 if (II == RewriteMap.end()) 10835 continue; 10836 10837 // Don't print things that are not interesting. 10838 if (II->second.second == Expr) 10839 continue; 10840 10841 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10842 OS.indent(Depth + 2) << *Expr << "\n"; 10843 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10844 } 10845 } 10846