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/APInt.h" 63 #include "llvm/ADT/ArrayRef.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/DepthFirstIterator.h" 66 #include "llvm/ADT/EquivalenceClasses.h" 67 #include "llvm/ADT/FoldingSet.h" 68 #include "llvm/ADT/None.h" 69 #include "llvm/ADT/Optional.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/ADT/ScopeExit.h" 72 #include "llvm/ADT/Sequence.h" 73 #include "llvm/ADT/SetVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallSet.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/Statistic.h" 78 #include "llvm/ADT/StringRef.h" 79 #include "llvm/Analysis/AssumptionCache.h" 80 #include "llvm/Analysis/ConstantFolding.h" 81 #include "llvm/Analysis/InstructionSimplify.h" 82 #include "llvm/Analysis/LoopInfo.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/CallSite.h" 91 #include "llvm/IR/Constant.h" 92 #include "llvm/IR/ConstantRange.h" 93 #include "llvm/IR/Constants.h" 94 #include "llvm/IR/DataLayout.h" 95 #include "llvm/IR/DerivedTypes.h" 96 #include "llvm/IR/Dominators.h" 97 #include "llvm/IR/Function.h" 98 #include "llvm/IR/GlobalAlias.h" 99 #include "llvm/IR/GlobalValue.h" 100 #include "llvm/IR/GlobalVariable.h" 101 #include "llvm/IR/InstIterator.h" 102 #include "llvm/IR/InstrTypes.h" 103 #include "llvm/IR/Instruction.h" 104 #include "llvm/IR/Instructions.h" 105 #include "llvm/IR/IntrinsicInst.h" 106 #include "llvm/IR/Intrinsics.h" 107 #include "llvm/IR/LLVMContext.h" 108 #include "llvm/IR/Metadata.h" 109 #include "llvm/IR/Operator.h" 110 #include "llvm/IR/PatternMatch.h" 111 #include "llvm/IR/Type.h" 112 #include "llvm/IR/Use.h" 113 #include "llvm/IR/User.h" 114 #include "llvm/IR/Value.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<unsigned> MulOpsInlineThreshold( 166 "scev-mulops-inline-threshold", cl::Hidden, 167 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 168 cl::init(32)); 169 170 static cl::opt<unsigned> AddOpsInlineThreshold( 171 "scev-addops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining addition operands into a SCEV"), 173 cl::init(500)); 174 175 static cl::opt<unsigned> MaxSCEVCompareDepth( 176 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 177 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 181 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 183 cl::init(2)); 184 185 static cl::opt<unsigned> MaxValueCompareDepth( 186 "scalar-evolution-max-value-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive value complexity comparisons"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> 191 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive arithmetics"), 193 cl::init(32)); 194 195 static cl::opt<unsigned> MaxConstantEvolvingDepth( 196 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 198 199 static cl::opt<unsigned> 200 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive SExt/ZExt"), 202 cl::init(8)); 203 204 static cl::opt<unsigned> 205 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 206 cl::desc("Max coefficients in AddRec during evolving"), 207 cl::init(16)); 208 209 //===----------------------------------------------------------------------===// 210 // SCEV class definitions 211 //===----------------------------------------------------------------------===// 212 213 //===----------------------------------------------------------------------===// 214 // Implementation of the SCEV class. 215 // 216 217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 218 LLVM_DUMP_METHOD void SCEV::dump() const { 219 print(dbgs()); 220 dbgs() << '\n'; 221 } 222 #endif 223 224 void SCEV::print(raw_ostream &OS) const { 225 switch (static_cast<SCEVTypes>(getSCEVType())) { 226 case scConstant: 227 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 228 return; 229 case scTruncate: { 230 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 231 const SCEV *Op = Trunc->getOperand(); 232 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 233 << *Trunc->getType() << ")"; 234 return; 235 } 236 case scZeroExtend: { 237 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 238 const SCEV *Op = ZExt->getOperand(); 239 OS << "(zext " << *Op->getType() << " " << *Op << " to " 240 << *ZExt->getType() << ")"; 241 return; 242 } 243 case scSignExtend: { 244 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 245 const SCEV *Op = SExt->getOperand(); 246 OS << "(sext " << *Op->getType() << " " << *Op << " to " 247 << *SExt->getType() << ")"; 248 return; 249 } 250 case scAddRecExpr: { 251 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 252 OS << "{" << *AR->getOperand(0); 253 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 254 OS << ",+," << *AR->getOperand(i); 255 OS << "}<"; 256 if (AR->hasNoUnsignedWrap()) 257 OS << "nuw><"; 258 if (AR->hasNoSignedWrap()) 259 OS << "nsw><"; 260 if (AR->hasNoSelfWrap() && 261 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 262 OS << "nw><"; 263 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 264 OS << ">"; 265 return; 266 } 267 case scAddExpr: 268 case scMulExpr: 269 case scUMaxExpr: 270 case scSMaxExpr: { 271 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 272 const char *OpStr = nullptr; 273 switch (NAry->getSCEVType()) { 274 case scAddExpr: OpStr = " + "; break; 275 case scMulExpr: OpStr = " * "; break; 276 case scUMaxExpr: OpStr = " umax "; break; 277 case scSMaxExpr: OpStr = " smax "; break; 278 } 279 OS << "("; 280 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 281 I != E; ++I) { 282 OS << **I; 283 if (std::next(I) != E) 284 OS << OpStr; 285 } 286 OS << ")"; 287 switch (NAry->getSCEVType()) { 288 case scAddExpr: 289 case scMulExpr: 290 if (NAry->hasNoUnsignedWrap()) 291 OS << "<nuw>"; 292 if (NAry->hasNoSignedWrap()) 293 OS << "<nsw>"; 294 } 295 return; 296 } 297 case scUDivExpr: { 298 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 299 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 300 return; 301 } 302 case scUnknown: { 303 const SCEVUnknown *U = cast<SCEVUnknown>(this); 304 Type *AllocTy; 305 if (U->isSizeOf(AllocTy)) { 306 OS << "sizeof(" << *AllocTy << ")"; 307 return; 308 } 309 if (U->isAlignOf(AllocTy)) { 310 OS << "alignof(" << *AllocTy << ")"; 311 return; 312 } 313 314 Type *CTy; 315 Constant *FieldNo; 316 if (U->isOffsetOf(CTy, FieldNo)) { 317 OS << "offsetof(" << *CTy << ", "; 318 FieldNo->printAsOperand(OS, false); 319 OS << ")"; 320 return; 321 } 322 323 // Otherwise just print it normally. 324 U->getValue()->printAsOperand(OS, false); 325 return; 326 } 327 case scCouldNotCompute: 328 OS << "***COULDNOTCOMPUTE***"; 329 return; 330 } 331 llvm_unreachable("Unknown SCEV kind!"); 332 } 333 334 Type *SCEV::getType() const { 335 switch (static_cast<SCEVTypes>(getSCEVType())) { 336 case scConstant: 337 return cast<SCEVConstant>(this)->getType(); 338 case scTruncate: 339 case scZeroExtend: 340 case scSignExtend: 341 return cast<SCEVCastExpr>(this)->getType(); 342 case scAddRecExpr: 343 case scMulExpr: 344 case scUMaxExpr: 345 case scSMaxExpr: 346 return cast<SCEVNAryExpr>(this)->getType(); 347 case scAddExpr: 348 return cast<SCEVAddExpr>(this)->getType(); 349 case scUDivExpr: 350 return cast<SCEVUDivExpr>(this)->getType(); 351 case scUnknown: 352 return cast<SCEVUnknown>(this)->getType(); 353 case scCouldNotCompute: 354 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 355 } 356 llvm_unreachable("Unknown SCEV kind!"); 357 } 358 359 bool SCEV::isZero() const { 360 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 361 return SC->getValue()->isZero(); 362 return false; 363 } 364 365 bool SCEV::isOne() const { 366 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 367 return SC->getValue()->isOne(); 368 return false; 369 } 370 371 bool SCEV::isAllOnesValue() const { 372 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 373 return SC->getValue()->isMinusOne(); 374 return false; 375 } 376 377 bool SCEV::isNonConstantNegative() const { 378 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 379 if (!Mul) return false; 380 381 // If there is a constant factor, it will be first. 382 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 383 if (!SC) return false; 384 385 // Return true if the value is negative, this matches things like (-42 * V). 386 return SC->getAPInt().isNegative(); 387 } 388 389 SCEVCouldNotCompute::SCEVCouldNotCompute() : 390 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 391 392 bool SCEVCouldNotCompute::classof(const SCEV *S) { 393 return S->getSCEVType() == scCouldNotCompute; 394 } 395 396 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 397 FoldingSetNodeID ID; 398 ID.AddInteger(scConstant); 399 ID.AddPointer(V); 400 void *IP = nullptr; 401 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 402 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 403 UniqueSCEVs.InsertNode(S, IP); 404 return S; 405 } 406 407 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 408 return getConstant(ConstantInt::get(getContext(), Val)); 409 } 410 411 const SCEV * 412 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 413 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 414 return getConstant(ConstantInt::get(ITy, V, isSigned)); 415 } 416 417 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 418 unsigned SCEVTy, const SCEV *op, Type *ty) 419 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 420 421 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 422 const SCEV *op, Type *ty) 423 : SCEVCastExpr(ID, scTruncate, op, ty) { 424 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 425 "Cannot truncate non-integer value!"); 426 } 427 428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 429 const SCEV *op, Type *ty) 430 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 431 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 432 "Cannot zero extend non-integer value!"); 433 } 434 435 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 436 const SCEV *op, Type *ty) 437 : SCEVCastExpr(ID, scSignExtend, op, ty) { 438 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 439 "Cannot sign extend non-integer value!"); 440 } 441 442 void SCEVUnknown::deleted() { 443 // Clear this SCEVUnknown from various maps. 444 SE->forgetMemoizedResults(this); 445 446 // Remove this SCEVUnknown from the uniquing map. 447 SE->UniqueSCEVs.RemoveNode(this); 448 449 // Release the value. 450 setValPtr(nullptr); 451 } 452 453 void SCEVUnknown::allUsesReplacedWith(Value *New) { 454 // Remove this SCEVUnknown from the uniquing map. 455 SE->UniqueSCEVs.RemoveNode(this); 456 457 // Update this SCEVUnknown to point to the new value. This is needed 458 // because there may still be outstanding SCEVs which still point to 459 // this SCEVUnknown. 460 setValPtr(New); 461 } 462 463 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 464 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 465 if (VCE->getOpcode() == Instruction::PtrToInt) 466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 467 if (CE->getOpcode() == Instruction::GetElementPtr && 468 CE->getOperand(0)->isNullValue() && 469 CE->getNumOperands() == 2) 470 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 471 if (CI->isOne()) { 472 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 473 ->getElementType(); 474 return true; 475 } 476 477 return false; 478 } 479 480 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 481 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 482 if (VCE->getOpcode() == Instruction::PtrToInt) 483 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 484 if (CE->getOpcode() == Instruction::GetElementPtr && 485 CE->getOperand(0)->isNullValue()) { 486 Type *Ty = 487 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 488 if (StructType *STy = dyn_cast<StructType>(Ty)) 489 if (!STy->isPacked() && 490 CE->getNumOperands() == 3 && 491 CE->getOperand(1)->isNullValue()) { 492 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 493 if (CI->isOne() && 494 STy->getNumElements() == 2 && 495 STy->getElementType(0)->isIntegerTy(1)) { 496 AllocTy = STy->getElementType(1); 497 return true; 498 } 499 } 500 } 501 502 return false; 503 } 504 505 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 506 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 507 if (VCE->getOpcode() == Instruction::PtrToInt) 508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 509 if (CE->getOpcode() == Instruction::GetElementPtr && 510 CE->getNumOperands() == 3 && 511 CE->getOperand(0)->isNullValue() && 512 CE->getOperand(1)->isNullValue()) { 513 Type *Ty = 514 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 515 // Ignore vector types here so that ScalarEvolutionExpander doesn't 516 // emit getelementptrs that index into vectors. 517 if (Ty->isStructTy() || Ty->isArrayTy()) { 518 CTy = Ty; 519 FieldNo = CE->getOperand(2); 520 return true; 521 } 522 } 523 524 return false; 525 } 526 527 //===----------------------------------------------------------------------===// 528 // SCEV Utilities 529 //===----------------------------------------------------------------------===// 530 531 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 532 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 533 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 534 /// have been previously deemed to be "equally complex" by this routine. It is 535 /// intended to avoid exponential time complexity in cases like: 536 /// 537 /// %a = f(%x, %y) 538 /// %b = f(%a, %a) 539 /// %c = f(%b, %b) 540 /// 541 /// %d = f(%x, %y) 542 /// %e = f(%d, %d) 543 /// %f = f(%e, %e) 544 /// 545 /// CompareValueComplexity(%f, %c) 546 /// 547 /// Since we do not continue running this routine on expression trees once we 548 /// have seen unequal values, there is no need to track them in the cache. 549 static int 550 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 551 const LoopInfo *const LI, Value *LV, Value *RV, 552 unsigned Depth) { 553 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 554 return 0; 555 556 // Order pointer values after integer values. This helps SCEVExpander form 557 // GEPs. 558 bool LIsPointer = LV->getType()->isPointerTy(), 559 RIsPointer = RV->getType()->isPointerTy(); 560 if (LIsPointer != RIsPointer) 561 return (int)LIsPointer - (int)RIsPointer; 562 563 // Compare getValueID values. 564 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 565 if (LID != RID) 566 return (int)LID - (int)RID; 567 568 // Sort arguments by their position. 569 if (const auto *LA = dyn_cast<Argument>(LV)) { 570 const auto *RA = cast<Argument>(RV); 571 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 572 return (int)LArgNo - (int)RArgNo; 573 } 574 575 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 576 const auto *RGV = cast<GlobalValue>(RV); 577 578 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 579 auto LT = GV->getLinkage(); 580 return !(GlobalValue::isPrivateLinkage(LT) || 581 GlobalValue::isInternalLinkage(LT)); 582 }; 583 584 // Use the names to distinguish the two values, but only if the 585 // names are semantically important. 586 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 587 return LGV->getName().compare(RGV->getName()); 588 } 589 590 // For instructions, compare their loop depth, and their operand count. This 591 // is pretty loose. 592 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 593 const auto *RInst = cast<Instruction>(RV); 594 595 // Compare loop depths. 596 const BasicBlock *LParent = LInst->getParent(), 597 *RParent = RInst->getParent(); 598 if (LParent != RParent) { 599 unsigned LDepth = LI->getLoopDepth(LParent), 600 RDepth = LI->getLoopDepth(RParent); 601 if (LDepth != RDepth) 602 return (int)LDepth - (int)RDepth; 603 } 604 605 // Compare the number of operands. 606 unsigned LNumOps = LInst->getNumOperands(), 607 RNumOps = RInst->getNumOperands(); 608 if (LNumOps != RNumOps) 609 return (int)LNumOps - (int)RNumOps; 610 611 for (unsigned Idx : seq(0u, LNumOps)) { 612 int Result = 613 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 614 RInst->getOperand(Idx), Depth + 1); 615 if (Result != 0) 616 return Result; 617 } 618 } 619 620 EqCacheValue.unionSets(LV, RV); 621 return 0; 622 } 623 624 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 625 // than RHS, respectively. A three-way result allows recursive comparisons to be 626 // more efficient. 627 static int CompareSCEVComplexity( 628 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 629 EquivalenceClasses<const Value *> &EqCacheValue, 630 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 631 DominatorTree &DT, unsigned Depth = 0) { 632 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 633 if (LHS == RHS) 634 return 0; 635 636 // Primarily, sort the SCEVs by their getSCEVType(). 637 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 638 if (LType != RType) 639 return (int)LType - (int)RType; 640 641 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 642 return 0; 643 // Aside from the getSCEVType() ordering, the particular ordering 644 // isn't very important except that it's beneficial to be consistent, 645 // so that (a + b) and (b + a) don't end up as different expressions. 646 switch (static_cast<SCEVTypes>(LType)) { 647 case scUnknown: { 648 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 649 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 650 651 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 652 RU->getValue(), Depth + 1); 653 if (X == 0) 654 EqCacheSCEV.unionSets(LHS, RHS); 655 return X; 656 } 657 658 case scConstant: { 659 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 660 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 661 662 // Compare constant values. 663 const APInt &LA = LC->getAPInt(); 664 const APInt &RA = RC->getAPInt(); 665 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 666 if (LBitWidth != RBitWidth) 667 return (int)LBitWidth - (int)RBitWidth; 668 return LA.ult(RA) ? -1 : 1; 669 } 670 671 case scAddRecExpr: { 672 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 673 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 674 675 // There is always a dominance between two recs that are used by one SCEV, 676 // so we can safely sort recs by loop header dominance. We require such 677 // order in getAddExpr. 678 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 679 if (LLoop != RLoop) { 680 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 681 assert(LHead != RHead && "Two loops share the same header?"); 682 if (DT.dominates(LHead, RHead)) 683 return 1; 684 else 685 assert(DT.dominates(RHead, LHead) && 686 "No dominance between recurrences used by one SCEV?"); 687 return -1; 688 } 689 690 // Addrec complexity grows with operand count. 691 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 692 if (LNumOps != RNumOps) 693 return (int)LNumOps - (int)RNumOps; 694 695 // Compare NoWrap flags. 696 if (LA->getNoWrapFlags() != RA->getNoWrapFlags()) 697 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags(); 698 699 // Lexicographically compare. 700 for (unsigned i = 0; i != LNumOps; ++i) { 701 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 702 LA->getOperand(i), RA->getOperand(i), DT, 703 Depth + 1); 704 if (X != 0) 705 return X; 706 } 707 EqCacheSCEV.unionSets(LHS, RHS); 708 return 0; 709 } 710 711 case scAddExpr: 712 case scMulExpr: 713 case scSMaxExpr: 714 case scUMaxExpr: { 715 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 716 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 717 718 // Lexicographically compare n-ary expressions. 719 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 720 if (LNumOps != RNumOps) 721 return (int)LNumOps - (int)RNumOps; 722 723 // Compare NoWrap flags. 724 if (LC->getNoWrapFlags() != RC->getNoWrapFlags()) 725 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags(); 726 727 for (unsigned i = 0; i != LNumOps; ++i) { 728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 729 LC->getOperand(i), RC->getOperand(i), DT, 730 Depth + 1); 731 if (X != 0) 732 return X; 733 } 734 EqCacheSCEV.unionSets(LHS, RHS); 735 return 0; 736 } 737 738 case scUDivExpr: { 739 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 740 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 741 742 // Lexicographically compare udiv expressions. 743 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 744 RC->getLHS(), DT, Depth + 1); 745 if (X != 0) 746 return X; 747 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 748 RC->getRHS(), DT, Depth + 1); 749 if (X == 0) 750 EqCacheSCEV.unionSets(LHS, RHS); 751 return X; 752 } 753 754 case scTruncate: 755 case scZeroExtend: 756 case scSignExtend: { 757 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 758 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 759 760 // Compare cast expressions by operand. 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 762 LC->getOperand(), RC->getOperand(), DT, 763 Depth + 1); 764 if (X == 0) 765 EqCacheSCEV.unionSets(LHS, RHS); 766 return X; 767 } 768 769 case scCouldNotCompute: 770 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 771 } 772 llvm_unreachable("Unknown SCEV kind!"); 773 } 774 775 /// Given a list of SCEV objects, order them by their complexity, and group 776 /// objects of the same complexity together by value. When this routine is 777 /// finished, we know that any duplicates in the vector are consecutive and that 778 /// complexity is monotonically increasing. 779 /// 780 /// Note that we go take special precautions to ensure that we get deterministic 781 /// results from this routine. In other words, we don't want the results of 782 /// this to depend on where the addresses of various SCEV objects happened to 783 /// land in memory. 784 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 785 LoopInfo *LI, DominatorTree &DT) { 786 if (Ops.size() < 2) return; // Noop 787 788 EquivalenceClasses<const SCEV *> EqCacheSCEV; 789 EquivalenceClasses<const Value *> EqCacheValue; 790 if (Ops.size() == 2) { 791 // This is the common case, which also happens to be trivially simple. 792 // Special case it. 793 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 794 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 795 std::swap(LHS, RHS); 796 return; 797 } 798 799 // Do the rough sort by complexity. 800 std::stable_sort(Ops.begin(), Ops.end(), 801 [&](const SCEV *LHS, const SCEV *RHS) { 802 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 803 LHS, RHS, DT) < 0; 804 }); 805 806 // Now that we are sorted by complexity, group elements of the same 807 // complexity. Note that this is, at worst, N^2, but the vector is likely to 808 // be extremely short in practice. Note that we take this approach because we 809 // do not want to depend on the addresses of the objects we are grouping. 810 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 811 const SCEV *S = Ops[i]; 812 unsigned Complexity = S->getSCEVType(); 813 814 // If there are any objects of the same complexity and same value as this 815 // one, group them. 816 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 817 if (Ops[j] == S) { // Found a duplicate. 818 // Move it to immediately after i'th element. 819 std::swap(Ops[i+1], Ops[j]); 820 ++i; // no need to rescan it. 821 if (i == e-2) return; // Done! 822 } 823 } 824 } 825 } 826 827 // Returns the size of the SCEV S. 828 static inline int sizeOfSCEV(const SCEV *S) { 829 struct FindSCEVSize { 830 int Size = 0; 831 832 FindSCEVSize() = default; 833 834 bool follow(const SCEV *S) { 835 ++Size; 836 // Keep looking at all operands of S. 837 return true; 838 } 839 840 bool isDone() const { 841 return false; 842 } 843 }; 844 845 FindSCEVSize F; 846 SCEVTraversal<FindSCEVSize> ST(F); 847 ST.visitAll(S); 848 return F.Size; 849 } 850 851 namespace { 852 853 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 854 public: 855 // Computes the Quotient and Remainder of the division of Numerator by 856 // Denominator. 857 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 858 const SCEV *Denominator, const SCEV **Quotient, 859 const SCEV **Remainder) { 860 assert(Numerator && Denominator && "Uninitialized SCEV"); 861 862 SCEVDivision D(SE, Numerator, Denominator); 863 864 // Check for the trivial case here to avoid having to check for it in the 865 // rest of the code. 866 if (Numerator == Denominator) { 867 *Quotient = D.One; 868 *Remainder = D.Zero; 869 return; 870 } 871 872 if (Numerator->isZero()) { 873 *Quotient = D.Zero; 874 *Remainder = D.Zero; 875 return; 876 } 877 878 // A simple case when N/1. The quotient is N. 879 if (Denominator->isOne()) { 880 *Quotient = Numerator; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 // Split the Denominator when it is a product. 886 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 887 const SCEV *Q, *R; 888 *Quotient = Numerator; 889 for (const SCEV *Op : T->operands()) { 890 divide(SE, *Quotient, Op, &Q, &R); 891 *Quotient = Q; 892 893 // Bail out when the Numerator is not divisible by one of the terms of 894 // the Denominator. 895 if (!R->isZero()) { 896 *Quotient = D.Zero; 897 *Remainder = Numerator; 898 return; 899 } 900 } 901 *Remainder = D.Zero; 902 return; 903 } 904 905 D.visit(Numerator); 906 *Quotient = D.Quotient; 907 *Remainder = D.Remainder; 908 } 909 910 // Except in the trivial case described above, we do not know how to divide 911 // Expr by Denominator for the following functions with empty implementation. 912 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 913 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 914 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 915 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 916 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 917 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 918 void visitUnknown(const SCEVUnknown *Numerator) {} 919 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 920 921 void visitConstant(const SCEVConstant *Numerator) { 922 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 923 APInt NumeratorVal = Numerator->getAPInt(); 924 APInt DenominatorVal = D->getAPInt(); 925 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 926 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 927 928 if (NumeratorBW > DenominatorBW) 929 DenominatorVal = DenominatorVal.sext(NumeratorBW); 930 else if (NumeratorBW < DenominatorBW) 931 NumeratorVal = NumeratorVal.sext(DenominatorBW); 932 933 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 934 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 935 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 936 Quotient = SE.getConstant(QuotientVal); 937 Remainder = SE.getConstant(RemainderVal); 938 return; 939 } 940 } 941 942 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 943 const SCEV *StartQ, *StartR, *StepQ, *StepR; 944 if (!Numerator->isAffine()) 945 return cannotDivide(Numerator); 946 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 947 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 948 // Bail out if the types do not match. 949 Type *Ty = Denominator->getType(); 950 if (Ty != StartQ->getType() || Ty != StartR->getType() || 951 Ty != StepQ->getType() || Ty != StepR->getType()) 952 return cannotDivide(Numerator); 953 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 954 Numerator->getNoWrapFlags()); 955 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 956 Numerator->getNoWrapFlags()); 957 } 958 959 void visitAddExpr(const SCEVAddExpr *Numerator) { 960 SmallVector<const SCEV *, 2> Qs, Rs; 961 Type *Ty = Denominator->getType(); 962 963 for (const SCEV *Op : Numerator->operands()) { 964 const SCEV *Q, *R; 965 divide(SE, Op, Denominator, &Q, &R); 966 967 // Bail out if types do not match. 968 if (Ty != Q->getType() || Ty != R->getType()) 969 return cannotDivide(Numerator); 970 971 Qs.push_back(Q); 972 Rs.push_back(R); 973 } 974 975 if (Qs.size() == 1) { 976 Quotient = Qs[0]; 977 Remainder = Rs[0]; 978 return; 979 } 980 981 Quotient = SE.getAddExpr(Qs); 982 Remainder = SE.getAddExpr(Rs); 983 } 984 985 void visitMulExpr(const SCEVMulExpr *Numerator) { 986 SmallVector<const SCEV *, 2> Qs; 987 Type *Ty = Denominator->getType(); 988 989 bool FoundDenominatorTerm = false; 990 for (const SCEV *Op : Numerator->operands()) { 991 // Bail out if types do not match. 992 if (Ty != Op->getType()) 993 return cannotDivide(Numerator); 994 995 if (FoundDenominatorTerm) { 996 Qs.push_back(Op); 997 continue; 998 } 999 1000 // Check whether Denominator divides one of the product operands. 1001 const SCEV *Q, *R; 1002 divide(SE, Op, Denominator, &Q, &R); 1003 if (!R->isZero()) { 1004 Qs.push_back(Op); 1005 continue; 1006 } 1007 1008 // Bail out if types do not match. 1009 if (Ty != Q->getType()) 1010 return cannotDivide(Numerator); 1011 1012 FoundDenominatorTerm = true; 1013 Qs.push_back(Q); 1014 } 1015 1016 if (FoundDenominatorTerm) { 1017 Remainder = Zero; 1018 if (Qs.size() == 1) 1019 Quotient = Qs[0]; 1020 else 1021 Quotient = SE.getMulExpr(Qs); 1022 return; 1023 } 1024 1025 if (!isa<SCEVUnknown>(Denominator)) 1026 return cannotDivide(Numerator); 1027 1028 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1029 ValueToValueMap RewriteMap; 1030 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1031 cast<SCEVConstant>(Zero)->getValue(); 1032 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1033 1034 if (Remainder->isZero()) { 1035 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1036 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1037 cast<SCEVConstant>(One)->getValue(); 1038 Quotient = 1039 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1040 return; 1041 } 1042 1043 // Quotient is (Numerator - Remainder) divided by Denominator. 1044 const SCEV *Q, *R; 1045 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1046 // This SCEV does not seem to simplify: fail the division here. 1047 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1048 return cannotDivide(Numerator); 1049 divide(SE, Diff, Denominator, &Q, &R); 1050 if (R != Zero) 1051 return cannotDivide(Numerator); 1052 Quotient = Q; 1053 } 1054 1055 private: 1056 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1057 const SCEV *Denominator) 1058 : SE(S), Denominator(Denominator) { 1059 Zero = SE.getZero(Denominator->getType()); 1060 One = SE.getOne(Denominator->getType()); 1061 1062 // We generally do not know how to divide Expr by Denominator. We 1063 // initialize the division to a "cannot divide" state to simplify the rest 1064 // of the code. 1065 cannotDivide(Numerator); 1066 } 1067 1068 // Convenience function for giving up on the division. We set the quotient to 1069 // be equal to zero and the remainder to be equal to the numerator. 1070 void cannotDivide(const SCEV *Numerator) { 1071 Quotient = Zero; 1072 Remainder = Numerator; 1073 } 1074 1075 ScalarEvolution &SE; 1076 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1077 }; 1078 1079 } // end anonymous namespace 1080 1081 //===----------------------------------------------------------------------===// 1082 // Simple SCEV method implementations 1083 //===----------------------------------------------------------------------===// 1084 1085 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1086 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1087 ScalarEvolution &SE, 1088 Type *ResultTy) { 1089 // Handle the simplest case efficiently. 1090 if (K == 1) 1091 return SE.getTruncateOrZeroExtend(It, ResultTy); 1092 1093 // We are using the following formula for BC(It, K): 1094 // 1095 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1096 // 1097 // Suppose, W is the bitwidth of the return value. We must be prepared for 1098 // overflow. Hence, we must assure that the result of our computation is 1099 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1100 // safe in modular arithmetic. 1101 // 1102 // However, this code doesn't use exactly that formula; the formula it uses 1103 // is something like the following, where T is the number of factors of 2 in 1104 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1105 // exponentiation: 1106 // 1107 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1108 // 1109 // This formula is trivially equivalent to the previous formula. However, 1110 // this formula can be implemented much more efficiently. The trick is that 1111 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1112 // arithmetic. To do exact division in modular arithmetic, all we have 1113 // to do is multiply by the inverse. Therefore, this step can be done at 1114 // width W. 1115 // 1116 // The next issue is how to safely do the division by 2^T. The way this 1117 // is done is by doing the multiplication step at a width of at least W + T 1118 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1119 // when we perform the division by 2^T (which is equivalent to a right shift 1120 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1121 // truncated out after the division by 2^T. 1122 // 1123 // In comparison to just directly using the first formula, this technique 1124 // is much more efficient; using the first formula requires W * K bits, 1125 // but this formula less than W + K bits. Also, the first formula requires 1126 // a division step, whereas this formula only requires multiplies and shifts. 1127 // 1128 // It doesn't matter whether the subtraction step is done in the calculation 1129 // width or the input iteration count's width; if the subtraction overflows, 1130 // the result must be zero anyway. We prefer here to do it in the width of 1131 // the induction variable because it helps a lot for certain cases; CodeGen 1132 // isn't smart enough to ignore the overflow, which leads to much less 1133 // efficient code if the width of the subtraction is wider than the native 1134 // register width. 1135 // 1136 // (It's possible to not widen at all by pulling out factors of 2 before 1137 // the multiplication; for example, K=2 can be calculated as 1138 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1139 // extra arithmetic, so it's not an obvious win, and it gets 1140 // much more complicated for K > 3.) 1141 1142 // Protection from insane SCEVs; this bound is conservative, 1143 // but it probably doesn't matter. 1144 if (K > 1000) 1145 return SE.getCouldNotCompute(); 1146 1147 unsigned W = SE.getTypeSizeInBits(ResultTy); 1148 1149 // Calculate K! / 2^T and T; we divide out the factors of two before 1150 // multiplying for calculating K! / 2^T to avoid overflow. 1151 // Other overflow doesn't matter because we only care about the bottom 1152 // W bits of the result. 1153 APInt OddFactorial(W, 1); 1154 unsigned T = 1; 1155 for (unsigned i = 3; i <= K; ++i) { 1156 APInt Mult(W, i); 1157 unsigned TwoFactors = Mult.countTrailingZeros(); 1158 T += TwoFactors; 1159 Mult.lshrInPlace(TwoFactors); 1160 OddFactorial *= Mult; 1161 } 1162 1163 // We need at least W + T bits for the multiplication step 1164 unsigned CalculationBits = W + T; 1165 1166 // Calculate 2^T, at width T+W. 1167 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1168 1169 // Calculate the multiplicative inverse of K! / 2^T; 1170 // this multiplication factor will perform the exact division by 1171 // K! / 2^T. 1172 APInt Mod = APInt::getSignedMinValue(W+1); 1173 APInt MultiplyFactor = OddFactorial.zext(W+1); 1174 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1175 MultiplyFactor = MultiplyFactor.trunc(W); 1176 1177 // Calculate the product, at width T+W 1178 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1179 CalculationBits); 1180 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1181 for (unsigned i = 1; i != K; ++i) { 1182 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1183 Dividend = SE.getMulExpr(Dividend, 1184 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1185 } 1186 1187 // Divide by 2^T 1188 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1189 1190 // Truncate the result, and divide by K! / 2^T. 1191 1192 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1193 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1194 } 1195 1196 /// Return the value of this chain of recurrences at the specified iteration 1197 /// number. We can evaluate this recurrence by multiplying each element in the 1198 /// chain by the binomial coefficient corresponding to it. In other words, we 1199 /// can evaluate {A,+,B,+,C,+,D} as: 1200 /// 1201 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1202 /// 1203 /// where BC(It, k) stands for binomial coefficient. 1204 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1205 ScalarEvolution &SE) const { 1206 const SCEV *Result = getStart(); 1207 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1208 // The computation is correct in the face of overflow provided that the 1209 // multiplication is performed _after_ the evaluation of the binomial 1210 // coefficient. 1211 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1212 if (isa<SCEVCouldNotCompute>(Coeff)) 1213 return Coeff; 1214 1215 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1216 } 1217 return Result; 1218 } 1219 1220 //===----------------------------------------------------------------------===// 1221 // SCEV Expression folder implementations 1222 //===----------------------------------------------------------------------===// 1223 1224 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1225 Type *Ty) { 1226 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1227 "This is not a truncating conversion!"); 1228 assert(isSCEVable(Ty) && 1229 "This is not a conversion to a SCEVable type!"); 1230 Ty = getEffectiveSCEVType(Ty); 1231 1232 FoldingSetNodeID ID; 1233 ID.AddInteger(scTruncate); 1234 ID.AddPointer(Op); 1235 ID.AddPointer(Ty); 1236 void *IP = nullptr; 1237 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1238 1239 // Fold if the operand is constant. 1240 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1241 return getConstant( 1242 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1243 1244 // trunc(trunc(x)) --> trunc(x) 1245 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1246 return getTruncateExpr(ST->getOperand(), Ty); 1247 1248 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1249 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1250 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1251 1252 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1253 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1254 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1255 1256 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1257 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1258 // if after transforming we have at most one truncate, not counting truncates 1259 // that replace other casts. 1260 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1261 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1262 SmallVector<const SCEV *, 4> Operands; 1263 unsigned numTruncs = 0; 1264 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1265 ++i) { 1266 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty); 1267 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1268 numTruncs++; 1269 Operands.push_back(S); 1270 } 1271 if (numTruncs < 2) { 1272 if (isa<SCEVAddExpr>(Op)) 1273 return getAddExpr(Operands); 1274 else if (isa<SCEVMulExpr>(Op)) 1275 return getMulExpr(Operands); 1276 else 1277 llvm_unreachable("Unexpected SCEV type for Op."); 1278 } 1279 // Although we checked in the beginning that ID is not in the cache, it is 1280 // possible that during recursion and different modification ID was inserted 1281 // into the cache. So if we find it, just return it. 1282 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1283 return S; 1284 } 1285 1286 // If the input value is a chrec scev, truncate the chrec's operands. 1287 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1288 SmallVector<const SCEV *, 4> Operands; 1289 for (const SCEV *Op : AddRec->operands()) 1290 Operands.push_back(getTruncateExpr(Op, Ty)); 1291 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1292 } 1293 1294 // The cast wasn't folded; create an explicit cast node. We can reuse 1295 // the existing insert position since if we get here, we won't have 1296 // made any changes which would invalidate it. 1297 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1298 Op, Ty); 1299 UniqueSCEVs.InsertNode(S, IP); 1300 addToLoopUseLists(S); 1301 return S; 1302 } 1303 1304 // Get the limit of a recurrence such that incrementing by Step cannot cause 1305 // signed overflow as long as the value of the recurrence within the 1306 // loop does not exceed this limit before incrementing. 1307 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1308 ICmpInst::Predicate *Pred, 1309 ScalarEvolution *SE) { 1310 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1311 if (SE->isKnownPositive(Step)) { 1312 *Pred = ICmpInst::ICMP_SLT; 1313 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1314 SE->getSignedRangeMax(Step)); 1315 } 1316 if (SE->isKnownNegative(Step)) { 1317 *Pred = ICmpInst::ICMP_SGT; 1318 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1319 SE->getSignedRangeMin(Step)); 1320 } 1321 return nullptr; 1322 } 1323 1324 // Get the limit of a recurrence such that incrementing by Step cannot cause 1325 // unsigned overflow as long as the value of the recurrence within the loop does 1326 // not exceed this limit before incrementing. 1327 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1328 ICmpInst::Predicate *Pred, 1329 ScalarEvolution *SE) { 1330 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1331 *Pred = ICmpInst::ICMP_ULT; 1332 1333 return SE->getConstant(APInt::getMinValue(BitWidth) - 1334 SE->getUnsignedRangeMax(Step)); 1335 } 1336 1337 namespace { 1338 1339 struct ExtendOpTraitsBase { 1340 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1341 unsigned); 1342 }; 1343 1344 // Used to make code generic over signed and unsigned overflow. 1345 template <typename ExtendOp> struct ExtendOpTraits { 1346 // Members present: 1347 // 1348 // static const SCEV::NoWrapFlags WrapType; 1349 // 1350 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1351 // 1352 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1353 // ICmpInst::Predicate *Pred, 1354 // ScalarEvolution *SE); 1355 }; 1356 1357 template <> 1358 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1359 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1360 1361 static const GetExtendExprTy GetExtendExpr; 1362 1363 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1364 ICmpInst::Predicate *Pred, 1365 ScalarEvolution *SE) { 1366 return getSignedOverflowLimitForStep(Step, Pred, SE); 1367 } 1368 }; 1369 1370 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1371 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1372 1373 template <> 1374 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1375 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1376 1377 static const GetExtendExprTy GetExtendExpr; 1378 1379 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1380 ICmpInst::Predicate *Pred, 1381 ScalarEvolution *SE) { 1382 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1383 } 1384 }; 1385 1386 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1387 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1388 1389 } // end anonymous namespace 1390 1391 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1392 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1393 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1394 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1395 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1396 // expression "Step + sext/zext(PreIncAR)" is congruent with 1397 // "sext/zext(PostIncAR)" 1398 template <typename ExtendOpTy> 1399 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1400 ScalarEvolution *SE, unsigned Depth) { 1401 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1402 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1403 1404 const Loop *L = AR->getLoop(); 1405 const SCEV *Start = AR->getStart(); 1406 const SCEV *Step = AR->getStepRecurrence(*SE); 1407 1408 // Check for a simple looking step prior to loop entry. 1409 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1410 if (!SA) 1411 return nullptr; 1412 1413 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1414 // subtraction is expensive. For this purpose, perform a quick and dirty 1415 // difference, by checking for Step in the operand list. 1416 SmallVector<const SCEV *, 4> DiffOps; 1417 for (const SCEV *Op : SA->operands()) 1418 if (Op != Step) 1419 DiffOps.push_back(Op); 1420 1421 if (DiffOps.size() == SA->getNumOperands()) 1422 return nullptr; 1423 1424 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1425 // `Step`: 1426 1427 // 1. NSW/NUW flags on the step increment. 1428 auto PreStartFlags = 1429 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1430 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1431 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1432 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1433 1434 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1435 // "S+X does not sign/unsign-overflow". 1436 // 1437 1438 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1439 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1440 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1441 return PreStart; 1442 1443 // 2. Direct overflow check on the step operation's expression. 1444 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1445 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1446 const SCEV *OperandExtendedStart = 1447 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1448 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1449 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1450 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1451 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1452 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1453 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1454 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1455 } 1456 return PreStart; 1457 } 1458 1459 // 3. Loop precondition. 1460 ICmpInst::Predicate Pred; 1461 const SCEV *OverflowLimit = 1462 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1463 1464 if (OverflowLimit && 1465 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1466 return PreStart; 1467 1468 return nullptr; 1469 } 1470 1471 // Get the normalized zero or sign extended expression for this AddRec's Start. 1472 template <typename ExtendOpTy> 1473 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1474 ScalarEvolution *SE, 1475 unsigned Depth) { 1476 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1477 1478 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1479 if (!PreStart) 1480 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1481 1482 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1483 Depth), 1484 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1485 } 1486 1487 // Try to prove away overflow by looking at "nearby" add recurrences. A 1488 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1489 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1490 // 1491 // Formally: 1492 // 1493 // {S,+,X} == {S-T,+,X} + T 1494 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1495 // 1496 // If ({S-T,+,X} + T) does not overflow ... (1) 1497 // 1498 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1499 // 1500 // If {S-T,+,X} does not overflow ... (2) 1501 // 1502 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1503 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1504 // 1505 // If (S-T)+T does not overflow ... (3) 1506 // 1507 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1508 // == {Ext(S),+,Ext(X)} == LHS 1509 // 1510 // Thus, if (1), (2) and (3) are true for some T, then 1511 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1512 // 1513 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1514 // does not overflow" restricted to the 0th iteration. Therefore we only need 1515 // to check for (1) and (2). 1516 // 1517 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1518 // is `Delta` (defined below). 1519 template <typename ExtendOpTy> 1520 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1521 const SCEV *Step, 1522 const Loop *L) { 1523 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1524 1525 // We restrict `Start` to a constant to prevent SCEV from spending too much 1526 // time here. It is correct (but more expensive) to continue with a 1527 // non-constant `Start` and do a general SCEV subtraction to compute 1528 // `PreStart` below. 1529 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1530 if (!StartC) 1531 return false; 1532 1533 APInt StartAI = StartC->getAPInt(); 1534 1535 for (unsigned Delta : {-2, -1, 1, 2}) { 1536 const SCEV *PreStart = getConstant(StartAI - Delta); 1537 1538 FoldingSetNodeID ID; 1539 ID.AddInteger(scAddRecExpr); 1540 ID.AddPointer(PreStart); 1541 ID.AddPointer(Step); 1542 ID.AddPointer(L); 1543 void *IP = nullptr; 1544 const auto *PreAR = 1545 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1546 1547 // Give up if we don't already have the add recurrence we need because 1548 // actually constructing an add recurrence is relatively expensive. 1549 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1550 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1551 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1552 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1553 DeltaS, &Pred, this); 1554 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1555 return true; 1556 } 1557 } 1558 1559 return false; 1560 } 1561 1562 const SCEV * 1563 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1564 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1565 "This is not an extending conversion!"); 1566 assert(isSCEVable(Ty) && 1567 "This is not a conversion to a SCEVable type!"); 1568 Ty = getEffectiveSCEVType(Ty); 1569 1570 // Fold if the operand is constant. 1571 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1572 return getConstant( 1573 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1574 1575 // zext(zext(x)) --> zext(x) 1576 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1577 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1578 1579 // Before doing any expensive analysis, check to see if we've already 1580 // computed a SCEV for this Op and Ty. 1581 FoldingSetNodeID ID; 1582 ID.AddInteger(scZeroExtend); 1583 ID.AddPointer(Op); 1584 ID.AddPointer(Ty); 1585 void *IP = nullptr; 1586 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1587 if (Depth > MaxExtDepth) { 1588 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1589 Op, Ty); 1590 UniqueSCEVs.InsertNode(S, IP); 1591 addToLoopUseLists(S); 1592 return S; 1593 } 1594 1595 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1596 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1597 // It's possible the bits taken off by the truncate were all zero bits. If 1598 // so, we should be able to simplify this further. 1599 const SCEV *X = ST->getOperand(); 1600 ConstantRange CR = getUnsignedRange(X); 1601 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1602 unsigned NewBits = getTypeSizeInBits(Ty); 1603 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1604 CR.zextOrTrunc(NewBits))) 1605 return getTruncateOrZeroExtend(X, Ty); 1606 } 1607 1608 // If the input value is a chrec scev, and we can prove that the value 1609 // did not overflow the old, smaller, value, we can zero extend all of the 1610 // operands (often constants). This allows analysis of something like 1611 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1612 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1613 if (AR->isAffine()) { 1614 const SCEV *Start = AR->getStart(); 1615 const SCEV *Step = AR->getStepRecurrence(*this); 1616 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1617 const Loop *L = AR->getLoop(); 1618 1619 if (!AR->hasNoUnsignedWrap()) { 1620 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1621 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1622 } 1623 1624 // If we have special knowledge that this addrec won't overflow, 1625 // we don't need to do any further analysis. 1626 if (AR->hasNoUnsignedWrap()) 1627 return getAddRecExpr( 1628 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1629 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1630 1631 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1632 // Note that this serves two purposes: It filters out loops that are 1633 // simply not analyzable, and it covers the case where this code is 1634 // being called from within backedge-taken count analysis, such that 1635 // attempting to ask for the backedge-taken count would likely result 1636 // in infinite recursion. In the later case, the analysis code will 1637 // cope with a conservative value, and it will take care to purge 1638 // that value once it has finished. 1639 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1640 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1641 // Manually compute the final value for AR, checking for 1642 // overflow. 1643 1644 // Check whether the backedge-taken count can be losslessly casted to 1645 // the addrec's type. The count is always unsigned. 1646 const SCEV *CastedMaxBECount = 1647 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1648 const SCEV *RecastedMaxBECount = 1649 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1650 if (MaxBECount == RecastedMaxBECount) { 1651 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1652 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1653 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1654 SCEV::FlagAnyWrap, Depth + 1); 1655 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1656 SCEV::FlagAnyWrap, 1657 Depth + 1), 1658 WideTy, Depth + 1); 1659 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1660 const SCEV *WideMaxBECount = 1661 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1662 const SCEV *OperandExtendedAdd = 1663 getAddExpr(WideStart, 1664 getMulExpr(WideMaxBECount, 1665 getZeroExtendExpr(Step, WideTy, Depth + 1), 1666 SCEV::FlagAnyWrap, Depth + 1), 1667 SCEV::FlagAnyWrap, Depth + 1); 1668 if (ZAdd == OperandExtendedAdd) { 1669 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1670 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1671 // Return the expression with the addrec on the outside. 1672 return getAddRecExpr( 1673 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1674 Depth + 1), 1675 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1676 AR->getNoWrapFlags()); 1677 } 1678 // Similar to above, only this time treat the step value as signed. 1679 // This covers loops that count down. 1680 OperandExtendedAdd = 1681 getAddExpr(WideStart, 1682 getMulExpr(WideMaxBECount, 1683 getSignExtendExpr(Step, WideTy, Depth + 1), 1684 SCEV::FlagAnyWrap, Depth + 1), 1685 SCEV::FlagAnyWrap, Depth + 1); 1686 if (ZAdd == OperandExtendedAdd) { 1687 // Cache knowledge of AR NW, which is propagated to this AddRec. 1688 // Negative step causes unsigned wrap, but it 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, 1693 Depth + 1), 1694 getSignExtendExpr(Step, Ty, Depth + 1), L, 1695 AR->getNoWrapFlags()); 1696 } 1697 } 1698 } 1699 1700 // Normally, in the cases we can prove no-overflow via a 1701 // backedge guarding condition, we can also compute a backedge 1702 // taken count for the loop. The exceptions are assumptions and 1703 // guards present in the loop -- SCEV is not great at exploiting 1704 // these to compute max backedge taken counts, but can still use 1705 // these to prove lack of overflow. Use this fact to avoid 1706 // doing extra work that may not pay off. 1707 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1708 !AC.assumptions().empty()) { 1709 // If the backedge is guarded by a comparison with the pre-inc 1710 // value the addrec is safe. Also, if the entry is guarded by 1711 // a comparison with the start value and the backedge is 1712 // guarded by a comparison with the post-inc value, the addrec 1713 // is safe. 1714 if (isKnownPositive(Step)) { 1715 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1716 getUnsignedRangeMax(Step)); 1717 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1718 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1719 // Cache knowledge of AR NUW, which is propagated to this 1720 // AddRec. 1721 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1722 // Return the expression with the addrec on the outside. 1723 return getAddRecExpr( 1724 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1725 Depth + 1), 1726 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1727 AR->getNoWrapFlags()); 1728 } 1729 } else if (isKnownNegative(Step)) { 1730 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1731 getSignedRangeMin(Step)); 1732 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1733 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1734 // Cache knowledge of AR NW, which is propagated to this 1735 // AddRec. Negative step causes unsigned wrap, but it 1736 // still can't self-wrap. 1737 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1738 // Return the expression with the addrec on the outside. 1739 return getAddRecExpr( 1740 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1741 Depth + 1), 1742 getSignExtendExpr(Step, Ty, Depth + 1), L, 1743 AR->getNoWrapFlags()); 1744 } 1745 } 1746 } 1747 1748 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1752 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1753 } 1754 } 1755 1756 // zext(A % B) --> zext(A) % zext(B) 1757 { 1758 const SCEV *LHS; 1759 const SCEV *RHS; 1760 if (matchURem(Op, LHS, RHS)) 1761 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1762 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1763 } 1764 1765 // zext(A / B) --> zext(A) / zext(B). 1766 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1767 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1768 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1769 1770 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1771 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1772 if (SA->hasNoUnsignedWrap()) { 1773 // If the addition does not unsign overflow then we can, by definition, 1774 // commute the zero extension with the addition operation. 1775 SmallVector<const SCEV *, 4> Ops; 1776 for (const auto *Op : SA->operands()) 1777 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1778 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1779 } 1780 1781 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))<nuw> 1782 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1783 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1784 // 1785 // Useful while proving that address arithmetic expressions are equal or 1786 // differ by a small constant amount, see LoadStoreVectorizer pass. 1787 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1788 // Often address arithmetics contain expressions like 1789 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1790 // ConstantRange is unable to prove that it's possible to transform 1791 // (5 + (4 * X)) to (1 + (4 + (4 * X))) w/o underflowing: 1792 // 1793 // | Expression | ConstantRange | KnownBits | 1794 // |---------------|------------------------|-----------------------| 1795 // | i8 4 * X | [L: 0, U: 253) | XXXX XX00 | 1796 // | | => Min: 0, Max: 252 | => Min: 0, Max: 252 | 1797 // | | | | 1798 // | i8 4 * X + 5 | [L: 5, U: 2) (wrapped) | YYYY YY01 | 1799 // | (101) | => Min: 0, Max: 255 | => Min: 1, Max: 253 | 1800 // 1801 // As KnownBits are not available for SCEV expressions, use number of 1802 // trailing zeroes instead: 1803 APInt C = SC->getAPInt(); 1804 uint32_t TZ = C.getBitWidth(); 1805 for (unsigned I = 1, E = SA->getNumOperands(); I < E && TZ; ++I) 1806 TZ = std::min(TZ, GetMinTrailingZeros(SA->getOperand(I))); 1807 if (TZ) { 1808 APInt D = TZ < C.getBitWidth() ? C.trunc(TZ).zext(C.getBitWidth()) : C; 1809 if (D != 0) { 1810 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1811 const SCEV *SResidual = 1812 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1813 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1814 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNUW, Depth + 1); 1815 } 1816 } 1817 } 1818 } 1819 1820 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1821 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1822 if (SM->hasNoUnsignedWrap()) { 1823 // If the multiply does not unsign overflow then we can, by definition, 1824 // commute the zero extension with the multiply operation. 1825 SmallVector<const SCEV *, 4> Ops; 1826 for (const auto *Op : SM->operands()) 1827 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1828 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1829 } 1830 1831 // zext(2^K * (trunc X to iN)) to iM -> 1832 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1833 // 1834 // Proof: 1835 // 1836 // zext(2^K * (trunc X to iN)) to iM 1837 // = zext((trunc X to iN) << K) to iM 1838 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1839 // (because shl removes the top K bits) 1840 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1841 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1842 // 1843 if (SM->getNumOperands() == 2) 1844 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1845 if (MulLHS->getAPInt().isPowerOf2()) 1846 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1847 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1848 MulLHS->getAPInt().logBase2(); 1849 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1850 return getMulExpr( 1851 getZeroExtendExpr(MulLHS, Ty), 1852 getZeroExtendExpr( 1853 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1854 SCEV::FlagNUW, Depth + 1); 1855 } 1856 } 1857 1858 // The cast wasn't folded; create an explicit cast node. 1859 // Recompute the insert position, as it may have been invalidated. 1860 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1861 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1862 Op, Ty); 1863 UniqueSCEVs.InsertNode(S, IP); 1864 addToLoopUseLists(S); 1865 return S; 1866 } 1867 1868 const SCEV * 1869 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1870 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1871 "This is not an extending conversion!"); 1872 assert(isSCEVable(Ty) && 1873 "This is not a conversion to a SCEVable type!"); 1874 Ty = getEffectiveSCEVType(Ty); 1875 1876 // Fold if the operand is constant. 1877 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1878 return getConstant( 1879 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1880 1881 // sext(sext(x)) --> sext(x) 1882 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1883 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1884 1885 // sext(zext(x)) --> zext(x) 1886 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1887 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1888 1889 // Before doing any expensive analysis, check to see if we've already 1890 // computed a SCEV for this Op and Ty. 1891 FoldingSetNodeID ID; 1892 ID.AddInteger(scSignExtend); 1893 ID.AddPointer(Op); 1894 ID.AddPointer(Ty); 1895 void *IP = nullptr; 1896 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1897 // Limit recursion depth. 1898 if (Depth > MaxExtDepth) { 1899 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1900 Op, Ty); 1901 UniqueSCEVs.InsertNode(S, IP); 1902 addToLoopUseLists(S); 1903 return S; 1904 } 1905 1906 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1907 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1908 // It's possible the bits taken off by the truncate were all sign bits. If 1909 // so, we should be able to simplify this further. 1910 const SCEV *X = ST->getOperand(); 1911 ConstantRange CR = getSignedRange(X); 1912 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1913 unsigned NewBits = getTypeSizeInBits(Ty); 1914 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1915 CR.sextOrTrunc(NewBits))) 1916 return getTruncateOrSignExtend(X, Ty); 1917 } 1918 1919 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1920 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1921 if (SA->getNumOperands() == 2) { 1922 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1923 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1924 if (SMul && SC1) { 1925 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1926 const APInt &C1 = SC1->getAPInt(); 1927 const APInt &C2 = SC2->getAPInt(); 1928 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1929 C2.ugt(C1) && C2.isPowerOf2()) 1930 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1931 getSignExtendExpr(SMul, Ty, Depth + 1), 1932 SCEV::FlagAnyWrap, Depth + 1); 1933 } 1934 } 1935 } 1936 1937 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1938 if (SA->hasNoSignedWrap()) { 1939 // If the addition does not sign overflow then we can, by definition, 1940 // commute the sign extension with the addition operation. 1941 SmallVector<const SCEV *, 4> Ops; 1942 for (const auto *Op : SA->operands()) 1943 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1944 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1945 } 1946 } 1947 // If the input value is a chrec scev, and we can prove that the value 1948 // did not overflow the old, smaller, value, we can sign extend all of the 1949 // operands (often constants). This allows analysis of something like 1950 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1951 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1952 if (AR->isAffine()) { 1953 const SCEV *Start = AR->getStart(); 1954 const SCEV *Step = AR->getStepRecurrence(*this); 1955 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1956 const Loop *L = AR->getLoop(); 1957 1958 if (!AR->hasNoSignedWrap()) { 1959 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1960 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1961 } 1962 1963 // If we have special knowledge that this addrec won't overflow, 1964 // we don't need to do any further analysis. 1965 if (AR->hasNoSignedWrap()) 1966 return getAddRecExpr( 1967 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1968 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1969 1970 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1971 // Note that this serves two purposes: It filters out loops that are 1972 // simply not analyzable, and it covers the case where this code is 1973 // being called from within backedge-taken count analysis, such that 1974 // attempting to ask for the backedge-taken count would likely result 1975 // in infinite recursion. In the later case, the analysis code will 1976 // cope with a conservative value, and it will take care to purge 1977 // that value once it has finished. 1978 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1979 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1980 // Manually compute the final value for AR, checking for 1981 // overflow. 1982 1983 // Check whether the backedge-taken count can be losslessly casted to 1984 // the addrec's type. The count is always unsigned. 1985 const SCEV *CastedMaxBECount = 1986 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1987 const SCEV *RecastedMaxBECount = 1988 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1989 if (MaxBECount == RecastedMaxBECount) { 1990 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1991 // Check whether Start+Step*MaxBECount has no signed overflow. 1992 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1993 SCEV::FlagAnyWrap, Depth + 1); 1994 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1995 SCEV::FlagAnyWrap, 1996 Depth + 1), 1997 WideTy, Depth + 1); 1998 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1999 const SCEV *WideMaxBECount = 2000 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2001 const SCEV *OperandExtendedAdd = 2002 getAddExpr(WideStart, 2003 getMulExpr(WideMaxBECount, 2004 getSignExtendExpr(Step, WideTy, Depth + 1), 2005 SCEV::FlagAnyWrap, Depth + 1), 2006 SCEV::FlagAnyWrap, Depth + 1); 2007 if (SAdd == OperandExtendedAdd) { 2008 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2009 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2010 // Return the expression with the addrec on the outside. 2011 return getAddRecExpr( 2012 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2013 Depth + 1), 2014 getSignExtendExpr(Step, Ty, Depth + 1), L, 2015 AR->getNoWrapFlags()); 2016 } 2017 // Similar to above, only this time treat the step value as unsigned. 2018 // This covers loops that count up with an unsigned step. 2019 OperandExtendedAdd = 2020 getAddExpr(WideStart, 2021 getMulExpr(WideMaxBECount, 2022 getZeroExtendExpr(Step, WideTy, Depth + 1), 2023 SCEV::FlagAnyWrap, Depth + 1), 2024 SCEV::FlagAnyWrap, Depth + 1); 2025 if (SAdd == OperandExtendedAdd) { 2026 // If AR wraps around then 2027 // 2028 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2029 // => SAdd != OperandExtendedAdd 2030 // 2031 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2032 // (SAdd == OperandExtendedAdd => AR is NW) 2033 2034 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2035 2036 // Return the expression with the addrec on the outside. 2037 return getAddRecExpr( 2038 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2039 Depth + 1), 2040 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2041 AR->getNoWrapFlags()); 2042 } 2043 } 2044 } 2045 2046 // Normally, in the cases we can prove no-overflow via a 2047 // backedge guarding condition, we can also compute a backedge 2048 // taken count for the loop. The exceptions are assumptions and 2049 // guards present in the loop -- SCEV is not great at exploiting 2050 // these to compute max backedge taken counts, but can still use 2051 // these to prove lack of overflow. Use this fact to avoid 2052 // doing extra work that may not pay off. 2053 2054 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2055 !AC.assumptions().empty()) { 2056 // If the backedge is guarded by a comparison with the pre-inc 2057 // value the addrec is safe. Also, if the entry is guarded by 2058 // a comparison with the start value and the backedge is 2059 // guarded by a comparison with the post-inc value, the addrec 2060 // is safe. 2061 ICmpInst::Predicate Pred; 2062 const SCEV *OverflowLimit = 2063 getSignedOverflowLimitForStep(Step, &Pred, this); 2064 if (OverflowLimit && 2065 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2066 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2067 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2068 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2069 return getAddRecExpr( 2070 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2071 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2072 } 2073 } 2074 2075 // If Start and Step are constants, check if we can apply this 2076 // transformation: 2077 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2078 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2079 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2080 if (SC1 && SC2) { 2081 const APInt &C1 = SC1->getAPInt(); 2082 const APInt &C2 = SC2->getAPInt(); 2083 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2084 C2.isPowerOf2()) { 2085 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2086 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2087 AR->getNoWrapFlags()); 2088 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2089 SCEV::FlagAnyWrap, Depth + 1); 2090 } 2091 } 2092 2093 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2094 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2095 return getAddRecExpr( 2096 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2097 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2098 } 2099 } 2100 2101 // If the input value is provably positive and we could not simplify 2102 // away the sext build a zext instead. 2103 if (isKnownNonNegative(Op)) 2104 return getZeroExtendExpr(Op, Ty, Depth + 1); 2105 2106 // The cast wasn't folded; create an explicit cast node. 2107 // Recompute the insert position, as it may have been invalidated. 2108 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2109 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2110 Op, Ty); 2111 UniqueSCEVs.InsertNode(S, IP); 2112 addToLoopUseLists(S); 2113 return S; 2114 } 2115 2116 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2117 /// unspecified bits out to the given type. 2118 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2119 Type *Ty) { 2120 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2121 "This is not an extending conversion!"); 2122 assert(isSCEVable(Ty) && 2123 "This is not a conversion to a SCEVable type!"); 2124 Ty = getEffectiveSCEVType(Ty); 2125 2126 // Sign-extend negative constants. 2127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2128 if (SC->getAPInt().isNegative()) 2129 return getSignExtendExpr(Op, Ty); 2130 2131 // Peel off a truncate cast. 2132 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2133 const SCEV *NewOp = T->getOperand(); 2134 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2135 return getAnyExtendExpr(NewOp, Ty); 2136 return getTruncateOrNoop(NewOp, Ty); 2137 } 2138 2139 // Next try a zext cast. If the cast is folded, use it. 2140 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2141 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2142 return ZExt; 2143 2144 // Next try a sext cast. If the cast is folded, use it. 2145 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2146 if (!isa<SCEVSignExtendExpr>(SExt)) 2147 return SExt; 2148 2149 // Force the cast to be folded into the operands of an addrec. 2150 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2151 SmallVector<const SCEV *, 4> Ops; 2152 for (const SCEV *Op : AR->operands()) 2153 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2154 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2155 } 2156 2157 // If the expression is obviously signed, use the sext cast value. 2158 if (isa<SCEVSMaxExpr>(Op)) 2159 return SExt; 2160 2161 // Absent any other information, use the zext cast value. 2162 return ZExt; 2163 } 2164 2165 /// Process the given Ops list, which is a list of operands to be added under 2166 /// the given scale, update the given map. This is a helper function for 2167 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2168 /// that would form an add expression like this: 2169 /// 2170 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2171 /// 2172 /// where A and B are constants, update the map with these values: 2173 /// 2174 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2175 /// 2176 /// and add 13 + A*B*29 to AccumulatedConstant. 2177 /// This will allow getAddRecExpr to produce this: 2178 /// 2179 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2180 /// 2181 /// This form often exposes folding opportunities that are hidden in 2182 /// the original operand list. 2183 /// 2184 /// Return true iff it appears that any interesting folding opportunities 2185 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2186 /// the common case where no interesting opportunities are present, and 2187 /// is also used as a check to avoid infinite recursion. 2188 static bool 2189 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2190 SmallVectorImpl<const SCEV *> &NewOps, 2191 APInt &AccumulatedConstant, 2192 const SCEV *const *Ops, size_t NumOperands, 2193 const APInt &Scale, 2194 ScalarEvolution &SE) { 2195 bool Interesting = false; 2196 2197 // Iterate over the add operands. They are sorted, with constants first. 2198 unsigned i = 0; 2199 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2200 ++i; 2201 // Pull a buried constant out to the outside. 2202 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2203 Interesting = true; 2204 AccumulatedConstant += Scale * C->getAPInt(); 2205 } 2206 2207 // Next comes everything else. We're especially interested in multiplies 2208 // here, but they're in the middle, so just visit the rest with one loop. 2209 for (; i != NumOperands; ++i) { 2210 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2211 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2212 APInt NewScale = 2213 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2214 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2215 // A multiplication of a constant with another add; recurse. 2216 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2217 Interesting |= 2218 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2219 Add->op_begin(), Add->getNumOperands(), 2220 NewScale, SE); 2221 } else { 2222 // A multiplication of a constant with some other value. Update 2223 // the map. 2224 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2225 const SCEV *Key = SE.getMulExpr(MulOps); 2226 auto Pair = M.insert({Key, NewScale}); 2227 if (Pair.second) { 2228 NewOps.push_back(Pair.first->first); 2229 } else { 2230 Pair.first->second += NewScale; 2231 // The map already had an entry for this value, which may indicate 2232 // a folding opportunity. 2233 Interesting = true; 2234 } 2235 } 2236 } else { 2237 // An ordinary operand. Update the map. 2238 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2239 M.insert({Ops[i], Scale}); 2240 if (Pair.second) { 2241 NewOps.push_back(Pair.first->first); 2242 } else { 2243 Pair.first->second += Scale; 2244 // The map already had an entry for this value, which may indicate 2245 // a folding opportunity. 2246 Interesting = true; 2247 } 2248 } 2249 } 2250 2251 return Interesting; 2252 } 2253 2254 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2255 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2256 // can't-overflow flags for the operation if possible. 2257 static SCEV::NoWrapFlags 2258 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2259 const SmallVectorImpl<const SCEV *> &Ops, 2260 SCEV::NoWrapFlags Flags) { 2261 using namespace std::placeholders; 2262 2263 using OBO = OverflowingBinaryOperator; 2264 2265 bool CanAnalyze = 2266 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2267 (void)CanAnalyze; 2268 assert(CanAnalyze && "don't call from other places!"); 2269 2270 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2271 SCEV::NoWrapFlags SignOrUnsignWrap = 2272 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2273 2274 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2275 auto IsKnownNonNegative = [&](const SCEV *S) { 2276 return SE->isKnownNonNegative(S); 2277 }; 2278 2279 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2280 Flags = 2281 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2282 2283 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2284 2285 if (SignOrUnsignWrap != SignOrUnsignMask && 2286 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2287 isa<SCEVConstant>(Ops[0])) { 2288 2289 auto Opcode = [&] { 2290 switch (Type) { 2291 case scAddExpr: 2292 return Instruction::Add; 2293 case scMulExpr: 2294 return Instruction::Mul; 2295 default: 2296 llvm_unreachable("Unexpected SCEV op."); 2297 } 2298 }(); 2299 2300 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2301 2302 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2303 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2304 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2305 Opcode, C, OBO::NoSignedWrap); 2306 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2307 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2308 } 2309 2310 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2311 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2312 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2313 Opcode, C, OBO::NoUnsignedWrap); 2314 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2315 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2316 } 2317 } 2318 2319 return Flags; 2320 } 2321 2322 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2323 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2324 } 2325 2326 /// Get a canonical add expression, or something simpler if possible. 2327 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2328 SCEV::NoWrapFlags Flags, 2329 unsigned Depth) { 2330 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2331 "only nuw or nsw allowed"); 2332 assert(!Ops.empty() && "Cannot get empty add!"); 2333 if (Ops.size() == 1) return Ops[0]; 2334 #ifndef NDEBUG 2335 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2336 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2337 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2338 "SCEVAddExpr operand types don't match!"); 2339 #endif 2340 2341 // Sort by complexity, this groups all similar expression types together. 2342 GroupByComplexity(Ops, &LI, DT); 2343 2344 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2345 2346 // If there are any constants, fold them together. 2347 unsigned Idx = 0; 2348 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2349 ++Idx; 2350 assert(Idx < Ops.size()); 2351 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2352 // We found two constants, fold them together! 2353 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2354 if (Ops.size() == 2) return Ops[0]; 2355 Ops.erase(Ops.begin()+1); // Erase the folded element 2356 LHSC = cast<SCEVConstant>(Ops[0]); 2357 } 2358 2359 // If we are left with a constant zero being added, strip it off. 2360 if (LHSC->getValue()->isZero()) { 2361 Ops.erase(Ops.begin()); 2362 --Idx; 2363 } 2364 2365 if (Ops.size() == 1) return Ops[0]; 2366 } 2367 2368 // Limit recursion calls depth. 2369 if (Depth > MaxArithDepth) 2370 return getOrCreateAddExpr(Ops, Flags); 2371 2372 // Okay, check to see if the same value occurs in the operand list more than 2373 // once. If so, merge them together into an multiply expression. Since we 2374 // sorted the list, these values are required to be adjacent. 2375 Type *Ty = Ops[0]->getType(); 2376 bool FoundMatch = false; 2377 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2378 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2379 // Scan ahead to count how many equal operands there are. 2380 unsigned Count = 2; 2381 while (i+Count != e && Ops[i+Count] == Ops[i]) 2382 ++Count; 2383 // Merge the values into a multiply. 2384 const SCEV *Scale = getConstant(Ty, Count); 2385 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2386 if (Ops.size() == Count) 2387 return Mul; 2388 Ops[i] = Mul; 2389 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2390 --i; e -= Count - 1; 2391 FoundMatch = true; 2392 } 2393 if (FoundMatch) 2394 return getAddExpr(Ops, Flags, Depth + 1); 2395 2396 // Check for truncates. If all the operands are truncated from the same 2397 // type, see if factoring out the truncate would permit the result to be 2398 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2399 // if the contents of the resulting outer trunc fold to something simple. 2400 auto FindTruncSrcType = [&]() -> Type * { 2401 // We're ultimately looking to fold an addrec of truncs and muls of only 2402 // constants and truncs, so if we find any other types of SCEV 2403 // as operands of the addrec then we bail and return nullptr here. 2404 // Otherwise, we return the type of the operand of a trunc that we find. 2405 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2406 return T->getOperand()->getType(); 2407 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2408 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2409 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2410 return T->getOperand()->getType(); 2411 } 2412 return nullptr; 2413 }; 2414 if (auto *SrcType = FindTruncSrcType()) { 2415 SmallVector<const SCEV *, 8> LargeOps; 2416 bool Ok = true; 2417 // Check all the operands to see if they can be represented in the 2418 // source type of the truncate. 2419 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2420 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2421 if (T->getOperand()->getType() != SrcType) { 2422 Ok = false; 2423 break; 2424 } 2425 LargeOps.push_back(T->getOperand()); 2426 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2427 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2428 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2429 SmallVector<const SCEV *, 8> LargeMulOps; 2430 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2431 if (const SCEVTruncateExpr *T = 2432 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2433 if (T->getOperand()->getType() != SrcType) { 2434 Ok = false; 2435 break; 2436 } 2437 LargeMulOps.push_back(T->getOperand()); 2438 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2439 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2440 } else { 2441 Ok = false; 2442 break; 2443 } 2444 } 2445 if (Ok) 2446 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2447 } else { 2448 Ok = false; 2449 break; 2450 } 2451 } 2452 if (Ok) { 2453 // Evaluate the expression in the larger type. 2454 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2455 // If it folds to something simple, use it. Otherwise, don't. 2456 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2457 return getTruncateExpr(Fold, Ty); 2458 } 2459 } 2460 2461 // Skip past any other cast SCEVs. 2462 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2463 ++Idx; 2464 2465 // If there are add operands they would be next. 2466 if (Idx < Ops.size()) { 2467 bool DeletedAdd = false; 2468 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2469 if (Ops.size() > AddOpsInlineThreshold || 2470 Add->getNumOperands() > AddOpsInlineThreshold) 2471 break; 2472 // If we have an add, expand the add operands onto the end of the operands 2473 // list. 2474 Ops.erase(Ops.begin()+Idx); 2475 Ops.append(Add->op_begin(), Add->op_end()); 2476 DeletedAdd = true; 2477 } 2478 2479 // If we deleted at least one add, we added operands to the end of the list, 2480 // and they are not necessarily sorted. Recurse to resort and resimplify 2481 // any operands we just acquired. 2482 if (DeletedAdd) 2483 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2484 } 2485 2486 // Skip over the add expression until we get to a multiply. 2487 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2488 ++Idx; 2489 2490 // Check to see if there are any folding opportunities present with 2491 // operands multiplied by constant values. 2492 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2493 uint64_t BitWidth = getTypeSizeInBits(Ty); 2494 DenseMap<const SCEV *, APInt> M; 2495 SmallVector<const SCEV *, 8> NewOps; 2496 APInt AccumulatedConstant(BitWidth, 0); 2497 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2498 Ops.data(), Ops.size(), 2499 APInt(BitWidth, 1), *this)) { 2500 struct APIntCompare { 2501 bool operator()(const APInt &LHS, const APInt &RHS) const { 2502 return LHS.ult(RHS); 2503 } 2504 }; 2505 2506 // Some interesting folding opportunity is present, so its worthwhile to 2507 // re-generate the operands list. Group the operands by constant scale, 2508 // to avoid multiplying by the same constant scale multiple times. 2509 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2510 for (const SCEV *NewOp : NewOps) 2511 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2512 // Re-generate the operands list. 2513 Ops.clear(); 2514 if (AccumulatedConstant != 0) 2515 Ops.push_back(getConstant(AccumulatedConstant)); 2516 for (auto &MulOp : MulOpLists) 2517 if (MulOp.first != 0) 2518 Ops.push_back(getMulExpr( 2519 getConstant(MulOp.first), 2520 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2521 SCEV::FlagAnyWrap, Depth + 1)); 2522 if (Ops.empty()) 2523 return getZero(Ty); 2524 if (Ops.size() == 1) 2525 return Ops[0]; 2526 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2527 } 2528 } 2529 2530 // If we are adding something to a multiply expression, make sure the 2531 // something is not already an operand of the multiply. If so, merge it into 2532 // the multiply. 2533 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2534 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2535 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2536 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2537 if (isa<SCEVConstant>(MulOpSCEV)) 2538 continue; 2539 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2540 if (MulOpSCEV == Ops[AddOp]) { 2541 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2542 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2543 if (Mul->getNumOperands() != 2) { 2544 // If the multiply has more than two operands, we must get the 2545 // Y*Z term. 2546 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2547 Mul->op_begin()+MulOp); 2548 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2549 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2550 } 2551 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2552 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2553 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2554 SCEV::FlagAnyWrap, Depth + 1); 2555 if (Ops.size() == 2) return OuterMul; 2556 if (AddOp < Idx) { 2557 Ops.erase(Ops.begin()+AddOp); 2558 Ops.erase(Ops.begin()+Idx-1); 2559 } else { 2560 Ops.erase(Ops.begin()+Idx); 2561 Ops.erase(Ops.begin()+AddOp-1); 2562 } 2563 Ops.push_back(OuterMul); 2564 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2565 } 2566 2567 // Check this multiply against other multiplies being added together. 2568 for (unsigned OtherMulIdx = Idx+1; 2569 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2570 ++OtherMulIdx) { 2571 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2572 // If MulOp occurs in OtherMul, we can fold the two multiplies 2573 // together. 2574 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2575 OMulOp != e; ++OMulOp) 2576 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2577 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2578 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2579 if (Mul->getNumOperands() != 2) { 2580 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2581 Mul->op_begin()+MulOp); 2582 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2583 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2584 } 2585 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2586 if (OtherMul->getNumOperands() != 2) { 2587 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2588 OtherMul->op_begin()+OMulOp); 2589 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2590 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2591 } 2592 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2593 const SCEV *InnerMulSum = 2594 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2595 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2596 SCEV::FlagAnyWrap, Depth + 1); 2597 if (Ops.size() == 2) return OuterMul; 2598 Ops.erase(Ops.begin()+Idx); 2599 Ops.erase(Ops.begin()+OtherMulIdx-1); 2600 Ops.push_back(OuterMul); 2601 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2602 } 2603 } 2604 } 2605 } 2606 2607 // If there are any add recurrences in the operands list, see if any other 2608 // added values are loop invariant. If so, we can fold them into the 2609 // recurrence. 2610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2611 ++Idx; 2612 2613 // Scan over all recurrences, trying to fold loop invariants into them. 2614 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2615 // Scan all of the other operands to this add and add them to the vector if 2616 // they are loop invariant w.r.t. the recurrence. 2617 SmallVector<const SCEV *, 8> LIOps; 2618 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2619 const Loop *AddRecLoop = AddRec->getLoop(); 2620 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2621 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2622 LIOps.push_back(Ops[i]); 2623 Ops.erase(Ops.begin()+i); 2624 --i; --e; 2625 } 2626 2627 // If we found some loop invariants, fold them into the recurrence. 2628 if (!LIOps.empty()) { 2629 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2630 LIOps.push_back(AddRec->getStart()); 2631 2632 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2633 AddRec->op_end()); 2634 // This follows from the fact that the no-wrap flags on the outer add 2635 // expression are applicable on the 0th iteration, when the add recurrence 2636 // will be equal to its start value. 2637 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2638 2639 // Build the new addrec. Propagate the NUW and NSW flags if both the 2640 // outer add and the inner addrec are guaranteed to have no overflow. 2641 // Always propagate NW. 2642 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2643 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2644 2645 // If all of the other operands were loop invariant, we are done. 2646 if (Ops.size() == 1) return NewRec; 2647 2648 // Otherwise, add the folded AddRec by the non-invariant parts. 2649 for (unsigned i = 0;; ++i) 2650 if (Ops[i] == AddRec) { 2651 Ops[i] = NewRec; 2652 break; 2653 } 2654 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2655 } 2656 2657 // Okay, if there weren't any loop invariants to be folded, check to see if 2658 // there are multiple AddRec's with the same loop induction variable being 2659 // added together. If so, we can fold them. 2660 for (unsigned OtherIdx = Idx+1; 2661 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2662 ++OtherIdx) { 2663 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2664 // so that the 1st found AddRecExpr is dominated by all others. 2665 assert(DT.dominates( 2666 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2667 AddRec->getLoop()->getHeader()) && 2668 "AddRecExprs are not sorted in reverse dominance order?"); 2669 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2670 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2671 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2672 AddRec->op_end()); 2673 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2674 ++OtherIdx) { 2675 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2676 if (OtherAddRec->getLoop() == AddRecLoop) { 2677 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2678 i != e; ++i) { 2679 if (i >= AddRecOps.size()) { 2680 AddRecOps.append(OtherAddRec->op_begin()+i, 2681 OtherAddRec->op_end()); 2682 break; 2683 } 2684 SmallVector<const SCEV *, 2> TwoOps = { 2685 AddRecOps[i], OtherAddRec->getOperand(i)}; 2686 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2687 } 2688 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2689 } 2690 } 2691 // Step size has changed, so we cannot guarantee no self-wraparound. 2692 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2693 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2694 } 2695 } 2696 2697 // Otherwise couldn't fold anything into this recurrence. Move onto the 2698 // next one. 2699 } 2700 2701 // Okay, it looks like we really DO need an add expr. Check to see if we 2702 // already have one, otherwise create a new one. 2703 return getOrCreateAddExpr(Ops, Flags); 2704 } 2705 2706 const SCEV * 2707 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2708 SCEV::NoWrapFlags Flags) { 2709 FoldingSetNodeID ID; 2710 ID.AddInteger(scAddExpr); 2711 for (const SCEV *Op : Ops) 2712 ID.AddPointer(Op); 2713 void *IP = nullptr; 2714 SCEVAddExpr *S = 2715 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2716 if (!S) { 2717 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2718 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2719 S = new (SCEVAllocator) 2720 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2721 UniqueSCEVs.InsertNode(S, IP); 2722 addToLoopUseLists(S); 2723 } 2724 S->setNoWrapFlags(Flags); 2725 return S; 2726 } 2727 2728 const SCEV * 2729 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2730 SCEV::NoWrapFlags Flags) { 2731 FoldingSetNodeID ID; 2732 ID.AddInteger(scMulExpr); 2733 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2734 ID.AddPointer(Ops[i]); 2735 void *IP = nullptr; 2736 SCEVMulExpr *S = 2737 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2738 if (!S) { 2739 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2740 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2741 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2742 O, Ops.size()); 2743 UniqueSCEVs.InsertNode(S, IP); 2744 addToLoopUseLists(S); 2745 } 2746 S->setNoWrapFlags(Flags); 2747 return S; 2748 } 2749 2750 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2751 uint64_t k = i*j; 2752 if (j > 1 && k / j != i) Overflow = true; 2753 return k; 2754 } 2755 2756 /// Compute the result of "n choose k", the binomial coefficient. If an 2757 /// intermediate computation overflows, Overflow will be set and the return will 2758 /// be garbage. Overflow is not cleared on absence of overflow. 2759 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2760 // We use the multiplicative formula: 2761 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2762 // At each iteration, we take the n-th term of the numeral and divide by the 2763 // (k-n)th term of the denominator. This division will always produce an 2764 // integral result, and helps reduce the chance of overflow in the 2765 // intermediate computations. However, we can still overflow even when the 2766 // final result would fit. 2767 2768 if (n == 0 || n == k) return 1; 2769 if (k > n) return 0; 2770 2771 if (k > n/2) 2772 k = n-k; 2773 2774 uint64_t r = 1; 2775 for (uint64_t i = 1; i <= k; ++i) { 2776 r = umul_ov(r, n-(i-1), Overflow); 2777 r /= i; 2778 } 2779 return r; 2780 } 2781 2782 /// Determine if any of the operands in this SCEV are a constant or if 2783 /// any of the add or multiply expressions in this SCEV contain a constant. 2784 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2785 struct FindConstantInAddMulChain { 2786 bool FoundConstant = false; 2787 2788 bool follow(const SCEV *S) { 2789 FoundConstant |= isa<SCEVConstant>(S); 2790 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2791 } 2792 2793 bool isDone() const { 2794 return FoundConstant; 2795 } 2796 }; 2797 2798 FindConstantInAddMulChain F; 2799 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2800 ST.visitAll(StartExpr); 2801 return F.FoundConstant; 2802 } 2803 2804 /// Get a canonical multiply expression, or something simpler if possible. 2805 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2806 SCEV::NoWrapFlags Flags, 2807 unsigned Depth) { 2808 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2809 "only nuw or nsw allowed"); 2810 assert(!Ops.empty() && "Cannot get empty mul!"); 2811 if (Ops.size() == 1) return Ops[0]; 2812 #ifndef NDEBUG 2813 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2814 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2815 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2816 "SCEVMulExpr operand types don't match!"); 2817 #endif 2818 2819 // Sort by complexity, this groups all similar expression types together. 2820 GroupByComplexity(Ops, &LI, DT); 2821 2822 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2823 2824 // Limit recursion calls depth. 2825 if (Depth > MaxArithDepth) 2826 return getOrCreateMulExpr(Ops, Flags); 2827 2828 // If there are any constants, fold them together. 2829 unsigned Idx = 0; 2830 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2831 2832 if (Ops.size() == 2) 2833 // C1*(C2+V) -> C1*C2 + C1*V 2834 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2835 // If any of Add's ops are Adds or Muls with a constant, apply this 2836 // transformation as well. 2837 // 2838 // TODO: There are some cases where this transformation is not 2839 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2840 // this transformation should be narrowed down. 2841 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2842 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2843 SCEV::FlagAnyWrap, Depth + 1), 2844 getMulExpr(LHSC, Add->getOperand(1), 2845 SCEV::FlagAnyWrap, Depth + 1), 2846 SCEV::FlagAnyWrap, Depth + 1); 2847 2848 ++Idx; 2849 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2850 // We found two constants, fold them together! 2851 ConstantInt *Fold = 2852 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2853 Ops[0] = getConstant(Fold); 2854 Ops.erase(Ops.begin()+1); // Erase the folded element 2855 if (Ops.size() == 1) return Ops[0]; 2856 LHSC = cast<SCEVConstant>(Ops[0]); 2857 } 2858 2859 // If we are left with a constant one being multiplied, strip it off. 2860 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2861 Ops.erase(Ops.begin()); 2862 --Idx; 2863 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2864 // If we have a multiply of zero, it will always be zero. 2865 return Ops[0]; 2866 } else if (Ops[0]->isAllOnesValue()) { 2867 // If we have a mul by -1 of an add, try distributing the -1 among the 2868 // add operands. 2869 if (Ops.size() == 2) { 2870 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2871 SmallVector<const SCEV *, 4> NewOps; 2872 bool AnyFolded = false; 2873 for (const SCEV *AddOp : Add->operands()) { 2874 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2875 Depth + 1); 2876 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2877 NewOps.push_back(Mul); 2878 } 2879 if (AnyFolded) 2880 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2881 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2882 // Negation preserves a recurrence's no self-wrap property. 2883 SmallVector<const SCEV *, 4> Operands; 2884 for (const SCEV *AddRecOp : AddRec->operands()) 2885 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2886 Depth + 1)); 2887 2888 return getAddRecExpr(Operands, AddRec->getLoop(), 2889 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2890 } 2891 } 2892 } 2893 2894 if (Ops.size() == 1) 2895 return Ops[0]; 2896 } 2897 2898 // Skip over the add expression until we get to a multiply. 2899 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2900 ++Idx; 2901 2902 // If there are mul operands inline them all into this expression. 2903 if (Idx < Ops.size()) { 2904 bool DeletedMul = false; 2905 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2906 if (Ops.size() > MulOpsInlineThreshold) 2907 break; 2908 // If we have an mul, expand the mul operands onto the end of the 2909 // operands list. 2910 Ops.erase(Ops.begin()+Idx); 2911 Ops.append(Mul->op_begin(), Mul->op_end()); 2912 DeletedMul = true; 2913 } 2914 2915 // If we deleted at least one mul, we added operands to the end of the 2916 // list, and they are not necessarily sorted. Recurse to resort and 2917 // resimplify any operands we just acquired. 2918 if (DeletedMul) 2919 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2920 } 2921 2922 // If there are any add recurrences in the operands list, see if any other 2923 // added values are loop invariant. If so, we can fold them into the 2924 // recurrence. 2925 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2926 ++Idx; 2927 2928 // Scan over all recurrences, trying to fold loop invariants into them. 2929 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2930 // Scan all of the other operands to this mul and add them to the vector 2931 // if they are loop invariant w.r.t. the recurrence. 2932 SmallVector<const SCEV *, 8> LIOps; 2933 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2934 const Loop *AddRecLoop = AddRec->getLoop(); 2935 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2936 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2937 LIOps.push_back(Ops[i]); 2938 Ops.erase(Ops.begin()+i); 2939 --i; --e; 2940 } 2941 2942 // If we found some loop invariants, fold them into the recurrence. 2943 if (!LIOps.empty()) { 2944 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2945 SmallVector<const SCEV *, 4> NewOps; 2946 NewOps.reserve(AddRec->getNumOperands()); 2947 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2948 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2949 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2950 SCEV::FlagAnyWrap, Depth + 1)); 2951 2952 // Build the new addrec. Propagate the NUW and NSW flags if both the 2953 // outer mul and the inner addrec are guaranteed to have no overflow. 2954 // 2955 // No self-wrap cannot be guaranteed after changing the step size, but 2956 // will be inferred if either NUW or NSW is true. 2957 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2958 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2959 2960 // If all of the other operands were loop invariant, we are done. 2961 if (Ops.size() == 1) return NewRec; 2962 2963 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2964 for (unsigned i = 0;; ++i) 2965 if (Ops[i] == AddRec) { 2966 Ops[i] = NewRec; 2967 break; 2968 } 2969 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2970 } 2971 2972 // Okay, if there weren't any loop invariants to be folded, check to see 2973 // if there are multiple AddRec's with the same loop induction variable 2974 // being multiplied together. If so, we can fold them. 2975 2976 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2977 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2978 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2979 // ]]],+,...up to x=2n}. 2980 // Note that the arguments to choose() are always integers with values 2981 // known at compile time, never SCEV objects. 2982 // 2983 // The implementation avoids pointless extra computations when the two 2984 // addrec's are of different length (mathematically, it's equivalent to 2985 // an infinite stream of zeros on the right). 2986 bool OpsModified = false; 2987 for (unsigned OtherIdx = Idx+1; 2988 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2989 ++OtherIdx) { 2990 const SCEVAddRecExpr *OtherAddRec = 2991 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2992 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2993 continue; 2994 2995 // Limit max number of arguments to avoid creation of unreasonably big 2996 // SCEVAddRecs with very complex operands. 2997 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2998 MaxAddRecSize) 2999 continue; 3000 3001 bool Overflow = false; 3002 Type *Ty = AddRec->getType(); 3003 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3004 SmallVector<const SCEV*, 7> AddRecOps; 3005 for (int x = 0, xe = AddRec->getNumOperands() + 3006 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3007 const SCEV *Term = getZero(Ty); 3008 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3009 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3010 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3011 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3012 z < ze && !Overflow; ++z) { 3013 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3014 uint64_t Coeff; 3015 if (LargerThan64Bits) 3016 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3017 else 3018 Coeff = Coeff1*Coeff2; 3019 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3020 const SCEV *Term1 = AddRec->getOperand(y-z); 3021 const SCEV *Term2 = OtherAddRec->getOperand(z); 3022 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 3023 SCEV::FlagAnyWrap, Depth + 1), 3024 SCEV::FlagAnyWrap, Depth + 1); 3025 } 3026 } 3027 AddRecOps.push_back(Term); 3028 } 3029 if (!Overflow) { 3030 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 3031 SCEV::FlagAnyWrap); 3032 if (Ops.size() == 2) return NewAddRec; 3033 Ops[Idx] = NewAddRec; 3034 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3035 OpsModified = true; 3036 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3037 if (!AddRec) 3038 break; 3039 } 3040 } 3041 if (OpsModified) 3042 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3043 3044 // Otherwise couldn't fold anything into this recurrence. Move onto the 3045 // next one. 3046 } 3047 3048 // Okay, it looks like we really DO need an mul expr. Check to see if we 3049 // already have one, otherwise create a new one. 3050 return getOrCreateMulExpr(Ops, Flags); 3051 } 3052 3053 /// Represents an unsigned remainder expression based on unsigned division. 3054 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3055 const SCEV *RHS) { 3056 assert(getEffectiveSCEVType(LHS->getType()) == 3057 getEffectiveSCEVType(RHS->getType()) && 3058 "SCEVURemExpr operand types don't match!"); 3059 3060 // Short-circuit easy cases 3061 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3062 // If constant is one, the result is trivial 3063 if (RHSC->getValue()->isOne()) 3064 return getZero(LHS->getType()); // X urem 1 --> 0 3065 3066 // If constant is a power of two, fold into a zext(trunc(LHS)). 3067 if (RHSC->getAPInt().isPowerOf2()) { 3068 Type *FullTy = LHS->getType(); 3069 Type *TruncTy = 3070 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3071 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3072 } 3073 } 3074 3075 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3076 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3077 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3078 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3079 } 3080 3081 /// Get a canonical unsigned division expression, or something simpler if 3082 /// possible. 3083 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3084 const SCEV *RHS) { 3085 assert(getEffectiveSCEVType(LHS->getType()) == 3086 getEffectiveSCEVType(RHS->getType()) && 3087 "SCEVUDivExpr operand types don't match!"); 3088 3089 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3090 if (RHSC->getValue()->isOne()) 3091 return LHS; // X udiv 1 --> x 3092 // If the denominator is zero, the result of the udiv is undefined. Don't 3093 // try to analyze it, because the resolution chosen here may differ from 3094 // the resolution chosen in other parts of the compiler. 3095 if (!RHSC->getValue()->isZero()) { 3096 // Determine if the division can be folded into the operands of 3097 // its operands. 3098 // TODO: Generalize this to non-constants by using known-bits information. 3099 Type *Ty = LHS->getType(); 3100 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3101 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3102 // For non-power-of-two values, effectively round the value up to the 3103 // nearest power of two. 3104 if (!RHSC->getAPInt().isPowerOf2()) 3105 ++MaxShiftAmt; 3106 IntegerType *ExtTy = 3107 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3108 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3109 if (const SCEVConstant *Step = 3110 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3111 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3112 const APInt &StepInt = Step->getAPInt(); 3113 const APInt &DivInt = RHSC->getAPInt(); 3114 if (!StepInt.urem(DivInt) && 3115 getZeroExtendExpr(AR, ExtTy) == 3116 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3117 getZeroExtendExpr(Step, ExtTy), 3118 AR->getLoop(), SCEV::FlagAnyWrap)) { 3119 SmallVector<const SCEV *, 4> Operands; 3120 for (const SCEV *Op : AR->operands()) 3121 Operands.push_back(getUDivExpr(Op, RHS)); 3122 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3123 } 3124 /// Get a canonical UDivExpr for a recurrence. 3125 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3126 // We can currently only fold X%N if X is constant. 3127 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3128 if (StartC && !DivInt.urem(StepInt) && 3129 getZeroExtendExpr(AR, ExtTy) == 3130 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3131 getZeroExtendExpr(Step, ExtTy), 3132 AR->getLoop(), SCEV::FlagAnyWrap)) { 3133 const APInt &StartInt = StartC->getAPInt(); 3134 const APInt &StartRem = StartInt.urem(StepInt); 3135 if (StartRem != 0) 3136 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3137 AR->getLoop(), SCEV::FlagNW); 3138 } 3139 } 3140 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3141 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3142 SmallVector<const SCEV *, 4> Operands; 3143 for (const SCEV *Op : M->operands()) 3144 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3145 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3146 // Find an operand that's safely divisible. 3147 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3148 const SCEV *Op = M->getOperand(i); 3149 const SCEV *Div = getUDivExpr(Op, RHSC); 3150 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3151 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3152 M->op_end()); 3153 Operands[i] = Div; 3154 return getMulExpr(Operands); 3155 } 3156 } 3157 } 3158 3159 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3160 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3161 if (auto *DivisorConstant = 3162 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3163 bool Overflow = false; 3164 APInt NewRHS = 3165 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3166 if (Overflow) { 3167 return getConstant(RHSC->getType(), 0, false); 3168 } 3169 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3170 } 3171 } 3172 3173 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3174 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3175 SmallVector<const SCEV *, 4> Operands; 3176 for (const SCEV *Op : A->operands()) 3177 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3178 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3179 Operands.clear(); 3180 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3181 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3182 if (isa<SCEVUDivExpr>(Op) || 3183 getMulExpr(Op, RHS) != A->getOperand(i)) 3184 break; 3185 Operands.push_back(Op); 3186 } 3187 if (Operands.size() == A->getNumOperands()) 3188 return getAddExpr(Operands); 3189 } 3190 } 3191 3192 // Fold if both operands are constant. 3193 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3194 Constant *LHSCV = LHSC->getValue(); 3195 Constant *RHSCV = RHSC->getValue(); 3196 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3197 RHSCV))); 3198 } 3199 } 3200 } 3201 3202 FoldingSetNodeID ID; 3203 ID.AddInteger(scUDivExpr); 3204 ID.AddPointer(LHS); 3205 ID.AddPointer(RHS); 3206 void *IP = nullptr; 3207 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3208 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3209 LHS, RHS); 3210 UniqueSCEVs.InsertNode(S, IP); 3211 addToLoopUseLists(S); 3212 return S; 3213 } 3214 3215 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3216 APInt A = C1->getAPInt().abs(); 3217 APInt B = C2->getAPInt().abs(); 3218 uint32_t ABW = A.getBitWidth(); 3219 uint32_t BBW = B.getBitWidth(); 3220 3221 if (ABW > BBW) 3222 B = B.zext(ABW); 3223 else if (ABW < BBW) 3224 A = A.zext(BBW); 3225 3226 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3227 } 3228 3229 /// Get a canonical unsigned division expression, or something simpler if 3230 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3231 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3232 /// it's not exact because the udiv may be clearing bits. 3233 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3234 const SCEV *RHS) { 3235 // TODO: we could try to find factors in all sorts of things, but for now we 3236 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3237 // end of this file for inspiration. 3238 3239 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3240 if (!Mul || !Mul->hasNoUnsignedWrap()) 3241 return getUDivExpr(LHS, RHS); 3242 3243 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3244 // If the mulexpr multiplies by a constant, then that constant must be the 3245 // first element of the mulexpr. 3246 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3247 if (LHSCst == RHSCst) { 3248 SmallVector<const SCEV *, 2> Operands; 3249 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3250 return getMulExpr(Operands); 3251 } 3252 3253 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3254 // that there's a factor provided by one of the other terms. We need to 3255 // check. 3256 APInt Factor = gcd(LHSCst, RHSCst); 3257 if (!Factor.isIntN(1)) { 3258 LHSCst = 3259 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3260 RHSCst = 3261 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3262 SmallVector<const SCEV *, 2> Operands; 3263 Operands.push_back(LHSCst); 3264 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3265 LHS = getMulExpr(Operands); 3266 RHS = RHSCst; 3267 Mul = dyn_cast<SCEVMulExpr>(LHS); 3268 if (!Mul) 3269 return getUDivExactExpr(LHS, RHS); 3270 } 3271 } 3272 } 3273 3274 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3275 if (Mul->getOperand(i) == RHS) { 3276 SmallVector<const SCEV *, 2> Operands; 3277 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3278 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3279 return getMulExpr(Operands); 3280 } 3281 } 3282 3283 return getUDivExpr(LHS, RHS); 3284 } 3285 3286 /// Get an add recurrence expression for the specified loop. Simplify the 3287 /// expression as much as possible. 3288 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3289 const Loop *L, 3290 SCEV::NoWrapFlags Flags) { 3291 SmallVector<const SCEV *, 4> Operands; 3292 Operands.push_back(Start); 3293 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3294 if (StepChrec->getLoop() == L) { 3295 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3296 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3297 } 3298 3299 Operands.push_back(Step); 3300 return getAddRecExpr(Operands, L, Flags); 3301 } 3302 3303 /// Get an add recurrence expression for the specified loop. Simplify the 3304 /// expression as much as possible. 3305 const SCEV * 3306 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3307 const Loop *L, SCEV::NoWrapFlags Flags) { 3308 if (Operands.size() == 1) return Operands[0]; 3309 #ifndef NDEBUG 3310 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3311 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3312 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3313 "SCEVAddRecExpr operand types don't match!"); 3314 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3315 assert(isLoopInvariant(Operands[i], L) && 3316 "SCEVAddRecExpr operand is not loop-invariant!"); 3317 #endif 3318 3319 if (Operands.back()->isZero()) { 3320 Operands.pop_back(); 3321 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3322 } 3323 3324 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3325 // use that information to infer NUW and NSW flags. However, computing a 3326 // BE count requires calling getAddRecExpr, so we may not yet have a 3327 // meaningful BE count at this point (and if we don't, we'd be stuck 3328 // with a SCEVCouldNotCompute as the cached BE count). 3329 3330 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3331 3332 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3333 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3334 const Loop *NestedLoop = NestedAR->getLoop(); 3335 if (L->contains(NestedLoop) 3336 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3337 : (!NestedLoop->contains(L) && 3338 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3339 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3340 NestedAR->op_end()); 3341 Operands[0] = NestedAR->getStart(); 3342 // AddRecs require their operands be loop-invariant with respect to their 3343 // loops. Don't perform this transformation if it would break this 3344 // requirement. 3345 bool AllInvariant = all_of( 3346 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3347 3348 if (AllInvariant) { 3349 // Create a recurrence for the outer loop with the same step size. 3350 // 3351 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3352 // inner recurrence has the same property. 3353 SCEV::NoWrapFlags OuterFlags = 3354 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3355 3356 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3357 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3358 return isLoopInvariant(Op, NestedLoop); 3359 }); 3360 3361 if (AllInvariant) { 3362 // Ok, both add recurrences are valid after the transformation. 3363 // 3364 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3365 // the outer recurrence has the same property. 3366 SCEV::NoWrapFlags InnerFlags = 3367 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3368 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3369 } 3370 } 3371 // Reset Operands to its original state. 3372 Operands[0] = NestedAR; 3373 } 3374 } 3375 3376 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3377 // already have one, otherwise create a new one. 3378 FoldingSetNodeID ID; 3379 ID.AddInteger(scAddRecExpr); 3380 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3381 ID.AddPointer(Operands[i]); 3382 ID.AddPointer(L); 3383 void *IP = nullptr; 3384 SCEVAddRecExpr *S = 3385 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3386 if (!S) { 3387 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3388 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3389 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3390 O, Operands.size(), L); 3391 UniqueSCEVs.InsertNode(S, IP); 3392 addToLoopUseLists(S); 3393 } 3394 S->setNoWrapFlags(Flags); 3395 return S; 3396 } 3397 3398 const SCEV * 3399 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3400 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3401 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3402 // getSCEV(Base)->getType() has the same address space as Base->getType() 3403 // because SCEV::getType() preserves the address space. 3404 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3405 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3406 // instruction to its SCEV, because the Instruction may be guarded by control 3407 // flow and the no-overflow bits may not be valid for the expression in any 3408 // context. This can be fixed similarly to how these flags are handled for 3409 // adds. 3410 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3411 : SCEV::FlagAnyWrap; 3412 3413 const SCEV *TotalOffset = getZero(IntPtrTy); 3414 // The array size is unimportant. The first thing we do on CurTy is getting 3415 // its element type. 3416 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3417 for (const SCEV *IndexExpr : IndexExprs) { 3418 // Compute the (potentially symbolic) offset in bytes for this index. 3419 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3420 // For a struct, add the member offset. 3421 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3422 unsigned FieldNo = Index->getZExtValue(); 3423 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3424 3425 // Add the field offset to the running total offset. 3426 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3427 3428 // Update CurTy to the type of the field at Index. 3429 CurTy = STy->getTypeAtIndex(Index); 3430 } else { 3431 // Update CurTy to its element type. 3432 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3433 // For an array, add the element offset, explicitly scaled. 3434 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3435 // Getelementptr indices are signed. 3436 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3437 3438 // Multiply the index by the element size to compute the element offset. 3439 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3440 3441 // Add the element offset to the running total offset. 3442 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3443 } 3444 } 3445 3446 // Add the total offset from all the GEP indices to the base. 3447 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3448 } 3449 3450 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3451 const SCEV *RHS) { 3452 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3453 return getSMaxExpr(Ops); 3454 } 3455 3456 const SCEV * 3457 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3458 assert(!Ops.empty() && "Cannot get empty smax!"); 3459 if (Ops.size() == 1) return Ops[0]; 3460 #ifndef NDEBUG 3461 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3462 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3463 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3464 "SCEVSMaxExpr operand types don't match!"); 3465 #endif 3466 3467 // Sort by complexity, this groups all similar expression types together. 3468 GroupByComplexity(Ops, &LI, DT); 3469 3470 // If there are any constants, fold them together. 3471 unsigned Idx = 0; 3472 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3473 ++Idx; 3474 assert(Idx < Ops.size()); 3475 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3476 // We found two constants, fold them together! 3477 ConstantInt *Fold = ConstantInt::get( 3478 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3479 Ops[0] = getConstant(Fold); 3480 Ops.erase(Ops.begin()+1); // Erase the folded element 3481 if (Ops.size() == 1) return Ops[0]; 3482 LHSC = cast<SCEVConstant>(Ops[0]); 3483 } 3484 3485 // If we are left with a constant minimum-int, strip it off. 3486 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3487 Ops.erase(Ops.begin()); 3488 --Idx; 3489 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3490 // If we have an smax with a constant maximum-int, it will always be 3491 // maximum-int. 3492 return Ops[0]; 3493 } 3494 3495 if (Ops.size() == 1) return Ops[0]; 3496 } 3497 3498 // Find the first SMax 3499 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3500 ++Idx; 3501 3502 // Check to see if one of the operands is an SMax. If so, expand its operands 3503 // onto our operand list, and recurse to simplify. 3504 if (Idx < Ops.size()) { 3505 bool DeletedSMax = false; 3506 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3507 Ops.erase(Ops.begin()+Idx); 3508 Ops.append(SMax->op_begin(), SMax->op_end()); 3509 DeletedSMax = true; 3510 } 3511 3512 if (DeletedSMax) 3513 return getSMaxExpr(Ops); 3514 } 3515 3516 // Okay, check to see if the same value occurs in the operand list twice. If 3517 // so, delete one. Since we sorted the list, these values are required to 3518 // be adjacent. 3519 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3520 // X smax Y smax Y --> X smax Y 3521 // X smax Y --> X, if X is always greater than Y 3522 if (Ops[i] == Ops[i+1] || 3523 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3524 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3525 --i; --e; 3526 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3527 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3528 --i; --e; 3529 } 3530 3531 if (Ops.size() == 1) return Ops[0]; 3532 3533 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3534 3535 // Okay, it looks like we really DO need an smax expr. Check to see if we 3536 // already have one, otherwise create a new one. 3537 FoldingSetNodeID ID; 3538 ID.AddInteger(scSMaxExpr); 3539 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3540 ID.AddPointer(Ops[i]); 3541 void *IP = nullptr; 3542 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3543 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3544 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3545 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3546 O, Ops.size()); 3547 UniqueSCEVs.InsertNode(S, IP); 3548 addToLoopUseLists(S); 3549 return S; 3550 } 3551 3552 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3553 const SCEV *RHS) { 3554 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3555 return getUMaxExpr(Ops); 3556 } 3557 3558 const SCEV * 3559 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3560 assert(!Ops.empty() && "Cannot get empty umax!"); 3561 if (Ops.size() == 1) return Ops[0]; 3562 #ifndef NDEBUG 3563 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3564 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3565 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3566 "SCEVUMaxExpr operand types don't match!"); 3567 #endif 3568 3569 // Sort by complexity, this groups all similar expression types together. 3570 GroupByComplexity(Ops, &LI, DT); 3571 3572 // If there are any constants, fold them together. 3573 unsigned Idx = 0; 3574 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3575 ++Idx; 3576 assert(Idx < Ops.size()); 3577 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3578 // We found two constants, fold them together! 3579 ConstantInt *Fold = ConstantInt::get( 3580 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3581 Ops[0] = getConstant(Fold); 3582 Ops.erase(Ops.begin()+1); // Erase the folded element 3583 if (Ops.size() == 1) return Ops[0]; 3584 LHSC = cast<SCEVConstant>(Ops[0]); 3585 } 3586 3587 // If we are left with a constant minimum-int, strip it off. 3588 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3589 Ops.erase(Ops.begin()); 3590 --Idx; 3591 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3592 // If we have an umax with a constant maximum-int, it will always be 3593 // maximum-int. 3594 return Ops[0]; 3595 } 3596 3597 if (Ops.size() == 1) return Ops[0]; 3598 } 3599 3600 // Find the first UMax 3601 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3602 ++Idx; 3603 3604 // Check to see if one of the operands is a UMax. If so, expand its operands 3605 // onto our operand list, and recurse to simplify. 3606 if (Idx < Ops.size()) { 3607 bool DeletedUMax = false; 3608 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3609 Ops.erase(Ops.begin()+Idx); 3610 Ops.append(UMax->op_begin(), UMax->op_end()); 3611 DeletedUMax = true; 3612 } 3613 3614 if (DeletedUMax) 3615 return getUMaxExpr(Ops); 3616 } 3617 3618 // Okay, check to see if the same value occurs in the operand list twice. If 3619 // so, delete one. Since we sorted the list, these values are required to 3620 // be adjacent. 3621 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3622 // X umax Y umax Y --> X umax Y 3623 // X umax Y --> X, if X is always greater than Y 3624 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3625 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3626 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3627 --i; --e; 3628 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3629 Ops[i + 1])) { 3630 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3631 --i; --e; 3632 } 3633 3634 if (Ops.size() == 1) return Ops[0]; 3635 3636 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3637 3638 // Okay, it looks like we really DO need a umax expr. Check to see if we 3639 // already have one, otherwise create a new one. 3640 FoldingSetNodeID ID; 3641 ID.AddInteger(scUMaxExpr); 3642 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3643 ID.AddPointer(Ops[i]); 3644 void *IP = nullptr; 3645 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3646 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3647 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3648 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3649 O, Ops.size()); 3650 UniqueSCEVs.InsertNode(S, IP); 3651 addToLoopUseLists(S); 3652 return S; 3653 } 3654 3655 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3656 const SCEV *RHS) { 3657 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3658 return getSMinExpr(Ops); 3659 } 3660 3661 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3662 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3663 SmallVector<const SCEV *, 2> NotOps; 3664 for (auto *S : Ops) 3665 NotOps.push_back(getNotSCEV(S)); 3666 return getNotSCEV(getSMaxExpr(NotOps)); 3667 } 3668 3669 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3670 const SCEV *RHS) { 3671 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3672 return getUMinExpr(Ops); 3673 } 3674 3675 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3676 assert(!Ops.empty() && "At least one operand must be!"); 3677 // Trivial case. 3678 if (Ops.size() == 1) 3679 return Ops[0]; 3680 3681 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3682 SmallVector<const SCEV *, 2> NotOps; 3683 for (auto *S : Ops) 3684 NotOps.push_back(getNotSCEV(S)); 3685 return getNotSCEV(getUMaxExpr(NotOps)); 3686 } 3687 3688 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3689 // We can bypass creating a target-independent 3690 // constant expression and then folding it back into a ConstantInt. 3691 // This is just a compile-time optimization. 3692 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3693 } 3694 3695 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3696 StructType *STy, 3697 unsigned FieldNo) { 3698 // We can bypass creating a target-independent 3699 // constant expression and then folding it back into a ConstantInt. 3700 // This is just a compile-time optimization. 3701 return getConstant( 3702 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3703 } 3704 3705 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3706 // Don't attempt to do anything other than create a SCEVUnknown object 3707 // here. createSCEV only calls getUnknown after checking for all other 3708 // interesting possibilities, and any other code that calls getUnknown 3709 // is doing so in order to hide a value from SCEV canonicalization. 3710 3711 FoldingSetNodeID ID; 3712 ID.AddInteger(scUnknown); 3713 ID.AddPointer(V); 3714 void *IP = nullptr; 3715 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3716 assert(cast<SCEVUnknown>(S)->getValue() == V && 3717 "Stale SCEVUnknown in uniquing map!"); 3718 return S; 3719 } 3720 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3721 FirstUnknown); 3722 FirstUnknown = cast<SCEVUnknown>(S); 3723 UniqueSCEVs.InsertNode(S, IP); 3724 return S; 3725 } 3726 3727 //===----------------------------------------------------------------------===// 3728 // Basic SCEV Analysis and PHI Idiom Recognition Code 3729 // 3730 3731 /// Test if values of the given type are analyzable within the SCEV 3732 /// framework. This primarily includes integer types, and it can optionally 3733 /// include pointer types if the ScalarEvolution class has access to 3734 /// target-specific information. 3735 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3736 // Integers and pointers are always SCEVable. 3737 return Ty->isIntOrPtrTy(); 3738 } 3739 3740 /// Return the size in bits of the specified type, for which isSCEVable must 3741 /// return true. 3742 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3743 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3744 if (Ty->isPointerTy()) 3745 return getDataLayout().getIndexTypeSizeInBits(Ty); 3746 return getDataLayout().getTypeSizeInBits(Ty); 3747 } 3748 3749 /// Return a type with the same bitwidth as the given type and which represents 3750 /// how SCEV will treat the given type, for which isSCEVable must return 3751 /// true. For pointer types, this is the pointer-sized integer type. 3752 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3753 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3754 3755 if (Ty->isIntegerTy()) 3756 return Ty; 3757 3758 // The only other support type is pointer. 3759 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3760 return getDataLayout().getIntPtrType(Ty); 3761 } 3762 3763 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3764 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3765 } 3766 3767 const SCEV *ScalarEvolution::getCouldNotCompute() { 3768 return CouldNotCompute.get(); 3769 } 3770 3771 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3772 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3773 auto *SU = dyn_cast<SCEVUnknown>(S); 3774 return SU && SU->getValue() == nullptr; 3775 }); 3776 3777 return !ContainsNulls; 3778 } 3779 3780 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3781 HasRecMapType::iterator I = HasRecMap.find(S); 3782 if (I != HasRecMap.end()) 3783 return I->second; 3784 3785 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3786 HasRecMap.insert({S, FoundAddRec}); 3787 return FoundAddRec; 3788 } 3789 3790 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3791 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3792 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3793 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3794 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3795 if (!Add) 3796 return {S, nullptr}; 3797 3798 if (Add->getNumOperands() != 2) 3799 return {S, nullptr}; 3800 3801 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3802 if (!ConstOp) 3803 return {S, nullptr}; 3804 3805 return {Add->getOperand(1), ConstOp->getValue()}; 3806 } 3807 3808 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3809 /// by the value and offset from any ValueOffsetPair in the set. 3810 SetVector<ScalarEvolution::ValueOffsetPair> * 3811 ScalarEvolution::getSCEVValues(const SCEV *S) { 3812 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3813 if (SI == ExprValueMap.end()) 3814 return nullptr; 3815 #ifndef NDEBUG 3816 if (VerifySCEVMap) { 3817 // Check there is no dangling Value in the set returned. 3818 for (const auto &VE : SI->second) 3819 assert(ValueExprMap.count(VE.first)); 3820 } 3821 #endif 3822 return &SI->second; 3823 } 3824 3825 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3826 /// cannot be used separately. eraseValueFromMap should be used to remove 3827 /// V from ValueExprMap and ExprValueMap at the same time. 3828 void ScalarEvolution::eraseValueFromMap(Value *V) { 3829 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3830 if (I != ValueExprMap.end()) { 3831 const SCEV *S = I->second; 3832 // Remove {V, 0} from the set of ExprValueMap[S] 3833 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3834 SV->remove({V, nullptr}); 3835 3836 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3837 const SCEV *Stripped; 3838 ConstantInt *Offset; 3839 std::tie(Stripped, Offset) = splitAddExpr(S); 3840 if (Offset != nullptr) { 3841 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3842 SV->remove({V, Offset}); 3843 } 3844 ValueExprMap.erase(V); 3845 } 3846 } 3847 3848 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3849 /// TODO: In reality it is better to check the poison recursevely 3850 /// but this is better than nothing. 3851 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3852 if (auto *I = dyn_cast<Instruction>(V)) { 3853 if (isa<OverflowingBinaryOperator>(I)) { 3854 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3855 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3856 return true; 3857 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3858 return true; 3859 } 3860 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3861 return true; 3862 } 3863 return false; 3864 } 3865 3866 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3867 /// create a new one. 3868 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3869 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3870 3871 const SCEV *S = getExistingSCEV(V); 3872 if (S == nullptr) { 3873 S = createSCEV(V); 3874 // During PHI resolution, it is possible to create two SCEVs for the same 3875 // V, so it is needed to double check whether V->S is inserted into 3876 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3877 std::pair<ValueExprMapType::iterator, bool> Pair = 3878 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3879 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3880 ExprValueMap[S].insert({V, nullptr}); 3881 3882 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3883 // ExprValueMap. 3884 const SCEV *Stripped = S; 3885 ConstantInt *Offset = nullptr; 3886 std::tie(Stripped, Offset) = splitAddExpr(S); 3887 // If stripped is SCEVUnknown, don't bother to save 3888 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3889 // increase the complexity of the expansion code. 3890 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3891 // because it may generate add/sub instead of GEP in SCEV expansion. 3892 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3893 !isa<GetElementPtrInst>(V)) 3894 ExprValueMap[Stripped].insert({V, Offset}); 3895 } 3896 } 3897 return S; 3898 } 3899 3900 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3901 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3902 3903 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3904 if (I != ValueExprMap.end()) { 3905 const SCEV *S = I->second; 3906 if (checkValidity(S)) 3907 return S; 3908 eraseValueFromMap(V); 3909 forgetMemoizedResults(S); 3910 } 3911 return nullptr; 3912 } 3913 3914 /// Return a SCEV corresponding to -V = -1*V 3915 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3916 SCEV::NoWrapFlags Flags) { 3917 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3918 return getConstant( 3919 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3920 3921 Type *Ty = V->getType(); 3922 Ty = getEffectiveSCEVType(Ty); 3923 return getMulExpr( 3924 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3925 } 3926 3927 /// Return a SCEV corresponding to ~V = -1-V 3928 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3929 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3930 return getConstant( 3931 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3932 3933 Type *Ty = V->getType(); 3934 Ty = getEffectiveSCEVType(Ty); 3935 const SCEV *AllOnes = 3936 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3937 return getMinusSCEV(AllOnes, V); 3938 } 3939 3940 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3941 SCEV::NoWrapFlags Flags, 3942 unsigned Depth) { 3943 // Fast path: X - X --> 0. 3944 if (LHS == RHS) 3945 return getZero(LHS->getType()); 3946 3947 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3948 // makes it so that we cannot make much use of NUW. 3949 auto AddFlags = SCEV::FlagAnyWrap; 3950 const bool RHSIsNotMinSigned = 3951 !getSignedRangeMin(RHS).isMinSignedValue(); 3952 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3953 // Let M be the minimum representable signed value. Then (-1)*RHS 3954 // signed-wraps if and only if RHS is M. That can happen even for 3955 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3956 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3957 // (-1)*RHS, we need to prove that RHS != M. 3958 // 3959 // If LHS is non-negative and we know that LHS - RHS does not 3960 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3961 // either by proving that RHS > M or that LHS >= 0. 3962 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3963 AddFlags = SCEV::FlagNSW; 3964 } 3965 } 3966 3967 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3968 // RHS is NSW and LHS >= 0. 3969 // 3970 // The difficulty here is that the NSW flag may have been proven 3971 // relative to a loop that is to be found in a recurrence in LHS and 3972 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3973 // larger scope than intended. 3974 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3975 3976 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3977 } 3978 3979 const SCEV * 3980 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3981 Type *SrcTy = V->getType(); 3982 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3983 "Cannot truncate or zero extend with non-integer arguments!"); 3984 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3985 return V; // No conversion 3986 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3987 return getTruncateExpr(V, Ty); 3988 return getZeroExtendExpr(V, Ty); 3989 } 3990 3991 const SCEV * 3992 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3993 Type *Ty) { 3994 Type *SrcTy = V->getType(); 3995 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3996 "Cannot truncate or zero extend with non-integer arguments!"); 3997 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3998 return V; // No conversion 3999 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4000 return getTruncateExpr(V, Ty); 4001 return getSignExtendExpr(V, Ty); 4002 } 4003 4004 const SCEV * 4005 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4006 Type *SrcTy = V->getType(); 4007 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4008 "Cannot noop or zero extend with non-integer arguments!"); 4009 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4010 "getNoopOrZeroExtend cannot truncate!"); 4011 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4012 return V; // No conversion 4013 return getZeroExtendExpr(V, Ty); 4014 } 4015 4016 const SCEV * 4017 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4018 Type *SrcTy = V->getType(); 4019 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4020 "Cannot noop or sign extend with non-integer arguments!"); 4021 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4022 "getNoopOrSignExtend cannot truncate!"); 4023 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4024 return V; // No conversion 4025 return getSignExtendExpr(V, Ty); 4026 } 4027 4028 const SCEV * 4029 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4030 Type *SrcTy = V->getType(); 4031 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4032 "Cannot noop or any extend with non-integer arguments!"); 4033 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4034 "getNoopOrAnyExtend cannot truncate!"); 4035 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4036 return V; // No conversion 4037 return getAnyExtendExpr(V, Ty); 4038 } 4039 4040 const SCEV * 4041 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4042 Type *SrcTy = V->getType(); 4043 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4044 "Cannot truncate or noop with non-integer arguments!"); 4045 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4046 "getTruncateOrNoop cannot extend!"); 4047 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4048 return V; // No conversion 4049 return getTruncateExpr(V, Ty); 4050 } 4051 4052 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4053 const SCEV *RHS) { 4054 const SCEV *PromotedLHS = LHS; 4055 const SCEV *PromotedRHS = RHS; 4056 4057 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4058 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4059 else 4060 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4061 4062 return getUMaxExpr(PromotedLHS, PromotedRHS); 4063 } 4064 4065 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4066 const SCEV *RHS) { 4067 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4068 return getUMinFromMismatchedTypes(Ops); 4069 } 4070 4071 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4072 SmallVectorImpl<const SCEV *> &Ops) { 4073 assert(!Ops.empty() && "At least one operand must be!"); 4074 // Trivial case. 4075 if (Ops.size() == 1) 4076 return Ops[0]; 4077 4078 // Find the max type first. 4079 Type *MaxType = nullptr; 4080 for (auto *S : Ops) 4081 if (MaxType) 4082 MaxType = getWiderType(MaxType, S->getType()); 4083 else 4084 MaxType = S->getType(); 4085 4086 // Extend all ops to max type. 4087 SmallVector<const SCEV *, 2> PromotedOps; 4088 for (auto *S : Ops) 4089 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4090 4091 // Generate umin. 4092 return getUMinExpr(PromotedOps); 4093 } 4094 4095 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4096 // A pointer operand may evaluate to a nonpointer expression, such as null. 4097 if (!V->getType()->isPointerTy()) 4098 return V; 4099 4100 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4101 return getPointerBase(Cast->getOperand()); 4102 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4103 const SCEV *PtrOp = nullptr; 4104 for (const SCEV *NAryOp : NAry->operands()) { 4105 if (NAryOp->getType()->isPointerTy()) { 4106 // Cannot find the base of an expression with multiple pointer operands. 4107 if (PtrOp) 4108 return V; 4109 PtrOp = NAryOp; 4110 } 4111 } 4112 if (!PtrOp) 4113 return V; 4114 return getPointerBase(PtrOp); 4115 } 4116 return V; 4117 } 4118 4119 /// Push users of the given Instruction onto the given Worklist. 4120 static void 4121 PushDefUseChildren(Instruction *I, 4122 SmallVectorImpl<Instruction *> &Worklist) { 4123 // Push the def-use children onto the Worklist stack. 4124 for (User *U : I->users()) 4125 Worklist.push_back(cast<Instruction>(U)); 4126 } 4127 4128 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4129 SmallVector<Instruction *, 16> Worklist; 4130 PushDefUseChildren(PN, Worklist); 4131 4132 SmallPtrSet<Instruction *, 8> Visited; 4133 Visited.insert(PN); 4134 while (!Worklist.empty()) { 4135 Instruction *I = Worklist.pop_back_val(); 4136 if (!Visited.insert(I).second) 4137 continue; 4138 4139 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4140 if (It != ValueExprMap.end()) { 4141 const SCEV *Old = It->second; 4142 4143 // Short-circuit the def-use traversal if the symbolic name 4144 // ceases to appear in expressions. 4145 if (Old != SymName && !hasOperand(Old, SymName)) 4146 continue; 4147 4148 // SCEVUnknown for a PHI either means that it has an unrecognized 4149 // structure, it's a PHI that's in the progress of being computed 4150 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4151 // additional loop trip count information isn't going to change anything. 4152 // In the second case, createNodeForPHI will perform the necessary 4153 // updates on its own when it gets to that point. In the third, we do 4154 // want to forget the SCEVUnknown. 4155 if (!isa<PHINode>(I) || 4156 !isa<SCEVUnknown>(Old) || 4157 (I != PN && Old == SymName)) { 4158 eraseValueFromMap(It->first); 4159 forgetMemoizedResults(Old); 4160 } 4161 } 4162 4163 PushDefUseChildren(I, Worklist); 4164 } 4165 } 4166 4167 namespace { 4168 4169 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4170 /// expression in case its Loop is L. If it is not L then 4171 /// if IgnoreOtherLoops is true then use AddRec itself 4172 /// otherwise rewrite cannot be done. 4173 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4174 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4175 public: 4176 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4177 bool IgnoreOtherLoops = true) { 4178 SCEVInitRewriter Rewriter(L, SE); 4179 const SCEV *Result = Rewriter.visit(S); 4180 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4181 return SE.getCouldNotCompute(); 4182 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4183 ? SE.getCouldNotCompute() 4184 : Result; 4185 } 4186 4187 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4188 if (!SE.isLoopInvariant(Expr, L)) 4189 SeenLoopVariantSCEVUnknown = true; 4190 return Expr; 4191 } 4192 4193 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4194 // Only re-write AddRecExprs for this loop. 4195 if (Expr->getLoop() == L) 4196 return Expr->getStart(); 4197 SeenOtherLoops = true; 4198 return Expr; 4199 } 4200 4201 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4202 4203 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4204 4205 private: 4206 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4207 : SCEVRewriteVisitor(SE), L(L) {} 4208 4209 const Loop *L; 4210 bool SeenLoopVariantSCEVUnknown = false; 4211 bool SeenOtherLoops = false; 4212 }; 4213 4214 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4215 /// increment expression in case its Loop is L. If it is not L then 4216 /// use AddRec itself. 4217 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4218 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4219 public: 4220 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4221 SCEVPostIncRewriter Rewriter(L, SE); 4222 const SCEV *Result = Rewriter.visit(S); 4223 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4224 ? SE.getCouldNotCompute() 4225 : Result; 4226 } 4227 4228 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4229 if (!SE.isLoopInvariant(Expr, L)) 4230 SeenLoopVariantSCEVUnknown = true; 4231 return Expr; 4232 } 4233 4234 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4235 // Only re-write AddRecExprs for this loop. 4236 if (Expr->getLoop() == L) 4237 return Expr->getPostIncExpr(SE); 4238 SeenOtherLoops = true; 4239 return Expr; 4240 } 4241 4242 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4243 4244 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4245 4246 private: 4247 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4248 : SCEVRewriteVisitor(SE), L(L) {} 4249 4250 const Loop *L; 4251 bool SeenLoopVariantSCEVUnknown = false; 4252 bool SeenOtherLoops = false; 4253 }; 4254 4255 /// This class evaluates the compare condition by matching it against the 4256 /// condition of loop latch. If there is a match we assume a true value 4257 /// for the condition while building SCEV nodes. 4258 class SCEVBackedgeConditionFolder 4259 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4260 public: 4261 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4262 ScalarEvolution &SE) { 4263 bool IsPosBECond = false; 4264 Value *BECond = nullptr; 4265 if (BasicBlock *Latch = L->getLoopLatch()) { 4266 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4267 if (BI && BI->isConditional()) { 4268 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4269 "Both outgoing branches should not target same header!"); 4270 BECond = BI->getCondition(); 4271 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4272 } else { 4273 return S; 4274 } 4275 } 4276 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4277 return Rewriter.visit(S); 4278 } 4279 4280 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4281 const SCEV *Result = Expr; 4282 bool InvariantF = SE.isLoopInvariant(Expr, L); 4283 4284 if (!InvariantF) { 4285 Instruction *I = cast<Instruction>(Expr->getValue()); 4286 switch (I->getOpcode()) { 4287 case Instruction::Select: { 4288 SelectInst *SI = cast<SelectInst>(I); 4289 Optional<const SCEV *> Res = 4290 compareWithBackedgeCondition(SI->getCondition()); 4291 if (Res.hasValue()) { 4292 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4293 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4294 } 4295 break; 4296 } 4297 default: { 4298 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4299 if (Res.hasValue()) 4300 Result = Res.getValue(); 4301 break; 4302 } 4303 } 4304 } 4305 return Result; 4306 } 4307 4308 private: 4309 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4310 bool IsPosBECond, ScalarEvolution &SE) 4311 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4312 IsPositiveBECond(IsPosBECond) {} 4313 4314 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4315 4316 const Loop *L; 4317 /// Loop back condition. 4318 Value *BackedgeCond = nullptr; 4319 /// Set to true if loop back is on positive branch condition. 4320 bool IsPositiveBECond; 4321 }; 4322 4323 Optional<const SCEV *> 4324 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4325 4326 // If value matches the backedge condition for loop latch, 4327 // then return a constant evolution node based on loopback 4328 // branch taken. 4329 if (BackedgeCond == IC) 4330 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4331 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4332 return None; 4333 } 4334 4335 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4336 public: 4337 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4338 ScalarEvolution &SE) { 4339 SCEVShiftRewriter Rewriter(L, SE); 4340 const SCEV *Result = Rewriter.visit(S); 4341 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4342 } 4343 4344 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4345 // Only allow AddRecExprs for this loop. 4346 if (!SE.isLoopInvariant(Expr, L)) 4347 Valid = false; 4348 return Expr; 4349 } 4350 4351 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4352 if (Expr->getLoop() == L && Expr->isAffine()) 4353 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4354 Valid = false; 4355 return Expr; 4356 } 4357 4358 bool isValid() { return Valid; } 4359 4360 private: 4361 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4362 : SCEVRewriteVisitor(SE), L(L) {} 4363 4364 const Loop *L; 4365 bool Valid = true; 4366 }; 4367 4368 } // end anonymous namespace 4369 4370 SCEV::NoWrapFlags 4371 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4372 if (!AR->isAffine()) 4373 return SCEV::FlagAnyWrap; 4374 4375 using OBO = OverflowingBinaryOperator; 4376 4377 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4378 4379 if (!AR->hasNoSignedWrap()) { 4380 ConstantRange AddRecRange = getSignedRange(AR); 4381 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4382 4383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4384 Instruction::Add, IncRange, OBO::NoSignedWrap); 4385 if (NSWRegion.contains(AddRecRange)) 4386 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4387 } 4388 4389 if (!AR->hasNoUnsignedWrap()) { 4390 ConstantRange AddRecRange = getUnsignedRange(AR); 4391 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4392 4393 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4394 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4395 if (NUWRegion.contains(AddRecRange)) 4396 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4397 } 4398 4399 return Result; 4400 } 4401 4402 namespace { 4403 4404 /// Represents an abstract binary operation. This may exist as a 4405 /// normal instruction or constant expression, or may have been 4406 /// derived from an expression tree. 4407 struct BinaryOp { 4408 unsigned Opcode; 4409 Value *LHS; 4410 Value *RHS; 4411 bool IsNSW = false; 4412 bool IsNUW = false; 4413 4414 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4415 /// constant expression. 4416 Operator *Op = nullptr; 4417 4418 explicit BinaryOp(Operator *Op) 4419 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4420 Op(Op) { 4421 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4422 IsNSW = OBO->hasNoSignedWrap(); 4423 IsNUW = OBO->hasNoUnsignedWrap(); 4424 } 4425 } 4426 4427 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4428 bool IsNUW = false) 4429 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4430 }; 4431 4432 } // end anonymous namespace 4433 4434 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4435 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4436 auto *Op = dyn_cast<Operator>(V); 4437 if (!Op) 4438 return None; 4439 4440 // Implementation detail: all the cleverness here should happen without 4441 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4442 // SCEV expressions when possible, and we should not break that. 4443 4444 switch (Op->getOpcode()) { 4445 case Instruction::Add: 4446 case Instruction::Sub: 4447 case Instruction::Mul: 4448 case Instruction::UDiv: 4449 case Instruction::URem: 4450 case Instruction::And: 4451 case Instruction::Or: 4452 case Instruction::AShr: 4453 case Instruction::Shl: 4454 return BinaryOp(Op); 4455 4456 case Instruction::Xor: 4457 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4458 // If the RHS of the xor is a signmask, then this is just an add. 4459 // Instcombine turns add of signmask into xor as a strength reduction step. 4460 if (RHSC->getValue().isSignMask()) 4461 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4462 return BinaryOp(Op); 4463 4464 case Instruction::LShr: 4465 // Turn logical shift right of a constant into a unsigned divide. 4466 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4467 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4468 4469 // If the shift count is not less than the bitwidth, the result of 4470 // the shift is undefined. Don't try to analyze it, because the 4471 // resolution chosen here may differ from the resolution chosen in 4472 // other parts of the compiler. 4473 if (SA->getValue().ult(BitWidth)) { 4474 Constant *X = 4475 ConstantInt::get(SA->getContext(), 4476 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4477 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4478 } 4479 } 4480 return BinaryOp(Op); 4481 4482 case Instruction::ExtractValue: { 4483 auto *EVI = cast<ExtractValueInst>(Op); 4484 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4485 break; 4486 4487 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4488 if (!CI) 4489 break; 4490 4491 if (auto *F = CI->getCalledFunction()) 4492 switch (F->getIntrinsicID()) { 4493 case Intrinsic::sadd_with_overflow: 4494 case Intrinsic::uadd_with_overflow: 4495 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4496 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4497 CI->getArgOperand(1)); 4498 4499 // Now that we know that all uses of the arithmetic-result component of 4500 // CI are guarded by the overflow check, we can go ahead and pretend 4501 // that the arithmetic is non-overflowing. 4502 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4503 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4504 CI->getArgOperand(1), /* IsNSW = */ true, 4505 /* IsNUW = */ false); 4506 else 4507 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4508 CI->getArgOperand(1), /* IsNSW = */ false, 4509 /* IsNUW*/ true); 4510 case Intrinsic::ssub_with_overflow: 4511 case Intrinsic::usub_with_overflow: 4512 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4513 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4514 CI->getArgOperand(1)); 4515 4516 // The same reasoning as sadd/uadd above. 4517 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4518 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4519 CI->getArgOperand(1), /* IsNSW = */ true, 4520 /* IsNUW = */ false); 4521 else 4522 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4523 CI->getArgOperand(1), /* IsNSW = */ false, 4524 /* IsNUW = */ true); 4525 case Intrinsic::smul_with_overflow: 4526 case Intrinsic::umul_with_overflow: 4527 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4528 CI->getArgOperand(1)); 4529 default: 4530 break; 4531 } 4532 break; 4533 } 4534 4535 default: 4536 break; 4537 } 4538 4539 return None; 4540 } 4541 4542 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4543 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4544 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4545 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4546 /// follows one of the following patterns: 4547 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4548 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4549 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4550 /// we return the type of the truncation operation, and indicate whether the 4551 /// truncated type should be treated as signed/unsigned by setting 4552 /// \p Signed to true/false, respectively. 4553 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4554 bool &Signed, ScalarEvolution &SE) { 4555 // The case where Op == SymbolicPHI (that is, with no type conversions on 4556 // the way) is handled by the regular add recurrence creating logic and 4557 // would have already been triggered in createAddRecForPHI. Reaching it here 4558 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4559 // because one of the other operands of the SCEVAddExpr updating this PHI is 4560 // not invariant). 4561 // 4562 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4563 // this case predicates that allow us to prove that Op == SymbolicPHI will 4564 // be added. 4565 if (Op == SymbolicPHI) 4566 return nullptr; 4567 4568 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4569 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4570 if (SourceBits != NewBits) 4571 return nullptr; 4572 4573 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4574 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4575 if (!SExt && !ZExt) 4576 return nullptr; 4577 const SCEVTruncateExpr *Trunc = 4578 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4579 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4580 if (!Trunc) 4581 return nullptr; 4582 const SCEV *X = Trunc->getOperand(); 4583 if (X != SymbolicPHI) 4584 return nullptr; 4585 Signed = SExt != nullptr; 4586 return Trunc->getType(); 4587 } 4588 4589 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4590 if (!PN->getType()->isIntegerTy()) 4591 return nullptr; 4592 const Loop *L = LI.getLoopFor(PN->getParent()); 4593 if (!L || L->getHeader() != PN->getParent()) 4594 return nullptr; 4595 return L; 4596 } 4597 4598 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4599 // computation that updates the phi follows the following pattern: 4600 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4601 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4602 // If so, try to see if it can be rewritten as an AddRecExpr under some 4603 // Predicates. If successful, return them as a pair. Also cache the results 4604 // of the analysis. 4605 // 4606 // Example usage scenario: 4607 // Say the Rewriter is called for the following SCEV: 4608 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4609 // where: 4610 // %X = phi i64 (%Start, %BEValue) 4611 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4612 // and call this function with %SymbolicPHI = %X. 4613 // 4614 // The analysis will find that the value coming around the backedge has 4615 // the following SCEV: 4616 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4617 // Upon concluding that this matches the desired pattern, the function 4618 // will return the pair {NewAddRec, SmallPredsVec} where: 4619 // NewAddRec = {%Start,+,%Step} 4620 // SmallPredsVec = {P1, P2, P3} as follows: 4621 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4622 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4623 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4624 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4625 // under the predicates {P1,P2,P3}. 4626 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4627 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4628 // 4629 // TODO's: 4630 // 4631 // 1) Extend the Induction descriptor to also support inductions that involve 4632 // casts: When needed (namely, when we are called in the context of the 4633 // vectorizer induction analysis), a Set of cast instructions will be 4634 // populated by this method, and provided back to isInductionPHI. This is 4635 // needed to allow the vectorizer to properly record them to be ignored by 4636 // the cost model and to avoid vectorizing them (otherwise these casts, 4637 // which are redundant under the runtime overflow checks, will be 4638 // vectorized, which can be costly). 4639 // 4640 // 2) Support additional induction/PHISCEV patterns: We also want to support 4641 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4642 // after the induction update operation (the induction increment): 4643 // 4644 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4645 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4646 // 4647 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4648 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4649 // 4650 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4651 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4652 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4653 SmallVector<const SCEVPredicate *, 3> Predicates; 4654 4655 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4656 // return an AddRec expression under some predicate. 4657 4658 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4659 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4660 assert(L && "Expecting an integer loop header phi"); 4661 4662 // The loop may have multiple entrances or multiple exits; we can analyze 4663 // this phi as an addrec if it has a unique entry value and a unique 4664 // backedge value. 4665 Value *BEValueV = nullptr, *StartValueV = nullptr; 4666 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4667 Value *V = PN->getIncomingValue(i); 4668 if (L->contains(PN->getIncomingBlock(i))) { 4669 if (!BEValueV) { 4670 BEValueV = V; 4671 } else if (BEValueV != V) { 4672 BEValueV = nullptr; 4673 break; 4674 } 4675 } else if (!StartValueV) { 4676 StartValueV = V; 4677 } else if (StartValueV != V) { 4678 StartValueV = nullptr; 4679 break; 4680 } 4681 } 4682 if (!BEValueV || !StartValueV) 4683 return None; 4684 4685 const SCEV *BEValue = getSCEV(BEValueV); 4686 4687 // If the value coming around the backedge is an add with the symbolic 4688 // value we just inserted, possibly with casts that we can ignore under 4689 // an appropriate runtime guard, then we found a simple induction variable! 4690 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4691 if (!Add) 4692 return None; 4693 4694 // If there is a single occurrence of the symbolic value, possibly 4695 // casted, replace it with a recurrence. 4696 unsigned FoundIndex = Add->getNumOperands(); 4697 Type *TruncTy = nullptr; 4698 bool Signed; 4699 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4700 if ((TruncTy = 4701 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4702 if (FoundIndex == e) { 4703 FoundIndex = i; 4704 break; 4705 } 4706 4707 if (FoundIndex == Add->getNumOperands()) 4708 return None; 4709 4710 // Create an add with everything but the specified operand. 4711 SmallVector<const SCEV *, 8> Ops; 4712 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4713 if (i != FoundIndex) 4714 Ops.push_back(Add->getOperand(i)); 4715 const SCEV *Accum = getAddExpr(Ops); 4716 4717 // The runtime checks will not be valid if the step amount is 4718 // varying inside the loop. 4719 if (!isLoopInvariant(Accum, L)) 4720 return None; 4721 4722 // *** Part2: Create the predicates 4723 4724 // Analysis was successful: we have a phi-with-cast pattern for which we 4725 // can return an AddRec expression under the following predicates: 4726 // 4727 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4728 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4729 // P2: An Equal predicate that guarantees that 4730 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4731 // P3: An Equal predicate that guarantees that 4732 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4733 // 4734 // As we next prove, the above predicates guarantee that: 4735 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4736 // 4737 // 4738 // More formally, we want to prove that: 4739 // Expr(i+1) = Start + (i+1) * Accum 4740 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4741 // 4742 // Given that: 4743 // 1) Expr(0) = Start 4744 // 2) Expr(1) = Start + Accum 4745 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4746 // 3) Induction hypothesis (step i): 4747 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4748 // 4749 // Proof: 4750 // Expr(i+1) = 4751 // = Start + (i+1)*Accum 4752 // = (Start + i*Accum) + Accum 4753 // = Expr(i) + Accum 4754 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4755 // :: from step i 4756 // 4757 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4758 // 4759 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4760 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4761 // + Accum :: from P3 4762 // 4763 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4764 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4765 // 4766 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4767 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4768 // 4769 // By induction, the same applies to all iterations 1<=i<n: 4770 // 4771 4772 // Create a truncated addrec for which we will add a no overflow check (P1). 4773 const SCEV *StartVal = getSCEV(StartValueV); 4774 const SCEV *PHISCEV = 4775 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4776 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4777 4778 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4779 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4780 // will be constant. 4781 // 4782 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4783 // add P1. 4784 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4785 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4786 Signed ? SCEVWrapPredicate::IncrementNSSW 4787 : SCEVWrapPredicate::IncrementNUSW; 4788 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4789 Predicates.push_back(AddRecPred); 4790 } 4791 4792 // Create the Equal Predicates P2,P3: 4793 4794 // It is possible that the predicates P2 and/or P3 are computable at 4795 // compile time due to StartVal and/or Accum being constants. 4796 // If either one is, then we can check that now and escape if either P2 4797 // or P3 is false. 4798 4799 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4800 // for each of StartVal and Accum 4801 auto getExtendedExpr = [&](const SCEV *Expr, 4802 bool CreateSignExtend) -> const SCEV * { 4803 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4804 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4805 const SCEV *ExtendedExpr = 4806 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4807 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4808 return ExtendedExpr; 4809 }; 4810 4811 // Given: 4812 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4813 // = getExtendedExpr(Expr) 4814 // Determine whether the predicate P: Expr == ExtendedExpr 4815 // is known to be false at compile time 4816 auto PredIsKnownFalse = [&](const SCEV *Expr, 4817 const SCEV *ExtendedExpr) -> bool { 4818 return Expr != ExtendedExpr && 4819 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4820 }; 4821 4822 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4823 if (PredIsKnownFalse(StartVal, StartExtended)) { 4824 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4825 return None; 4826 } 4827 4828 // The Step is always Signed (because the overflow checks are either 4829 // NSSW or NUSW) 4830 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4831 if (PredIsKnownFalse(Accum, AccumExtended)) { 4832 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4833 return None; 4834 } 4835 4836 auto AppendPredicate = [&](const SCEV *Expr, 4837 const SCEV *ExtendedExpr) -> void { 4838 if (Expr != ExtendedExpr && 4839 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4840 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4841 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4842 Predicates.push_back(Pred); 4843 } 4844 }; 4845 4846 AppendPredicate(StartVal, StartExtended); 4847 AppendPredicate(Accum, AccumExtended); 4848 4849 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4850 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4851 // into NewAR if it will also add the runtime overflow checks specified in 4852 // Predicates. 4853 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4854 4855 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4856 std::make_pair(NewAR, Predicates); 4857 // Remember the result of the analysis for this SCEV at this locayyytion. 4858 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4859 return PredRewrite; 4860 } 4861 4862 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4863 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4864 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4865 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4866 if (!L) 4867 return None; 4868 4869 // Check to see if we already analyzed this PHI. 4870 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4871 if (I != PredicatedSCEVRewrites.end()) { 4872 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4873 I->second; 4874 // Analysis was done before and failed to create an AddRec: 4875 if (Rewrite.first == SymbolicPHI) 4876 return None; 4877 // Analysis was done before and succeeded to create an AddRec under 4878 // a predicate: 4879 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4880 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4881 return Rewrite; 4882 } 4883 4884 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4885 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4886 4887 // Record in the cache that the analysis failed 4888 if (!Rewrite) { 4889 SmallVector<const SCEVPredicate *, 3> Predicates; 4890 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4891 return None; 4892 } 4893 4894 return Rewrite; 4895 } 4896 4897 // FIXME: This utility is currently required because the Rewriter currently 4898 // does not rewrite this expression: 4899 // {0, +, (sext ix (trunc iy to ix) to iy)} 4900 // into {0, +, %step}, 4901 // even when the following Equal predicate exists: 4902 // "%step == (sext ix (trunc iy to ix) to iy)". 4903 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4904 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4905 if (AR1 == AR2) 4906 return true; 4907 4908 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4909 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4910 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4911 return false; 4912 return true; 4913 }; 4914 4915 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4916 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4917 return false; 4918 return true; 4919 } 4920 4921 /// A helper function for createAddRecFromPHI to handle simple cases. 4922 /// 4923 /// This function tries to find an AddRec expression for the simplest (yet most 4924 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4925 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4926 /// technique for finding the AddRec expression. 4927 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4928 Value *BEValueV, 4929 Value *StartValueV) { 4930 const Loop *L = LI.getLoopFor(PN->getParent()); 4931 assert(L && L->getHeader() == PN->getParent()); 4932 assert(BEValueV && StartValueV); 4933 4934 auto BO = MatchBinaryOp(BEValueV, DT); 4935 if (!BO) 4936 return nullptr; 4937 4938 if (BO->Opcode != Instruction::Add) 4939 return nullptr; 4940 4941 const SCEV *Accum = nullptr; 4942 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4943 Accum = getSCEV(BO->RHS); 4944 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4945 Accum = getSCEV(BO->LHS); 4946 4947 if (!Accum) 4948 return nullptr; 4949 4950 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4951 if (BO->IsNUW) 4952 Flags = setFlags(Flags, SCEV::FlagNUW); 4953 if (BO->IsNSW) 4954 Flags = setFlags(Flags, SCEV::FlagNSW); 4955 4956 const SCEV *StartVal = getSCEV(StartValueV); 4957 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4958 4959 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4960 4961 // We can add Flags to the post-inc expression only if we 4962 // know that it is *undefined behavior* for BEValueV to 4963 // overflow. 4964 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4965 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4966 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4967 4968 return PHISCEV; 4969 } 4970 4971 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4972 const Loop *L = LI.getLoopFor(PN->getParent()); 4973 if (!L || L->getHeader() != PN->getParent()) 4974 return nullptr; 4975 4976 // The loop may have multiple entrances or multiple exits; we can analyze 4977 // this phi as an addrec if it has a unique entry value and a unique 4978 // backedge value. 4979 Value *BEValueV = nullptr, *StartValueV = nullptr; 4980 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4981 Value *V = PN->getIncomingValue(i); 4982 if (L->contains(PN->getIncomingBlock(i))) { 4983 if (!BEValueV) { 4984 BEValueV = V; 4985 } else if (BEValueV != V) { 4986 BEValueV = nullptr; 4987 break; 4988 } 4989 } else if (!StartValueV) { 4990 StartValueV = V; 4991 } else if (StartValueV != V) { 4992 StartValueV = nullptr; 4993 break; 4994 } 4995 } 4996 if (!BEValueV || !StartValueV) 4997 return nullptr; 4998 4999 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5000 "PHI node already processed?"); 5001 5002 // First, try to find AddRec expression without creating a fictituos symbolic 5003 // value for PN. 5004 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5005 return S; 5006 5007 // Handle PHI node value symbolically. 5008 const SCEV *SymbolicName = getUnknown(PN); 5009 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5010 5011 // Using this symbolic name for the PHI, analyze the value coming around 5012 // the back-edge. 5013 const SCEV *BEValue = getSCEV(BEValueV); 5014 5015 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5016 // has a special value for the first iteration of the loop. 5017 5018 // If the value coming around the backedge is an add with the symbolic 5019 // value we just inserted, then we found a simple induction variable! 5020 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5021 // If there is a single occurrence of the symbolic value, replace it 5022 // with a recurrence. 5023 unsigned FoundIndex = Add->getNumOperands(); 5024 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5025 if (Add->getOperand(i) == SymbolicName) 5026 if (FoundIndex == e) { 5027 FoundIndex = i; 5028 break; 5029 } 5030 5031 if (FoundIndex != Add->getNumOperands()) { 5032 // Create an add with everything but the specified operand. 5033 SmallVector<const SCEV *, 8> Ops; 5034 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5035 if (i != FoundIndex) 5036 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5037 L, *this)); 5038 const SCEV *Accum = getAddExpr(Ops); 5039 5040 // This is not a valid addrec if the step amount is varying each 5041 // loop iteration, but is not itself an addrec in this loop. 5042 if (isLoopInvariant(Accum, L) || 5043 (isa<SCEVAddRecExpr>(Accum) && 5044 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5045 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5046 5047 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5048 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5049 if (BO->IsNUW) 5050 Flags = setFlags(Flags, SCEV::FlagNUW); 5051 if (BO->IsNSW) 5052 Flags = setFlags(Flags, SCEV::FlagNSW); 5053 } 5054 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5055 // If the increment is an inbounds GEP, then we know the address 5056 // space cannot be wrapped around. We cannot make any guarantee 5057 // about signed or unsigned overflow because pointers are 5058 // unsigned but we may have a negative index from the base 5059 // pointer. We can guarantee that no unsigned wrap occurs if the 5060 // indices form a positive value. 5061 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5062 Flags = setFlags(Flags, SCEV::FlagNW); 5063 5064 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5065 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5066 Flags = setFlags(Flags, SCEV::FlagNUW); 5067 } 5068 5069 // We cannot transfer nuw and nsw flags from subtraction 5070 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5071 // for instance. 5072 } 5073 5074 const SCEV *StartVal = getSCEV(StartValueV); 5075 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5076 5077 // Okay, for the entire analysis of this edge we assumed the PHI 5078 // to be symbolic. We now need to go back and purge all of the 5079 // entries for the scalars that use the symbolic expression. 5080 forgetSymbolicName(PN, SymbolicName); 5081 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5082 5083 // We can add Flags to the post-inc expression only if we 5084 // know that it is *undefined behavior* for BEValueV to 5085 // overflow. 5086 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5087 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5088 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5089 5090 return PHISCEV; 5091 } 5092 } 5093 } else { 5094 // Otherwise, this could be a loop like this: 5095 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5096 // In this case, j = {1,+,1} and BEValue is j. 5097 // Because the other in-value of i (0) fits the evolution of BEValue 5098 // i really is an addrec evolution. 5099 // 5100 // We can generalize this saying that i is the shifted value of BEValue 5101 // by one iteration: 5102 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5103 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5104 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5105 if (Shifted != getCouldNotCompute() && 5106 Start != getCouldNotCompute()) { 5107 const SCEV *StartVal = getSCEV(StartValueV); 5108 if (Start == StartVal) { 5109 // Okay, for the entire analysis of this edge we assumed the PHI 5110 // to be symbolic. We now need to go back and purge all of the 5111 // entries for the scalars that use the symbolic expression. 5112 forgetSymbolicName(PN, SymbolicName); 5113 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5114 return Shifted; 5115 } 5116 } 5117 } 5118 5119 // Remove the temporary PHI node SCEV that has been inserted while intending 5120 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5121 // as it will prevent later (possibly simpler) SCEV expressions to be added 5122 // to the ValueExprMap. 5123 eraseValueFromMap(PN); 5124 5125 return nullptr; 5126 } 5127 5128 // Checks if the SCEV S is available at BB. S is considered available at BB 5129 // if S can be materialized at BB without introducing a fault. 5130 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5131 BasicBlock *BB) { 5132 struct CheckAvailable { 5133 bool TraversalDone = false; 5134 bool Available = true; 5135 5136 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5137 BasicBlock *BB = nullptr; 5138 DominatorTree &DT; 5139 5140 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5141 : L(L), BB(BB), DT(DT) {} 5142 5143 bool setUnavailable() { 5144 TraversalDone = true; 5145 Available = false; 5146 return false; 5147 } 5148 5149 bool follow(const SCEV *S) { 5150 switch (S->getSCEVType()) { 5151 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5152 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5153 // These expressions are available if their operand(s) is/are. 5154 return true; 5155 5156 case scAddRecExpr: { 5157 // We allow add recurrences that are on the loop BB is in, or some 5158 // outer loop. This guarantees availability because the value of the 5159 // add recurrence at BB is simply the "current" value of the induction 5160 // variable. We can relax this in the future; for instance an add 5161 // recurrence on a sibling dominating loop is also available at BB. 5162 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5163 if (L && (ARLoop == L || ARLoop->contains(L))) 5164 return true; 5165 5166 return setUnavailable(); 5167 } 5168 5169 case scUnknown: { 5170 // For SCEVUnknown, we check for simple dominance. 5171 const auto *SU = cast<SCEVUnknown>(S); 5172 Value *V = SU->getValue(); 5173 5174 if (isa<Argument>(V)) 5175 return false; 5176 5177 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5178 return false; 5179 5180 return setUnavailable(); 5181 } 5182 5183 case scUDivExpr: 5184 case scCouldNotCompute: 5185 // We do not try to smart about these at all. 5186 return setUnavailable(); 5187 } 5188 llvm_unreachable("switch should be fully covered!"); 5189 } 5190 5191 bool isDone() { return TraversalDone; } 5192 }; 5193 5194 CheckAvailable CA(L, BB, DT); 5195 SCEVTraversal<CheckAvailable> ST(CA); 5196 5197 ST.visitAll(S); 5198 return CA.Available; 5199 } 5200 5201 // Try to match a control flow sequence that branches out at BI and merges back 5202 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5203 // match. 5204 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5205 Value *&C, Value *&LHS, Value *&RHS) { 5206 C = BI->getCondition(); 5207 5208 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5209 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5210 5211 if (!LeftEdge.isSingleEdge()) 5212 return false; 5213 5214 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5215 5216 Use &LeftUse = Merge->getOperandUse(0); 5217 Use &RightUse = Merge->getOperandUse(1); 5218 5219 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5220 LHS = LeftUse; 5221 RHS = RightUse; 5222 return true; 5223 } 5224 5225 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5226 LHS = RightUse; 5227 RHS = LeftUse; 5228 return true; 5229 } 5230 5231 return false; 5232 } 5233 5234 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5235 auto IsReachable = 5236 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5237 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5238 const Loop *L = LI.getLoopFor(PN->getParent()); 5239 5240 // We don't want to break LCSSA, even in a SCEV expression tree. 5241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5242 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5243 return nullptr; 5244 5245 // Try to match 5246 // 5247 // br %cond, label %left, label %right 5248 // left: 5249 // br label %merge 5250 // right: 5251 // br label %merge 5252 // merge: 5253 // V = phi [ %x, %left ], [ %y, %right ] 5254 // 5255 // as "select %cond, %x, %y" 5256 5257 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5258 assert(IDom && "At least the entry block should dominate PN"); 5259 5260 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5261 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5262 5263 if (BI && BI->isConditional() && 5264 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5265 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5266 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5267 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5268 } 5269 5270 return nullptr; 5271 } 5272 5273 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5274 if (const SCEV *S = createAddRecFromPHI(PN)) 5275 return S; 5276 5277 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5278 return S; 5279 5280 // If the PHI has a single incoming value, follow that value, unless the 5281 // PHI's incoming blocks are in a different loop, in which case doing so 5282 // risks breaking LCSSA form. Instcombine would normally zap these, but 5283 // it doesn't have DominatorTree information, so it may miss cases. 5284 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5285 if (LI.replacementPreservesLCSSAForm(PN, V)) 5286 return getSCEV(V); 5287 5288 // If it's not a loop phi, we can't handle it yet. 5289 return getUnknown(PN); 5290 } 5291 5292 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5293 Value *Cond, 5294 Value *TrueVal, 5295 Value *FalseVal) { 5296 // Handle "constant" branch or select. This can occur for instance when a 5297 // loop pass transforms an inner loop and moves on to process the outer loop. 5298 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5299 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5300 5301 // Try to match some simple smax or umax patterns. 5302 auto *ICI = dyn_cast<ICmpInst>(Cond); 5303 if (!ICI) 5304 return getUnknown(I); 5305 5306 Value *LHS = ICI->getOperand(0); 5307 Value *RHS = ICI->getOperand(1); 5308 5309 switch (ICI->getPredicate()) { 5310 case ICmpInst::ICMP_SLT: 5311 case ICmpInst::ICMP_SLE: 5312 std::swap(LHS, RHS); 5313 LLVM_FALLTHROUGH; 5314 case ICmpInst::ICMP_SGT: 5315 case ICmpInst::ICMP_SGE: 5316 // a >s b ? a+x : b+x -> smax(a, b)+x 5317 // a >s b ? b+x : a+x -> smin(a, b)+x 5318 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5319 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5320 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5321 const SCEV *LA = getSCEV(TrueVal); 5322 const SCEV *RA = getSCEV(FalseVal); 5323 const SCEV *LDiff = getMinusSCEV(LA, LS); 5324 const SCEV *RDiff = getMinusSCEV(RA, RS); 5325 if (LDiff == RDiff) 5326 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5327 LDiff = getMinusSCEV(LA, RS); 5328 RDiff = getMinusSCEV(RA, LS); 5329 if (LDiff == RDiff) 5330 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5331 } 5332 break; 5333 case ICmpInst::ICMP_ULT: 5334 case ICmpInst::ICMP_ULE: 5335 std::swap(LHS, RHS); 5336 LLVM_FALLTHROUGH; 5337 case ICmpInst::ICMP_UGT: 5338 case ICmpInst::ICMP_UGE: 5339 // a >u b ? a+x : b+x -> umax(a, b)+x 5340 // a >u b ? b+x : a+x -> umin(a, b)+x 5341 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5342 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5343 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5344 const SCEV *LA = getSCEV(TrueVal); 5345 const SCEV *RA = getSCEV(FalseVal); 5346 const SCEV *LDiff = getMinusSCEV(LA, LS); 5347 const SCEV *RDiff = getMinusSCEV(RA, RS); 5348 if (LDiff == RDiff) 5349 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5350 LDiff = getMinusSCEV(LA, RS); 5351 RDiff = getMinusSCEV(RA, LS); 5352 if (LDiff == RDiff) 5353 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5354 } 5355 break; 5356 case ICmpInst::ICMP_NE: 5357 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5358 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5359 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5360 const SCEV *One = getOne(I->getType()); 5361 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5362 const SCEV *LA = getSCEV(TrueVal); 5363 const SCEV *RA = getSCEV(FalseVal); 5364 const SCEV *LDiff = getMinusSCEV(LA, LS); 5365 const SCEV *RDiff = getMinusSCEV(RA, One); 5366 if (LDiff == RDiff) 5367 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5368 } 5369 break; 5370 case ICmpInst::ICMP_EQ: 5371 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5372 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5373 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5374 const SCEV *One = getOne(I->getType()); 5375 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5376 const SCEV *LA = getSCEV(TrueVal); 5377 const SCEV *RA = getSCEV(FalseVal); 5378 const SCEV *LDiff = getMinusSCEV(LA, One); 5379 const SCEV *RDiff = getMinusSCEV(RA, LS); 5380 if (LDiff == RDiff) 5381 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5382 } 5383 break; 5384 default: 5385 break; 5386 } 5387 5388 return getUnknown(I); 5389 } 5390 5391 /// Expand GEP instructions into add and multiply operations. This allows them 5392 /// to be analyzed by regular SCEV code. 5393 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5394 // Don't attempt to analyze GEPs over unsized objects. 5395 if (!GEP->getSourceElementType()->isSized()) 5396 return getUnknown(GEP); 5397 5398 SmallVector<const SCEV *, 4> IndexExprs; 5399 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5400 IndexExprs.push_back(getSCEV(*Index)); 5401 return getGEPExpr(GEP, IndexExprs); 5402 } 5403 5404 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5405 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5406 return C->getAPInt().countTrailingZeros(); 5407 5408 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5409 return std::min(GetMinTrailingZeros(T->getOperand()), 5410 (uint32_t)getTypeSizeInBits(T->getType())); 5411 5412 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5413 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5414 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5415 ? getTypeSizeInBits(E->getType()) 5416 : OpRes; 5417 } 5418 5419 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5420 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5421 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5422 ? getTypeSizeInBits(E->getType()) 5423 : OpRes; 5424 } 5425 5426 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5427 // The result is the min of all operands results. 5428 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5429 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5430 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5431 return MinOpRes; 5432 } 5433 5434 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5435 // The result is the sum of all operands results. 5436 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5437 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5438 for (unsigned i = 1, e = M->getNumOperands(); 5439 SumOpRes != BitWidth && i != e; ++i) 5440 SumOpRes = 5441 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5442 return SumOpRes; 5443 } 5444 5445 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5446 // The result is the min of all operands results. 5447 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5448 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5449 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5450 return MinOpRes; 5451 } 5452 5453 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5454 // The result is the min of all operands results. 5455 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5456 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5457 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5458 return MinOpRes; 5459 } 5460 5461 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5462 // The result is the min of all operands results. 5463 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5464 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5465 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5466 return MinOpRes; 5467 } 5468 5469 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5470 // For a SCEVUnknown, ask ValueTracking. 5471 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5472 return Known.countMinTrailingZeros(); 5473 } 5474 5475 // SCEVUDivExpr 5476 return 0; 5477 } 5478 5479 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5480 auto I = MinTrailingZerosCache.find(S); 5481 if (I != MinTrailingZerosCache.end()) 5482 return I->second; 5483 5484 uint32_t Result = GetMinTrailingZerosImpl(S); 5485 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5486 assert(InsertPair.second && "Should insert a new key"); 5487 return InsertPair.first->second; 5488 } 5489 5490 /// Helper method to assign a range to V from metadata present in the IR. 5491 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5492 if (Instruction *I = dyn_cast<Instruction>(V)) 5493 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5494 return getConstantRangeFromMetadata(*MD); 5495 5496 return None; 5497 } 5498 5499 /// Determine the range for a particular SCEV. If SignHint is 5500 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5501 /// with a "cleaner" unsigned (resp. signed) representation. 5502 const ConstantRange & 5503 ScalarEvolution::getRangeRef(const SCEV *S, 5504 ScalarEvolution::RangeSignHint SignHint) { 5505 DenseMap<const SCEV *, ConstantRange> &Cache = 5506 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5507 : SignedRanges; 5508 5509 // See if we've computed this range already. 5510 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5511 if (I != Cache.end()) 5512 return I->second; 5513 5514 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5515 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5516 5517 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5518 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5519 5520 // If the value has known zeros, the maximum value will have those known zeros 5521 // as well. 5522 uint32_t TZ = GetMinTrailingZeros(S); 5523 if (TZ != 0) { 5524 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5525 ConservativeResult = 5526 ConstantRange(APInt::getMinValue(BitWidth), 5527 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5528 else 5529 ConservativeResult = ConstantRange( 5530 APInt::getSignedMinValue(BitWidth), 5531 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5532 } 5533 5534 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5535 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5536 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5537 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5538 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5539 } 5540 5541 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5542 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5543 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5544 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5545 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5546 } 5547 5548 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5549 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5550 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5551 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5552 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5553 } 5554 5555 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5556 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5557 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5558 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5559 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5560 } 5561 5562 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5563 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5564 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5565 return setRange(UDiv, SignHint, 5566 ConservativeResult.intersectWith(X.udiv(Y))); 5567 } 5568 5569 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5570 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5571 return setRange(ZExt, SignHint, 5572 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5573 } 5574 5575 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5576 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5577 return setRange(SExt, SignHint, 5578 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5579 } 5580 5581 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5582 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5583 return setRange(Trunc, SignHint, 5584 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5585 } 5586 5587 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5588 // If there's no unsigned wrap, the value will never be less than its 5589 // initial value. 5590 if (AddRec->hasNoUnsignedWrap()) 5591 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5592 if (!C->getValue()->isZero()) 5593 ConservativeResult = ConservativeResult.intersectWith( 5594 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5595 5596 // If there's no signed wrap, and all the operands have the same sign or 5597 // zero, the value won't ever change sign. 5598 if (AddRec->hasNoSignedWrap()) { 5599 bool AllNonNeg = true; 5600 bool AllNonPos = true; 5601 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5602 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5603 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5604 } 5605 if (AllNonNeg) 5606 ConservativeResult = ConservativeResult.intersectWith( 5607 ConstantRange(APInt(BitWidth, 0), 5608 APInt::getSignedMinValue(BitWidth))); 5609 else if (AllNonPos) 5610 ConservativeResult = ConservativeResult.intersectWith( 5611 ConstantRange(APInt::getSignedMinValue(BitWidth), 5612 APInt(BitWidth, 1))); 5613 } 5614 5615 // TODO: non-affine addrec 5616 if (AddRec->isAffine()) { 5617 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5618 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5619 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5620 auto RangeFromAffine = getRangeForAffineAR( 5621 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5622 BitWidth); 5623 if (!RangeFromAffine.isFullSet()) 5624 ConservativeResult = 5625 ConservativeResult.intersectWith(RangeFromAffine); 5626 5627 auto RangeFromFactoring = getRangeViaFactoring( 5628 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5629 BitWidth); 5630 if (!RangeFromFactoring.isFullSet()) 5631 ConservativeResult = 5632 ConservativeResult.intersectWith(RangeFromFactoring); 5633 } 5634 } 5635 5636 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5637 } 5638 5639 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5640 // Check if the IR explicitly contains !range metadata. 5641 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5642 if (MDRange.hasValue()) 5643 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5644 5645 // Split here to avoid paying the compile-time cost of calling both 5646 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5647 // if needed. 5648 const DataLayout &DL = getDataLayout(); 5649 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5650 // For a SCEVUnknown, ask ValueTracking. 5651 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5652 if (Known.One != ~Known.Zero + 1) 5653 ConservativeResult = 5654 ConservativeResult.intersectWith(ConstantRange(Known.One, 5655 ~Known.Zero + 1)); 5656 } else { 5657 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5658 "generalize as needed!"); 5659 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5660 if (NS > 1) 5661 ConservativeResult = ConservativeResult.intersectWith( 5662 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5663 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5664 } 5665 5666 // A range of Phi is a subset of union of all ranges of its input. 5667 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5668 // Make sure that we do not run over cycled Phis. 5669 if (PendingPhiRanges.insert(Phi).second) { 5670 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5671 for (auto &Op : Phi->operands()) { 5672 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5673 RangeFromOps = RangeFromOps.unionWith(OpRange); 5674 // No point to continue if we already have a full set. 5675 if (RangeFromOps.isFullSet()) 5676 break; 5677 } 5678 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5679 bool Erased = PendingPhiRanges.erase(Phi); 5680 assert(Erased && "Failed to erase Phi properly?"); 5681 (void) Erased; 5682 } 5683 } 5684 5685 return setRange(U, SignHint, std::move(ConservativeResult)); 5686 } 5687 5688 return setRange(S, SignHint, std::move(ConservativeResult)); 5689 } 5690 5691 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5692 // values that the expression can take. Initially, the expression has a value 5693 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5694 // argument defines if we treat Step as signed or unsigned. 5695 static ConstantRange getRangeForAffineARHelper(APInt Step, 5696 const ConstantRange &StartRange, 5697 const APInt &MaxBECount, 5698 unsigned BitWidth, bool Signed) { 5699 // If either Step or MaxBECount is 0, then the expression won't change, and we 5700 // just need to return the initial range. 5701 if (Step == 0 || MaxBECount == 0) 5702 return StartRange; 5703 5704 // If we don't know anything about the initial value (i.e. StartRange is 5705 // FullRange), then we don't know anything about the final range either. 5706 // Return FullRange. 5707 if (StartRange.isFullSet()) 5708 return ConstantRange(BitWidth, /* isFullSet = */ true); 5709 5710 // If Step is signed and negative, then we use its absolute value, but we also 5711 // note that we're moving in the opposite direction. 5712 bool Descending = Signed && Step.isNegative(); 5713 5714 if (Signed) 5715 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5716 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5717 // This equations hold true due to the well-defined wrap-around behavior of 5718 // APInt. 5719 Step = Step.abs(); 5720 5721 // Check if Offset is more than full span of BitWidth. If it is, the 5722 // expression is guaranteed to overflow. 5723 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5724 return ConstantRange(BitWidth, /* isFullSet = */ true); 5725 5726 // Offset is by how much the expression can change. Checks above guarantee no 5727 // overflow here. 5728 APInt Offset = Step * MaxBECount; 5729 5730 // Minimum value of the final range will match the minimal value of StartRange 5731 // if the expression is increasing and will be decreased by Offset otherwise. 5732 // Maximum value of the final range will match the maximal value of StartRange 5733 // if the expression is decreasing and will be increased by Offset otherwise. 5734 APInt StartLower = StartRange.getLower(); 5735 APInt StartUpper = StartRange.getUpper() - 1; 5736 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5737 : (StartUpper + std::move(Offset)); 5738 5739 // It's possible that the new minimum/maximum value will fall into the initial 5740 // range (due to wrap around). This means that the expression can take any 5741 // value in this bitwidth, and we have to return full range. 5742 if (StartRange.contains(MovedBoundary)) 5743 return ConstantRange(BitWidth, /* isFullSet = */ true); 5744 5745 APInt NewLower = 5746 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5747 APInt NewUpper = 5748 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5749 NewUpper += 1; 5750 5751 // If we end up with full range, return a proper full range. 5752 if (NewLower == NewUpper) 5753 return ConstantRange(BitWidth, /* isFullSet = */ true); 5754 5755 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5756 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5757 } 5758 5759 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5760 const SCEV *Step, 5761 const SCEV *MaxBECount, 5762 unsigned BitWidth) { 5763 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5764 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5765 "Precondition!"); 5766 5767 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5768 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5769 5770 // First, consider step signed. 5771 ConstantRange StartSRange = getSignedRange(Start); 5772 ConstantRange StepSRange = getSignedRange(Step); 5773 5774 // If Step can be both positive and negative, we need to find ranges for the 5775 // maximum absolute step values in both directions and union them. 5776 ConstantRange SR = 5777 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5778 MaxBECountValue, BitWidth, /* Signed = */ true); 5779 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5780 StartSRange, MaxBECountValue, 5781 BitWidth, /* Signed = */ true)); 5782 5783 // Next, consider step unsigned. 5784 ConstantRange UR = getRangeForAffineARHelper( 5785 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5786 MaxBECountValue, BitWidth, /* Signed = */ false); 5787 5788 // Finally, intersect signed and unsigned ranges. 5789 return SR.intersectWith(UR); 5790 } 5791 5792 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5793 const SCEV *Step, 5794 const SCEV *MaxBECount, 5795 unsigned BitWidth) { 5796 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5797 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5798 5799 struct SelectPattern { 5800 Value *Condition = nullptr; 5801 APInt TrueValue; 5802 APInt FalseValue; 5803 5804 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5805 const SCEV *S) { 5806 Optional<unsigned> CastOp; 5807 APInt Offset(BitWidth, 0); 5808 5809 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5810 "Should be!"); 5811 5812 // Peel off a constant offset: 5813 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5814 // In the future we could consider being smarter here and handle 5815 // {Start+Step,+,Step} too. 5816 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5817 return; 5818 5819 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5820 S = SA->getOperand(1); 5821 } 5822 5823 // Peel off a cast operation 5824 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5825 CastOp = SCast->getSCEVType(); 5826 S = SCast->getOperand(); 5827 } 5828 5829 using namespace llvm::PatternMatch; 5830 5831 auto *SU = dyn_cast<SCEVUnknown>(S); 5832 const APInt *TrueVal, *FalseVal; 5833 if (!SU || 5834 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5835 m_APInt(FalseVal)))) { 5836 Condition = nullptr; 5837 return; 5838 } 5839 5840 TrueValue = *TrueVal; 5841 FalseValue = *FalseVal; 5842 5843 // Re-apply the cast we peeled off earlier 5844 if (CastOp.hasValue()) 5845 switch (*CastOp) { 5846 default: 5847 llvm_unreachable("Unknown SCEV cast type!"); 5848 5849 case scTruncate: 5850 TrueValue = TrueValue.trunc(BitWidth); 5851 FalseValue = FalseValue.trunc(BitWidth); 5852 break; 5853 case scZeroExtend: 5854 TrueValue = TrueValue.zext(BitWidth); 5855 FalseValue = FalseValue.zext(BitWidth); 5856 break; 5857 case scSignExtend: 5858 TrueValue = TrueValue.sext(BitWidth); 5859 FalseValue = FalseValue.sext(BitWidth); 5860 break; 5861 } 5862 5863 // Re-apply the constant offset we peeled off earlier 5864 TrueValue += Offset; 5865 FalseValue += Offset; 5866 } 5867 5868 bool isRecognized() { return Condition != nullptr; } 5869 }; 5870 5871 SelectPattern StartPattern(*this, BitWidth, Start); 5872 if (!StartPattern.isRecognized()) 5873 return ConstantRange(BitWidth, /* isFullSet = */ true); 5874 5875 SelectPattern StepPattern(*this, BitWidth, Step); 5876 if (!StepPattern.isRecognized()) 5877 return ConstantRange(BitWidth, /* isFullSet = */ true); 5878 5879 if (StartPattern.Condition != StepPattern.Condition) { 5880 // We don't handle this case today; but we could, by considering four 5881 // possibilities below instead of two. I'm not sure if there are cases where 5882 // that will help over what getRange already does, though. 5883 return ConstantRange(BitWidth, /* isFullSet = */ true); 5884 } 5885 5886 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5887 // construct arbitrary general SCEV expressions here. This function is called 5888 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5889 // say) can end up caching a suboptimal value. 5890 5891 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5892 // C2352 and C2512 (otherwise it isn't needed). 5893 5894 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5895 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5896 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5897 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5898 5899 ConstantRange TrueRange = 5900 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5901 ConstantRange FalseRange = 5902 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5903 5904 return TrueRange.unionWith(FalseRange); 5905 } 5906 5907 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5908 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5909 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5910 5911 // Return early if there are no flags to propagate to the SCEV. 5912 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5913 if (BinOp->hasNoUnsignedWrap()) 5914 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5915 if (BinOp->hasNoSignedWrap()) 5916 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5917 if (Flags == SCEV::FlagAnyWrap) 5918 return SCEV::FlagAnyWrap; 5919 5920 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5921 } 5922 5923 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5924 // Here we check that I is in the header of the innermost loop containing I, 5925 // since we only deal with instructions in the loop header. The actual loop we 5926 // need to check later will come from an add recurrence, but getting that 5927 // requires computing the SCEV of the operands, which can be expensive. This 5928 // check we can do cheaply to rule out some cases early. 5929 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5930 if (InnermostContainingLoop == nullptr || 5931 InnermostContainingLoop->getHeader() != I->getParent()) 5932 return false; 5933 5934 // Only proceed if we can prove that I does not yield poison. 5935 if (!programUndefinedIfFullPoison(I)) 5936 return false; 5937 5938 // At this point we know that if I is executed, then it does not wrap 5939 // according to at least one of NSW or NUW. If I is not executed, then we do 5940 // not know if the calculation that I represents would wrap. Multiple 5941 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5942 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5943 // derived from other instructions that map to the same SCEV. We cannot make 5944 // that guarantee for cases where I is not executed. So we need to find the 5945 // loop that I is considered in relation to and prove that I is executed for 5946 // every iteration of that loop. That implies that the value that I 5947 // calculates does not wrap anywhere in the loop, so then we can apply the 5948 // flags to the SCEV. 5949 // 5950 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5951 // from different loops, so that we know which loop to prove that I is 5952 // executed in. 5953 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5954 // I could be an extractvalue from a call to an overflow intrinsic. 5955 // TODO: We can do better here in some cases. 5956 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5957 return false; 5958 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5959 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5960 bool AllOtherOpsLoopInvariant = true; 5961 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5962 ++OtherOpIndex) { 5963 if (OtherOpIndex != OpIndex) { 5964 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5965 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5966 AllOtherOpsLoopInvariant = false; 5967 break; 5968 } 5969 } 5970 } 5971 if (AllOtherOpsLoopInvariant && 5972 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5973 return true; 5974 } 5975 } 5976 return false; 5977 } 5978 5979 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5980 // If we know that \c I can never be poison period, then that's enough. 5981 if (isSCEVExprNeverPoison(I)) 5982 return true; 5983 5984 // For an add recurrence specifically, we assume that infinite loops without 5985 // side effects are undefined behavior, and then reason as follows: 5986 // 5987 // If the add recurrence is poison in any iteration, it is poison on all 5988 // future iterations (since incrementing poison yields poison). If the result 5989 // of the add recurrence is fed into the loop latch condition and the loop 5990 // does not contain any throws or exiting blocks other than the latch, we now 5991 // have the ability to "choose" whether the backedge is taken or not (by 5992 // choosing a sufficiently evil value for the poison feeding into the branch) 5993 // for every iteration including and after the one in which \p I first became 5994 // poison. There are two possibilities (let's call the iteration in which \p 5995 // I first became poison as K): 5996 // 5997 // 1. In the set of iterations including and after K, the loop body executes 5998 // no side effects. In this case executing the backege an infinte number 5999 // of times will yield undefined behavior. 6000 // 6001 // 2. In the set of iterations including and after K, the loop body executes 6002 // at least one side effect. In this case, that specific instance of side 6003 // effect is control dependent on poison, which also yields undefined 6004 // behavior. 6005 6006 auto *ExitingBB = L->getExitingBlock(); 6007 auto *LatchBB = L->getLoopLatch(); 6008 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6009 return false; 6010 6011 SmallPtrSet<const Instruction *, 16> Pushed; 6012 SmallVector<const Instruction *, 8> PoisonStack; 6013 6014 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6015 // things that are known to be fully poison under that assumption go on the 6016 // PoisonStack. 6017 Pushed.insert(I); 6018 PoisonStack.push_back(I); 6019 6020 bool LatchControlDependentOnPoison = false; 6021 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6022 const Instruction *Poison = PoisonStack.pop_back_val(); 6023 6024 for (auto *PoisonUser : Poison->users()) { 6025 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6026 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6027 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6028 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6029 assert(BI->isConditional() && "Only possibility!"); 6030 if (BI->getParent() == LatchBB) { 6031 LatchControlDependentOnPoison = true; 6032 break; 6033 } 6034 } 6035 } 6036 } 6037 6038 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6039 } 6040 6041 ScalarEvolution::LoopProperties 6042 ScalarEvolution::getLoopProperties(const Loop *L) { 6043 using LoopProperties = ScalarEvolution::LoopProperties; 6044 6045 auto Itr = LoopPropertiesCache.find(L); 6046 if (Itr == LoopPropertiesCache.end()) { 6047 auto HasSideEffects = [](Instruction *I) { 6048 if (auto *SI = dyn_cast<StoreInst>(I)) 6049 return !SI->isSimple(); 6050 6051 return I->mayHaveSideEffects(); 6052 }; 6053 6054 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6055 /*HasNoSideEffects*/ true}; 6056 6057 for (auto *BB : L->getBlocks()) 6058 for (auto &I : *BB) { 6059 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6060 LP.HasNoAbnormalExits = false; 6061 if (HasSideEffects(&I)) 6062 LP.HasNoSideEffects = false; 6063 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6064 break; // We're already as pessimistic as we can get. 6065 } 6066 6067 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6068 assert(InsertPair.second && "We just checked!"); 6069 Itr = InsertPair.first; 6070 } 6071 6072 return Itr->second; 6073 } 6074 6075 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6076 if (!isSCEVable(V->getType())) 6077 return getUnknown(V); 6078 6079 if (Instruction *I = dyn_cast<Instruction>(V)) { 6080 // Don't attempt to analyze instructions in blocks that aren't 6081 // reachable. Such instructions don't matter, and they aren't required 6082 // to obey basic rules for definitions dominating uses which this 6083 // analysis depends on. 6084 if (!DT.isReachableFromEntry(I->getParent())) 6085 return getUnknown(V); 6086 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6087 return getConstant(CI); 6088 else if (isa<ConstantPointerNull>(V)) 6089 return getZero(V->getType()); 6090 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6091 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6092 else if (!isa<ConstantExpr>(V)) 6093 return getUnknown(V); 6094 6095 Operator *U = cast<Operator>(V); 6096 if (auto BO = MatchBinaryOp(U, DT)) { 6097 switch (BO->Opcode) { 6098 case Instruction::Add: { 6099 // The simple thing to do would be to just call getSCEV on both operands 6100 // and call getAddExpr with the result. However if we're looking at a 6101 // bunch of things all added together, this can be quite inefficient, 6102 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6103 // Instead, gather up all the operands and make a single getAddExpr call. 6104 // LLVM IR canonical form means we need only traverse the left operands. 6105 SmallVector<const SCEV *, 4> AddOps; 6106 do { 6107 if (BO->Op) { 6108 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6109 AddOps.push_back(OpSCEV); 6110 break; 6111 } 6112 6113 // If a NUW or NSW flag can be applied to the SCEV for this 6114 // addition, then compute the SCEV for this addition by itself 6115 // with a separate call to getAddExpr. We need to do that 6116 // instead of pushing the operands of the addition onto AddOps, 6117 // since the flags are only known to apply to this particular 6118 // addition - they may not apply to other additions that can be 6119 // formed with operands from AddOps. 6120 const SCEV *RHS = getSCEV(BO->RHS); 6121 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6122 if (Flags != SCEV::FlagAnyWrap) { 6123 const SCEV *LHS = getSCEV(BO->LHS); 6124 if (BO->Opcode == Instruction::Sub) 6125 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6126 else 6127 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6128 break; 6129 } 6130 } 6131 6132 if (BO->Opcode == Instruction::Sub) 6133 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6134 else 6135 AddOps.push_back(getSCEV(BO->RHS)); 6136 6137 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6138 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6139 NewBO->Opcode != Instruction::Sub)) { 6140 AddOps.push_back(getSCEV(BO->LHS)); 6141 break; 6142 } 6143 BO = NewBO; 6144 } while (true); 6145 6146 return getAddExpr(AddOps); 6147 } 6148 6149 case Instruction::Mul: { 6150 SmallVector<const SCEV *, 4> MulOps; 6151 do { 6152 if (BO->Op) { 6153 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6154 MulOps.push_back(OpSCEV); 6155 break; 6156 } 6157 6158 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6159 if (Flags != SCEV::FlagAnyWrap) { 6160 MulOps.push_back( 6161 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6162 break; 6163 } 6164 } 6165 6166 MulOps.push_back(getSCEV(BO->RHS)); 6167 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6168 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6169 MulOps.push_back(getSCEV(BO->LHS)); 6170 break; 6171 } 6172 BO = NewBO; 6173 } while (true); 6174 6175 return getMulExpr(MulOps); 6176 } 6177 case Instruction::UDiv: 6178 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6179 case Instruction::URem: 6180 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6181 case Instruction::Sub: { 6182 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6183 if (BO->Op) 6184 Flags = getNoWrapFlagsFromUB(BO->Op); 6185 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6186 } 6187 case Instruction::And: 6188 // For an expression like x&255 that merely masks off the high bits, 6189 // use zext(trunc(x)) as the SCEV expression. 6190 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6191 if (CI->isZero()) 6192 return getSCEV(BO->RHS); 6193 if (CI->isMinusOne()) 6194 return getSCEV(BO->LHS); 6195 const APInt &A = CI->getValue(); 6196 6197 // Instcombine's ShrinkDemandedConstant may strip bits out of 6198 // constants, obscuring what would otherwise be a low-bits mask. 6199 // Use computeKnownBits to compute what ShrinkDemandedConstant 6200 // knew about to reconstruct a low-bits mask value. 6201 unsigned LZ = A.countLeadingZeros(); 6202 unsigned TZ = A.countTrailingZeros(); 6203 unsigned BitWidth = A.getBitWidth(); 6204 KnownBits Known(BitWidth); 6205 computeKnownBits(BO->LHS, Known, getDataLayout(), 6206 0, &AC, nullptr, &DT); 6207 6208 APInt EffectiveMask = 6209 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6210 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6211 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6212 const SCEV *LHS = getSCEV(BO->LHS); 6213 const SCEV *ShiftedLHS = nullptr; 6214 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6215 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6216 // For an expression like (x * 8) & 8, simplify the multiply. 6217 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6218 unsigned GCD = std::min(MulZeros, TZ); 6219 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6220 SmallVector<const SCEV*, 4> MulOps; 6221 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6222 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6223 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6224 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6225 } 6226 } 6227 if (!ShiftedLHS) 6228 ShiftedLHS = getUDivExpr(LHS, MulCount); 6229 return getMulExpr( 6230 getZeroExtendExpr( 6231 getTruncateExpr(ShiftedLHS, 6232 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6233 BO->LHS->getType()), 6234 MulCount); 6235 } 6236 } 6237 break; 6238 6239 case Instruction::Or: 6240 // If the RHS of the Or is a constant, we may have something like: 6241 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6242 // optimizations will transparently handle this case. 6243 // 6244 // In order for this transformation to be safe, the LHS must be of the 6245 // form X*(2^n) and the Or constant must be less than 2^n. 6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6247 const SCEV *LHS = getSCEV(BO->LHS); 6248 const APInt &CIVal = CI->getValue(); 6249 if (GetMinTrailingZeros(LHS) >= 6250 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6251 // Build a plain add SCEV. 6252 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6253 // If the LHS of the add was an addrec and it has no-wrap flags, 6254 // transfer the no-wrap flags, since an or won't introduce a wrap. 6255 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6256 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6257 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6258 OldAR->getNoWrapFlags()); 6259 } 6260 return S; 6261 } 6262 } 6263 break; 6264 6265 case Instruction::Xor: 6266 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6267 // If the RHS of xor is -1, then this is a not operation. 6268 if (CI->isMinusOne()) 6269 return getNotSCEV(getSCEV(BO->LHS)); 6270 6271 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6272 // This is a variant of the check for xor with -1, and it handles 6273 // the case where instcombine has trimmed non-demanded bits out 6274 // of an xor with -1. 6275 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6276 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6277 if (LBO->getOpcode() == Instruction::And && 6278 LCI->getValue() == CI->getValue()) 6279 if (const SCEVZeroExtendExpr *Z = 6280 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6281 Type *UTy = BO->LHS->getType(); 6282 const SCEV *Z0 = Z->getOperand(); 6283 Type *Z0Ty = Z0->getType(); 6284 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6285 6286 // If C is a low-bits mask, the zero extend is serving to 6287 // mask off the high bits. Complement the operand and 6288 // re-apply the zext. 6289 if (CI->getValue().isMask(Z0TySize)) 6290 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6291 6292 // If C is a single bit, it may be in the sign-bit position 6293 // before the zero-extend. In this case, represent the xor 6294 // using an add, which is equivalent, and re-apply the zext. 6295 APInt Trunc = CI->getValue().trunc(Z0TySize); 6296 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6297 Trunc.isSignMask()) 6298 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6299 UTy); 6300 } 6301 } 6302 break; 6303 6304 case Instruction::Shl: 6305 // Turn shift left of a constant amount into a multiply. 6306 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6307 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6308 6309 // If the shift count is not less than the bitwidth, the result of 6310 // the shift is undefined. Don't try to analyze it, because the 6311 // resolution chosen here may differ from the resolution chosen in 6312 // other parts of the compiler. 6313 if (SA->getValue().uge(BitWidth)) 6314 break; 6315 6316 // It is currently not resolved how to interpret NSW for left 6317 // shift by BitWidth - 1, so we avoid applying flags in that 6318 // case. Remove this check (or this comment) once the situation 6319 // is resolved. See 6320 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6321 // and http://reviews.llvm.org/D8890 . 6322 auto Flags = SCEV::FlagAnyWrap; 6323 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6324 Flags = getNoWrapFlagsFromUB(BO->Op); 6325 6326 Constant *X = ConstantInt::get( 6327 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6328 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6329 } 6330 break; 6331 6332 case Instruction::AShr: { 6333 // AShr X, C, where C is a constant. 6334 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6335 if (!CI) 6336 break; 6337 6338 Type *OuterTy = BO->LHS->getType(); 6339 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6340 // If the shift count is not less than the bitwidth, the result of 6341 // the shift is undefined. Don't try to analyze it, because the 6342 // resolution chosen here may differ from the resolution chosen in 6343 // other parts of the compiler. 6344 if (CI->getValue().uge(BitWidth)) 6345 break; 6346 6347 if (CI->isZero()) 6348 return getSCEV(BO->LHS); // shift by zero --> noop 6349 6350 uint64_t AShrAmt = CI->getZExtValue(); 6351 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6352 6353 Operator *L = dyn_cast<Operator>(BO->LHS); 6354 if (L && L->getOpcode() == Instruction::Shl) { 6355 // X = Shl A, n 6356 // Y = AShr X, m 6357 // Both n and m are constant. 6358 6359 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6360 if (L->getOperand(1) == BO->RHS) 6361 // For a two-shift sext-inreg, i.e. n = m, 6362 // use sext(trunc(x)) as the SCEV expression. 6363 return getSignExtendExpr( 6364 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6365 6366 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6367 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6368 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6369 if (ShlAmt > AShrAmt) { 6370 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6371 // expression. We already checked that ShlAmt < BitWidth, so 6372 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6373 // ShlAmt - AShrAmt < Amt. 6374 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6375 ShlAmt - AShrAmt); 6376 return getSignExtendExpr( 6377 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6378 getConstant(Mul)), OuterTy); 6379 } 6380 } 6381 } 6382 break; 6383 } 6384 } 6385 } 6386 6387 switch (U->getOpcode()) { 6388 case Instruction::Trunc: 6389 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6390 6391 case Instruction::ZExt: 6392 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6393 6394 case Instruction::SExt: 6395 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6396 // The NSW flag of a subtract does not always survive the conversion to 6397 // A + (-1)*B. By pushing sign extension onto its operands we are much 6398 // more likely to preserve NSW and allow later AddRec optimisations. 6399 // 6400 // NOTE: This is effectively duplicating this logic from getSignExtend: 6401 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6402 // but by that point the NSW information has potentially been lost. 6403 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6404 Type *Ty = U->getType(); 6405 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6406 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6407 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6408 } 6409 } 6410 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6411 6412 case Instruction::BitCast: 6413 // BitCasts are no-op casts so we just eliminate the cast. 6414 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6415 return getSCEV(U->getOperand(0)); 6416 break; 6417 6418 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6419 // lead to pointer expressions which cannot safely be expanded to GEPs, 6420 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6421 // simplifying integer expressions. 6422 6423 case Instruction::GetElementPtr: 6424 return createNodeForGEP(cast<GEPOperator>(U)); 6425 6426 case Instruction::PHI: 6427 return createNodeForPHI(cast<PHINode>(U)); 6428 6429 case Instruction::Select: 6430 // U can also be a select constant expr, which let fall through. Since 6431 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6432 // constant expressions cannot have instructions as operands, we'd have 6433 // returned getUnknown for a select constant expressions anyway. 6434 if (isa<Instruction>(U)) 6435 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6436 U->getOperand(1), U->getOperand(2)); 6437 break; 6438 6439 case Instruction::Call: 6440 case Instruction::Invoke: 6441 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6442 return getSCEV(RV); 6443 break; 6444 } 6445 6446 return getUnknown(V); 6447 } 6448 6449 //===----------------------------------------------------------------------===// 6450 // Iteration Count Computation Code 6451 // 6452 6453 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6454 if (!ExitCount) 6455 return 0; 6456 6457 ConstantInt *ExitConst = ExitCount->getValue(); 6458 6459 // Guard against huge trip counts. 6460 if (ExitConst->getValue().getActiveBits() > 32) 6461 return 0; 6462 6463 // In case of integer overflow, this returns 0, which is correct. 6464 return ((unsigned)ExitConst->getZExtValue()) + 1; 6465 } 6466 6467 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6468 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6469 return getSmallConstantTripCount(L, ExitingBB); 6470 6471 // No trip count information for multiple exits. 6472 return 0; 6473 } 6474 6475 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6476 BasicBlock *ExitingBlock) { 6477 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6478 assert(L->isLoopExiting(ExitingBlock) && 6479 "Exiting block must actually branch out of the loop!"); 6480 const SCEVConstant *ExitCount = 6481 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6482 return getConstantTripCount(ExitCount); 6483 } 6484 6485 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6486 const auto *MaxExitCount = 6487 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6488 return getConstantTripCount(MaxExitCount); 6489 } 6490 6491 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6492 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6493 return getSmallConstantTripMultiple(L, ExitingBB); 6494 6495 // No trip multiple information for multiple exits. 6496 return 0; 6497 } 6498 6499 /// Returns the largest constant divisor of the trip count of this loop as a 6500 /// normal unsigned value, if possible. This means that the actual trip count is 6501 /// always a multiple of the returned value (don't forget the trip count could 6502 /// very well be zero as well!). 6503 /// 6504 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6505 /// multiple of a constant (which is also the case if the trip count is simply 6506 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6507 /// if the trip count is very large (>= 2^32). 6508 /// 6509 /// As explained in the comments for getSmallConstantTripCount, this assumes 6510 /// that control exits the loop via ExitingBlock. 6511 unsigned 6512 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6513 BasicBlock *ExitingBlock) { 6514 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6515 assert(L->isLoopExiting(ExitingBlock) && 6516 "Exiting block must actually branch out of the loop!"); 6517 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6518 if (ExitCount == getCouldNotCompute()) 6519 return 1; 6520 6521 // Get the trip count from the BE count by adding 1. 6522 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6523 6524 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6525 if (!TC) 6526 // Attempt to factor more general cases. Returns the greatest power of 6527 // two divisor. If overflow happens, the trip count expression is still 6528 // divisible by the greatest power of 2 divisor returned. 6529 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6530 6531 ConstantInt *Result = TC->getValue(); 6532 6533 // Guard against huge trip counts (this requires checking 6534 // for zero to handle the case where the trip count == -1 and the 6535 // addition wraps). 6536 if (!Result || Result->getValue().getActiveBits() > 32 || 6537 Result->getValue().getActiveBits() == 0) 6538 return 1; 6539 6540 return (unsigned)Result->getZExtValue(); 6541 } 6542 6543 /// Get the expression for the number of loop iterations for which this loop is 6544 /// guaranteed not to exit via ExitingBlock. Otherwise return 6545 /// SCEVCouldNotCompute. 6546 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6547 BasicBlock *ExitingBlock) { 6548 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6549 } 6550 6551 const SCEV * 6552 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6553 SCEVUnionPredicate &Preds) { 6554 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6555 } 6556 6557 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6558 return getBackedgeTakenInfo(L).getExact(L, this); 6559 } 6560 6561 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6562 /// known never to be less than the actual backedge taken count. 6563 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6564 return getBackedgeTakenInfo(L).getMax(this); 6565 } 6566 6567 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6568 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6569 } 6570 6571 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6572 static void 6573 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6574 BasicBlock *Header = L->getHeader(); 6575 6576 // Push all Loop-header PHIs onto the Worklist stack. 6577 for (PHINode &PN : Header->phis()) 6578 Worklist.push_back(&PN); 6579 } 6580 6581 const ScalarEvolution::BackedgeTakenInfo & 6582 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6583 auto &BTI = getBackedgeTakenInfo(L); 6584 if (BTI.hasFullInfo()) 6585 return BTI; 6586 6587 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6588 6589 if (!Pair.second) 6590 return Pair.first->second; 6591 6592 BackedgeTakenInfo Result = 6593 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6594 6595 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6596 } 6597 6598 const ScalarEvolution::BackedgeTakenInfo & 6599 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6600 // Initially insert an invalid entry for this loop. If the insertion 6601 // succeeds, proceed to actually compute a backedge-taken count and 6602 // update the value. The temporary CouldNotCompute value tells SCEV 6603 // code elsewhere that it shouldn't attempt to request a new 6604 // backedge-taken count, which could result in infinite recursion. 6605 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6606 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6607 if (!Pair.second) 6608 return Pair.first->second; 6609 6610 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6611 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6612 // must be cleared in this scope. 6613 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6614 6615 // In product build, there are no usage of statistic. 6616 (void)NumTripCountsComputed; 6617 (void)NumTripCountsNotComputed; 6618 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6619 const SCEV *BEExact = Result.getExact(L, this); 6620 if (BEExact != getCouldNotCompute()) { 6621 assert(isLoopInvariant(BEExact, L) && 6622 isLoopInvariant(Result.getMax(this), L) && 6623 "Computed backedge-taken count isn't loop invariant for loop!"); 6624 ++NumTripCountsComputed; 6625 } 6626 else if (Result.getMax(this) == getCouldNotCompute() && 6627 isa<PHINode>(L->getHeader()->begin())) { 6628 // Only count loops that have phi nodes as not being computable. 6629 ++NumTripCountsNotComputed; 6630 } 6631 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6632 6633 // Now that we know more about the trip count for this loop, forget any 6634 // existing SCEV values for PHI nodes in this loop since they are only 6635 // conservative estimates made without the benefit of trip count 6636 // information. This is similar to the code in forgetLoop, except that 6637 // it handles SCEVUnknown PHI nodes specially. 6638 if (Result.hasAnyInfo()) { 6639 SmallVector<Instruction *, 16> Worklist; 6640 PushLoopPHIs(L, Worklist); 6641 6642 SmallPtrSet<Instruction *, 8> Discovered; 6643 while (!Worklist.empty()) { 6644 Instruction *I = Worklist.pop_back_val(); 6645 6646 ValueExprMapType::iterator It = 6647 ValueExprMap.find_as(static_cast<Value *>(I)); 6648 if (It != ValueExprMap.end()) { 6649 const SCEV *Old = It->second; 6650 6651 // SCEVUnknown for a PHI either means that it has an unrecognized 6652 // structure, or it's a PHI that's in the progress of being computed 6653 // by createNodeForPHI. In the former case, additional loop trip 6654 // count information isn't going to change anything. In the later 6655 // case, createNodeForPHI will perform the necessary updates on its 6656 // own when it gets to that point. 6657 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6658 eraseValueFromMap(It->first); 6659 forgetMemoizedResults(Old); 6660 } 6661 if (PHINode *PN = dyn_cast<PHINode>(I)) 6662 ConstantEvolutionLoopExitValue.erase(PN); 6663 } 6664 6665 // Since we don't need to invalidate anything for correctness and we're 6666 // only invalidating to make SCEV's results more precise, we get to stop 6667 // early to avoid invalidating too much. This is especially important in 6668 // cases like: 6669 // 6670 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6671 // loop0: 6672 // %pn0 = phi 6673 // ... 6674 // loop1: 6675 // %pn1 = phi 6676 // ... 6677 // 6678 // where both loop0 and loop1's backedge taken count uses the SCEV 6679 // expression for %v. If we don't have the early stop below then in cases 6680 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6681 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6682 // count for loop1, effectively nullifying SCEV's trip count cache. 6683 for (auto *U : I->users()) 6684 if (auto *I = dyn_cast<Instruction>(U)) { 6685 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6686 if (LoopForUser && L->contains(LoopForUser) && 6687 Discovered.insert(I).second) 6688 Worklist.push_back(I); 6689 } 6690 } 6691 } 6692 6693 // Re-lookup the insert position, since the call to 6694 // computeBackedgeTakenCount above could result in a 6695 // recusive call to getBackedgeTakenInfo (on a different 6696 // loop), which would invalidate the iterator computed 6697 // earlier. 6698 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6699 } 6700 6701 void ScalarEvolution::forgetLoop(const Loop *L) { 6702 // Drop any stored trip count value. 6703 auto RemoveLoopFromBackedgeMap = 6704 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6705 auto BTCPos = Map.find(L); 6706 if (BTCPos != Map.end()) { 6707 BTCPos->second.clear(); 6708 Map.erase(BTCPos); 6709 } 6710 }; 6711 6712 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6713 SmallVector<Instruction *, 32> Worklist; 6714 SmallPtrSet<Instruction *, 16> Visited; 6715 6716 // Iterate over all the loops and sub-loops to drop SCEV information. 6717 while (!LoopWorklist.empty()) { 6718 auto *CurrL = LoopWorklist.pop_back_val(); 6719 6720 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6721 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6722 6723 // Drop information about predicated SCEV rewrites for this loop. 6724 for (auto I = PredicatedSCEVRewrites.begin(); 6725 I != PredicatedSCEVRewrites.end();) { 6726 std::pair<const SCEV *, const Loop *> Entry = I->first; 6727 if (Entry.second == CurrL) 6728 PredicatedSCEVRewrites.erase(I++); 6729 else 6730 ++I; 6731 } 6732 6733 auto LoopUsersItr = LoopUsers.find(CurrL); 6734 if (LoopUsersItr != LoopUsers.end()) { 6735 for (auto *S : LoopUsersItr->second) 6736 forgetMemoizedResults(S); 6737 LoopUsers.erase(LoopUsersItr); 6738 } 6739 6740 // Drop information about expressions based on loop-header PHIs. 6741 PushLoopPHIs(CurrL, Worklist); 6742 6743 while (!Worklist.empty()) { 6744 Instruction *I = Worklist.pop_back_val(); 6745 if (!Visited.insert(I).second) 6746 continue; 6747 6748 ValueExprMapType::iterator It = 6749 ValueExprMap.find_as(static_cast<Value *>(I)); 6750 if (It != ValueExprMap.end()) { 6751 eraseValueFromMap(It->first); 6752 forgetMemoizedResults(It->second); 6753 if (PHINode *PN = dyn_cast<PHINode>(I)) 6754 ConstantEvolutionLoopExitValue.erase(PN); 6755 } 6756 6757 PushDefUseChildren(I, Worklist); 6758 } 6759 6760 LoopPropertiesCache.erase(CurrL); 6761 // Forget all contained loops too, to avoid dangling entries in the 6762 // ValuesAtScopes map. 6763 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6764 } 6765 } 6766 6767 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6768 while (Loop *Parent = L->getParentLoop()) 6769 L = Parent; 6770 forgetLoop(L); 6771 } 6772 6773 void ScalarEvolution::forgetValue(Value *V) { 6774 Instruction *I = dyn_cast<Instruction>(V); 6775 if (!I) return; 6776 6777 // Drop information about expressions based on loop-header PHIs. 6778 SmallVector<Instruction *, 16> Worklist; 6779 Worklist.push_back(I); 6780 6781 SmallPtrSet<Instruction *, 8> Visited; 6782 while (!Worklist.empty()) { 6783 I = Worklist.pop_back_val(); 6784 if (!Visited.insert(I).second) 6785 continue; 6786 6787 ValueExprMapType::iterator It = 6788 ValueExprMap.find_as(static_cast<Value *>(I)); 6789 if (It != ValueExprMap.end()) { 6790 eraseValueFromMap(It->first); 6791 forgetMemoizedResults(It->second); 6792 if (PHINode *PN = dyn_cast<PHINode>(I)) 6793 ConstantEvolutionLoopExitValue.erase(PN); 6794 } 6795 6796 PushDefUseChildren(I, Worklist); 6797 } 6798 } 6799 6800 /// Get the exact loop backedge taken count considering all loop exits. A 6801 /// computable result can only be returned for loops with all exiting blocks 6802 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6803 /// is never skipped. This is a valid assumption as long as the loop exits via 6804 /// that test. For precise results, it is the caller's responsibility to specify 6805 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6806 const SCEV * 6807 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6808 SCEVUnionPredicate *Preds) const { 6809 // If any exits were not computable, the loop is not computable. 6810 if (!isComplete() || ExitNotTaken.empty()) 6811 return SE->getCouldNotCompute(); 6812 6813 const BasicBlock *Latch = L->getLoopLatch(); 6814 // All exiting blocks we have collected must dominate the only backedge. 6815 if (!Latch) 6816 return SE->getCouldNotCompute(); 6817 6818 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6819 // count is simply a minimum out of all these calculated exit counts. 6820 SmallVector<const SCEV *, 2> Ops; 6821 for (auto &ENT : ExitNotTaken) { 6822 const SCEV *BECount = ENT.ExactNotTaken; 6823 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6824 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6825 "We should only have known counts for exiting blocks that dominate " 6826 "latch!"); 6827 6828 Ops.push_back(BECount); 6829 6830 if (Preds && !ENT.hasAlwaysTruePredicate()) 6831 Preds->add(ENT.Predicate.get()); 6832 6833 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6834 "Predicate should be always true!"); 6835 } 6836 6837 return SE->getUMinFromMismatchedTypes(Ops); 6838 } 6839 6840 /// Get the exact not taken count for this loop exit. 6841 const SCEV * 6842 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6843 ScalarEvolution *SE) const { 6844 for (auto &ENT : ExitNotTaken) 6845 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6846 return ENT.ExactNotTaken; 6847 6848 return SE->getCouldNotCompute(); 6849 } 6850 6851 /// getMax - Get the max backedge taken count for the loop. 6852 const SCEV * 6853 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6854 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6855 return !ENT.hasAlwaysTruePredicate(); 6856 }; 6857 6858 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6859 return SE->getCouldNotCompute(); 6860 6861 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6862 "No point in having a non-constant max backedge taken count!"); 6863 return getMax(); 6864 } 6865 6866 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6867 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6868 return !ENT.hasAlwaysTruePredicate(); 6869 }; 6870 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6871 } 6872 6873 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6874 ScalarEvolution *SE) const { 6875 if (getMax() && getMax() != SE->getCouldNotCompute() && 6876 SE->hasOperand(getMax(), S)) 6877 return true; 6878 6879 for (auto &ENT : ExitNotTaken) 6880 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6881 SE->hasOperand(ENT.ExactNotTaken, S)) 6882 return true; 6883 6884 return false; 6885 } 6886 6887 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6888 : ExactNotTaken(E), MaxNotTaken(E) { 6889 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6890 isa<SCEVConstant>(MaxNotTaken)) && 6891 "No point in having a non-constant max backedge taken count!"); 6892 } 6893 6894 ScalarEvolution::ExitLimit::ExitLimit( 6895 const SCEV *E, const SCEV *M, bool MaxOrZero, 6896 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6897 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6898 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6899 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6900 "Exact is not allowed to be less precise than Max"); 6901 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6902 isa<SCEVConstant>(MaxNotTaken)) && 6903 "No point in having a non-constant max backedge taken count!"); 6904 for (auto *PredSet : PredSetList) 6905 for (auto *P : *PredSet) 6906 addPredicate(P); 6907 } 6908 6909 ScalarEvolution::ExitLimit::ExitLimit( 6910 const SCEV *E, const SCEV *M, bool MaxOrZero, 6911 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6912 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6913 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6914 isa<SCEVConstant>(MaxNotTaken)) && 6915 "No point in having a non-constant max backedge taken count!"); 6916 } 6917 6918 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6919 bool MaxOrZero) 6920 : ExitLimit(E, M, MaxOrZero, None) { 6921 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6922 isa<SCEVConstant>(MaxNotTaken)) && 6923 "No point in having a non-constant max backedge taken count!"); 6924 } 6925 6926 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6927 /// computable exit into a persistent ExitNotTakenInfo array. 6928 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6929 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6930 &&ExitCounts, 6931 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6932 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6933 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6934 6935 ExitNotTaken.reserve(ExitCounts.size()); 6936 std::transform( 6937 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6938 [&](const EdgeExitInfo &EEI) { 6939 BasicBlock *ExitBB = EEI.first; 6940 const ExitLimit &EL = EEI.second; 6941 if (EL.Predicates.empty()) 6942 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6943 6944 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6945 for (auto *Pred : EL.Predicates) 6946 Predicate->add(Pred); 6947 6948 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6949 }); 6950 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6951 "No point in having a non-constant max backedge taken count!"); 6952 } 6953 6954 /// Invalidate this result and free the ExitNotTakenInfo array. 6955 void ScalarEvolution::BackedgeTakenInfo::clear() { 6956 ExitNotTaken.clear(); 6957 } 6958 6959 /// Compute the number of times the backedge of the specified loop will execute. 6960 ScalarEvolution::BackedgeTakenInfo 6961 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6962 bool AllowPredicates) { 6963 SmallVector<BasicBlock *, 8> ExitingBlocks; 6964 L->getExitingBlocks(ExitingBlocks); 6965 6966 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6967 6968 SmallVector<EdgeExitInfo, 4> ExitCounts; 6969 bool CouldComputeBECount = true; 6970 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6971 const SCEV *MustExitMaxBECount = nullptr; 6972 const SCEV *MayExitMaxBECount = nullptr; 6973 bool MustExitMaxOrZero = false; 6974 6975 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6976 // and compute maxBECount. 6977 // Do a union of all the predicates here. 6978 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6979 BasicBlock *ExitBB = ExitingBlocks[i]; 6980 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6981 6982 assert((AllowPredicates || EL.Predicates.empty()) && 6983 "Predicated exit limit when predicates are not allowed!"); 6984 6985 // 1. For each exit that can be computed, add an entry to ExitCounts. 6986 // CouldComputeBECount is true only if all exits can be computed. 6987 if (EL.ExactNotTaken == getCouldNotCompute()) 6988 // We couldn't compute an exact value for this exit, so 6989 // we won't be able to compute an exact value for the loop. 6990 CouldComputeBECount = false; 6991 else 6992 ExitCounts.emplace_back(ExitBB, EL); 6993 6994 // 2. Derive the loop's MaxBECount from each exit's max number of 6995 // non-exiting iterations. Partition the loop exits into two kinds: 6996 // LoopMustExits and LoopMayExits. 6997 // 6998 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6999 // is a LoopMayExit. If any computable LoopMustExit is found, then 7000 // MaxBECount is the minimum EL.MaxNotTaken of computable 7001 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7002 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7003 // computable EL.MaxNotTaken. 7004 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7005 DT.dominates(ExitBB, Latch)) { 7006 if (!MustExitMaxBECount) { 7007 MustExitMaxBECount = EL.MaxNotTaken; 7008 MustExitMaxOrZero = EL.MaxOrZero; 7009 } else { 7010 MustExitMaxBECount = 7011 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7012 } 7013 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7014 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7015 MayExitMaxBECount = EL.MaxNotTaken; 7016 else { 7017 MayExitMaxBECount = 7018 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7019 } 7020 } 7021 } 7022 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7023 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7024 // The loop backedge will be taken the maximum or zero times if there's 7025 // a single exit that must be taken the maximum or zero times. 7026 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7027 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7028 MaxBECount, MaxOrZero); 7029 } 7030 7031 ScalarEvolution::ExitLimit 7032 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7033 bool AllowPredicates) { 7034 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7035 // If our exiting block does not dominate the latch, then its connection with 7036 // loop's exit limit may be far from trivial. 7037 const BasicBlock *Latch = L->getLoopLatch(); 7038 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7039 return getCouldNotCompute(); 7040 7041 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7042 TerminatorInst *Term = ExitingBlock->getTerminator(); 7043 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7044 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7045 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7046 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7047 "It should have one successor in loop and one exit block!"); 7048 // Proceed to the next level to examine the exit condition expression. 7049 return computeExitLimitFromCond( 7050 L, BI->getCondition(), ExitIfTrue, 7051 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7052 } 7053 7054 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7055 // For switch, make sure that there is a single exit from the loop. 7056 BasicBlock *Exit = nullptr; 7057 for (auto *SBB : successors(ExitingBlock)) 7058 if (!L->contains(SBB)) { 7059 if (Exit) // Multiple exit successors. 7060 return getCouldNotCompute(); 7061 Exit = SBB; 7062 } 7063 assert(Exit && "Exiting block must have at least one exit"); 7064 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7065 /*ControlsExit=*/IsOnlyExit); 7066 } 7067 7068 return getCouldNotCompute(); 7069 } 7070 7071 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7072 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7073 bool ControlsExit, bool AllowPredicates) { 7074 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7075 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7076 ControlsExit, AllowPredicates); 7077 } 7078 7079 Optional<ScalarEvolution::ExitLimit> 7080 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7081 bool ExitIfTrue, bool ControlsExit, 7082 bool AllowPredicates) { 7083 (void)this->L; 7084 (void)this->ExitIfTrue; 7085 (void)this->AllowPredicates; 7086 7087 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7088 this->AllowPredicates == AllowPredicates && 7089 "Variance in assumed invariant key components!"); 7090 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7091 if (Itr == TripCountMap.end()) 7092 return None; 7093 return Itr->second; 7094 } 7095 7096 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7097 bool ExitIfTrue, 7098 bool ControlsExit, 7099 bool AllowPredicates, 7100 const ExitLimit &EL) { 7101 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7102 this->AllowPredicates == AllowPredicates && 7103 "Variance in assumed invariant key components!"); 7104 7105 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7106 assert(InsertResult.second && "Expected successful insertion!"); 7107 (void)InsertResult; 7108 (void)ExitIfTrue; 7109 } 7110 7111 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7112 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7113 bool ControlsExit, bool AllowPredicates) { 7114 7115 if (auto MaybeEL = 7116 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7117 return *MaybeEL; 7118 7119 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7120 ControlsExit, AllowPredicates); 7121 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7122 return EL; 7123 } 7124 7125 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7126 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7127 bool ControlsExit, bool AllowPredicates) { 7128 // Check if the controlling expression for this loop is an And or Or. 7129 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7130 if (BO->getOpcode() == Instruction::And) { 7131 // Recurse on the operands of the and. 7132 bool EitherMayExit = !ExitIfTrue; 7133 ExitLimit EL0 = computeExitLimitFromCondCached( 7134 Cache, L, BO->getOperand(0), ExitIfTrue, 7135 ControlsExit && !EitherMayExit, AllowPredicates); 7136 ExitLimit EL1 = computeExitLimitFromCondCached( 7137 Cache, L, BO->getOperand(1), ExitIfTrue, 7138 ControlsExit && !EitherMayExit, AllowPredicates); 7139 const SCEV *BECount = getCouldNotCompute(); 7140 const SCEV *MaxBECount = getCouldNotCompute(); 7141 if (EitherMayExit) { 7142 // Both conditions must be true for the loop to continue executing. 7143 // Choose the less conservative count. 7144 if (EL0.ExactNotTaken == getCouldNotCompute() || 7145 EL1.ExactNotTaken == getCouldNotCompute()) 7146 BECount = getCouldNotCompute(); 7147 else 7148 BECount = 7149 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7150 if (EL0.MaxNotTaken == getCouldNotCompute()) 7151 MaxBECount = EL1.MaxNotTaken; 7152 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7153 MaxBECount = EL0.MaxNotTaken; 7154 else 7155 MaxBECount = 7156 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7157 } else { 7158 // Both conditions must be true at the same time for the loop to exit. 7159 // For now, be conservative. 7160 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7161 MaxBECount = EL0.MaxNotTaken; 7162 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7163 BECount = EL0.ExactNotTaken; 7164 } 7165 7166 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7167 // to be more aggressive when computing BECount than when computing 7168 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7169 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7170 // to not. 7171 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7172 !isa<SCEVCouldNotCompute>(BECount)) 7173 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7174 7175 return ExitLimit(BECount, MaxBECount, false, 7176 {&EL0.Predicates, &EL1.Predicates}); 7177 } 7178 if (BO->getOpcode() == Instruction::Or) { 7179 // Recurse on the operands of the or. 7180 bool EitherMayExit = ExitIfTrue; 7181 ExitLimit EL0 = computeExitLimitFromCondCached( 7182 Cache, L, BO->getOperand(0), ExitIfTrue, 7183 ControlsExit && !EitherMayExit, AllowPredicates); 7184 ExitLimit EL1 = computeExitLimitFromCondCached( 7185 Cache, L, BO->getOperand(1), ExitIfTrue, 7186 ControlsExit && !EitherMayExit, AllowPredicates); 7187 const SCEV *BECount = getCouldNotCompute(); 7188 const SCEV *MaxBECount = getCouldNotCompute(); 7189 if (EitherMayExit) { 7190 // Both conditions must be false for the loop to continue executing. 7191 // Choose the less conservative count. 7192 if (EL0.ExactNotTaken == getCouldNotCompute() || 7193 EL1.ExactNotTaken == getCouldNotCompute()) 7194 BECount = getCouldNotCompute(); 7195 else 7196 BECount = 7197 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7198 if (EL0.MaxNotTaken == getCouldNotCompute()) 7199 MaxBECount = EL1.MaxNotTaken; 7200 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7201 MaxBECount = EL0.MaxNotTaken; 7202 else 7203 MaxBECount = 7204 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7205 } else { 7206 // Both conditions must be false at the same time for the loop to exit. 7207 // For now, be conservative. 7208 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7209 MaxBECount = EL0.MaxNotTaken; 7210 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7211 BECount = EL0.ExactNotTaken; 7212 } 7213 7214 return ExitLimit(BECount, MaxBECount, false, 7215 {&EL0.Predicates, &EL1.Predicates}); 7216 } 7217 } 7218 7219 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7220 // Proceed to the next level to examine the icmp. 7221 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7222 ExitLimit EL = 7223 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7224 if (EL.hasFullInfo() || !AllowPredicates) 7225 return EL; 7226 7227 // Try again, but use SCEV predicates this time. 7228 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7229 /*AllowPredicates=*/true); 7230 } 7231 7232 // Check for a constant condition. These are normally stripped out by 7233 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7234 // preserve the CFG and is temporarily leaving constant conditions 7235 // in place. 7236 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7237 if (ExitIfTrue == !CI->getZExtValue()) 7238 // The backedge is always taken. 7239 return getCouldNotCompute(); 7240 else 7241 // The backedge is never taken. 7242 return getZero(CI->getType()); 7243 } 7244 7245 // If it's not an integer or pointer comparison then compute it the hard way. 7246 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7247 } 7248 7249 ScalarEvolution::ExitLimit 7250 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7251 ICmpInst *ExitCond, 7252 bool ExitIfTrue, 7253 bool ControlsExit, 7254 bool AllowPredicates) { 7255 // If the condition was exit on true, convert the condition to exit on false 7256 ICmpInst::Predicate Pred; 7257 if (!ExitIfTrue) 7258 Pred = ExitCond->getPredicate(); 7259 else 7260 Pred = ExitCond->getInversePredicate(); 7261 const ICmpInst::Predicate OriginalPred = Pred; 7262 7263 // Handle common loops like: for (X = "string"; *X; ++X) 7264 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7265 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7266 ExitLimit ItCnt = 7267 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7268 if (ItCnt.hasAnyInfo()) 7269 return ItCnt; 7270 } 7271 7272 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7273 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7274 7275 // Try to evaluate any dependencies out of the loop. 7276 LHS = getSCEVAtScope(LHS, L); 7277 RHS = getSCEVAtScope(RHS, L); 7278 7279 // At this point, we would like to compute how many iterations of the 7280 // loop the predicate will return true for these inputs. 7281 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7282 // If there is a loop-invariant, force it into the RHS. 7283 std::swap(LHS, RHS); 7284 Pred = ICmpInst::getSwappedPredicate(Pred); 7285 } 7286 7287 // Simplify the operands before analyzing them. 7288 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7289 7290 // If we have a comparison of a chrec against a constant, try to use value 7291 // ranges to answer this query. 7292 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7293 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7294 if (AddRec->getLoop() == L) { 7295 // Form the constant range. 7296 ConstantRange CompRange = 7297 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7298 7299 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7300 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7301 } 7302 7303 switch (Pred) { 7304 case ICmpInst::ICMP_NE: { // while (X != Y) 7305 // Convert to: while (X-Y != 0) 7306 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7307 AllowPredicates); 7308 if (EL.hasAnyInfo()) return EL; 7309 break; 7310 } 7311 case ICmpInst::ICMP_EQ: { // while (X == Y) 7312 // Convert to: while (X-Y == 0) 7313 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7314 if (EL.hasAnyInfo()) return EL; 7315 break; 7316 } 7317 case ICmpInst::ICMP_SLT: 7318 case ICmpInst::ICMP_ULT: { // while (X < Y) 7319 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7320 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7321 AllowPredicates); 7322 if (EL.hasAnyInfo()) return EL; 7323 break; 7324 } 7325 case ICmpInst::ICMP_SGT: 7326 case ICmpInst::ICMP_UGT: { // while (X > Y) 7327 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7328 ExitLimit EL = 7329 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7330 AllowPredicates); 7331 if (EL.hasAnyInfo()) return EL; 7332 break; 7333 } 7334 default: 7335 break; 7336 } 7337 7338 auto *ExhaustiveCount = 7339 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7340 7341 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7342 return ExhaustiveCount; 7343 7344 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7345 ExitCond->getOperand(1), L, OriginalPred); 7346 } 7347 7348 ScalarEvolution::ExitLimit 7349 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7350 SwitchInst *Switch, 7351 BasicBlock *ExitingBlock, 7352 bool ControlsExit) { 7353 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7354 7355 // Give up if the exit is the default dest of a switch. 7356 if (Switch->getDefaultDest() == ExitingBlock) 7357 return getCouldNotCompute(); 7358 7359 assert(L->contains(Switch->getDefaultDest()) && 7360 "Default case must not exit the loop!"); 7361 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7362 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7363 7364 // while (X != Y) --> while (X-Y != 0) 7365 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7366 if (EL.hasAnyInfo()) 7367 return EL; 7368 7369 return getCouldNotCompute(); 7370 } 7371 7372 static ConstantInt * 7373 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7374 ScalarEvolution &SE) { 7375 const SCEV *InVal = SE.getConstant(C); 7376 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7377 assert(isa<SCEVConstant>(Val) && 7378 "Evaluation of SCEV at constant didn't fold correctly?"); 7379 return cast<SCEVConstant>(Val)->getValue(); 7380 } 7381 7382 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7383 /// compute the backedge execution count. 7384 ScalarEvolution::ExitLimit 7385 ScalarEvolution::computeLoadConstantCompareExitLimit( 7386 LoadInst *LI, 7387 Constant *RHS, 7388 const Loop *L, 7389 ICmpInst::Predicate predicate) { 7390 if (LI->isVolatile()) return getCouldNotCompute(); 7391 7392 // Check to see if the loaded pointer is a getelementptr of a global. 7393 // TODO: Use SCEV instead of manually grubbing with GEPs. 7394 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7395 if (!GEP) return getCouldNotCompute(); 7396 7397 // Make sure that it is really a constant global we are gepping, with an 7398 // initializer, and make sure the first IDX is really 0. 7399 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7400 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7401 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7402 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7403 return getCouldNotCompute(); 7404 7405 // Okay, we allow one non-constant index into the GEP instruction. 7406 Value *VarIdx = nullptr; 7407 std::vector<Constant*> Indexes; 7408 unsigned VarIdxNum = 0; 7409 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7410 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7411 Indexes.push_back(CI); 7412 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7413 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7414 VarIdx = GEP->getOperand(i); 7415 VarIdxNum = i-2; 7416 Indexes.push_back(nullptr); 7417 } 7418 7419 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7420 if (!VarIdx) 7421 return getCouldNotCompute(); 7422 7423 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7424 // Check to see if X is a loop variant variable value now. 7425 const SCEV *Idx = getSCEV(VarIdx); 7426 Idx = getSCEVAtScope(Idx, L); 7427 7428 // We can only recognize very limited forms of loop index expressions, in 7429 // particular, only affine AddRec's like {C1,+,C2}. 7430 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7431 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7432 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7433 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7434 return getCouldNotCompute(); 7435 7436 unsigned MaxSteps = MaxBruteForceIterations; 7437 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7438 ConstantInt *ItCst = ConstantInt::get( 7439 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7440 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7441 7442 // Form the GEP offset. 7443 Indexes[VarIdxNum] = Val; 7444 7445 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7446 Indexes); 7447 if (!Result) break; // Cannot compute! 7448 7449 // Evaluate the condition for this iteration. 7450 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7451 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7452 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7453 ++NumArrayLenItCounts; 7454 return getConstant(ItCst); // Found terminating iteration! 7455 } 7456 } 7457 return getCouldNotCompute(); 7458 } 7459 7460 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7461 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7462 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7463 if (!RHS) 7464 return getCouldNotCompute(); 7465 7466 const BasicBlock *Latch = L->getLoopLatch(); 7467 if (!Latch) 7468 return getCouldNotCompute(); 7469 7470 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7471 if (!Predecessor) 7472 return getCouldNotCompute(); 7473 7474 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7475 // Return LHS in OutLHS and shift_opt in OutOpCode. 7476 auto MatchPositiveShift = 7477 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7478 7479 using namespace PatternMatch; 7480 7481 ConstantInt *ShiftAmt; 7482 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7483 OutOpCode = Instruction::LShr; 7484 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7485 OutOpCode = Instruction::AShr; 7486 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7487 OutOpCode = Instruction::Shl; 7488 else 7489 return false; 7490 7491 return ShiftAmt->getValue().isStrictlyPositive(); 7492 }; 7493 7494 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7495 // 7496 // loop: 7497 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7498 // %iv.shifted = lshr i32 %iv, <positive constant> 7499 // 7500 // Return true on a successful match. Return the corresponding PHI node (%iv 7501 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7502 auto MatchShiftRecurrence = 7503 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7504 Optional<Instruction::BinaryOps> PostShiftOpCode; 7505 7506 { 7507 Instruction::BinaryOps OpC; 7508 Value *V; 7509 7510 // If we encounter a shift instruction, "peel off" the shift operation, 7511 // and remember that we did so. Later when we inspect %iv's backedge 7512 // value, we will make sure that the backedge value uses the same 7513 // operation. 7514 // 7515 // Note: the peeled shift operation does not have to be the same 7516 // instruction as the one feeding into the PHI's backedge value. We only 7517 // really care about it being the same *kind* of shift instruction -- 7518 // that's all that is required for our later inferences to hold. 7519 if (MatchPositiveShift(LHS, V, OpC)) { 7520 PostShiftOpCode = OpC; 7521 LHS = V; 7522 } 7523 } 7524 7525 PNOut = dyn_cast<PHINode>(LHS); 7526 if (!PNOut || PNOut->getParent() != L->getHeader()) 7527 return false; 7528 7529 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7530 Value *OpLHS; 7531 7532 return 7533 // The backedge value for the PHI node must be a shift by a positive 7534 // amount 7535 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7536 7537 // of the PHI node itself 7538 OpLHS == PNOut && 7539 7540 // and the kind of shift should be match the kind of shift we peeled 7541 // off, if any. 7542 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7543 }; 7544 7545 PHINode *PN; 7546 Instruction::BinaryOps OpCode; 7547 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7548 return getCouldNotCompute(); 7549 7550 const DataLayout &DL = getDataLayout(); 7551 7552 // The key rationale for this optimization is that for some kinds of shift 7553 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7554 // within a finite number of iterations. If the condition guarding the 7555 // backedge (in the sense that the backedge is taken if the condition is true) 7556 // is false for the value the shift recurrence stabilizes to, then we know 7557 // that the backedge is taken only a finite number of times. 7558 7559 ConstantInt *StableValue = nullptr; 7560 switch (OpCode) { 7561 default: 7562 llvm_unreachable("Impossible case!"); 7563 7564 case Instruction::AShr: { 7565 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7566 // bitwidth(K) iterations. 7567 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7568 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7569 Predecessor->getTerminator(), &DT); 7570 auto *Ty = cast<IntegerType>(RHS->getType()); 7571 if (Known.isNonNegative()) 7572 StableValue = ConstantInt::get(Ty, 0); 7573 else if (Known.isNegative()) 7574 StableValue = ConstantInt::get(Ty, -1, true); 7575 else 7576 return getCouldNotCompute(); 7577 7578 break; 7579 } 7580 case Instruction::LShr: 7581 case Instruction::Shl: 7582 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7583 // stabilize to 0 in at most bitwidth(K) iterations. 7584 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7585 break; 7586 } 7587 7588 auto *Result = 7589 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7590 assert(Result->getType()->isIntegerTy(1) && 7591 "Otherwise cannot be an operand to a branch instruction"); 7592 7593 if (Result->isZeroValue()) { 7594 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7595 const SCEV *UpperBound = 7596 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7597 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7598 } 7599 7600 return getCouldNotCompute(); 7601 } 7602 7603 /// Return true if we can constant fold an instruction of the specified type, 7604 /// assuming that all operands were constants. 7605 static bool CanConstantFold(const Instruction *I) { 7606 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7607 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7608 isa<LoadInst>(I)) 7609 return true; 7610 7611 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7612 if (const Function *F = CI->getCalledFunction()) 7613 return canConstantFoldCallTo(CI, F); 7614 return false; 7615 } 7616 7617 /// Determine whether this instruction can constant evolve within this loop 7618 /// assuming its operands can all constant evolve. 7619 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7620 // An instruction outside of the loop can't be derived from a loop PHI. 7621 if (!L->contains(I)) return false; 7622 7623 if (isa<PHINode>(I)) { 7624 // We don't currently keep track of the control flow needed to evaluate 7625 // PHIs, so we cannot handle PHIs inside of loops. 7626 return L->getHeader() == I->getParent(); 7627 } 7628 7629 // If we won't be able to constant fold this expression even if the operands 7630 // are constants, bail early. 7631 return CanConstantFold(I); 7632 } 7633 7634 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7635 /// recursing through each instruction operand until reaching a loop header phi. 7636 static PHINode * 7637 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7638 DenseMap<Instruction *, PHINode *> &PHIMap, 7639 unsigned Depth) { 7640 if (Depth > MaxConstantEvolvingDepth) 7641 return nullptr; 7642 7643 // Otherwise, we can evaluate this instruction if all of its operands are 7644 // constant or derived from a PHI node themselves. 7645 PHINode *PHI = nullptr; 7646 for (Value *Op : UseInst->operands()) { 7647 if (isa<Constant>(Op)) continue; 7648 7649 Instruction *OpInst = dyn_cast<Instruction>(Op); 7650 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7651 7652 PHINode *P = dyn_cast<PHINode>(OpInst); 7653 if (!P) 7654 // If this operand is already visited, reuse the prior result. 7655 // We may have P != PHI if this is the deepest point at which the 7656 // inconsistent paths meet. 7657 P = PHIMap.lookup(OpInst); 7658 if (!P) { 7659 // Recurse and memoize the results, whether a phi is found or not. 7660 // This recursive call invalidates pointers into PHIMap. 7661 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7662 PHIMap[OpInst] = P; 7663 } 7664 if (!P) 7665 return nullptr; // Not evolving from PHI 7666 if (PHI && PHI != P) 7667 return nullptr; // Evolving from multiple different PHIs. 7668 PHI = P; 7669 } 7670 // This is a expression evolving from a constant PHI! 7671 return PHI; 7672 } 7673 7674 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7675 /// in the loop that V is derived from. We allow arbitrary operations along the 7676 /// way, but the operands of an operation must either be constants or a value 7677 /// derived from a constant PHI. If this expression does not fit with these 7678 /// constraints, return null. 7679 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7680 Instruction *I = dyn_cast<Instruction>(V); 7681 if (!I || !canConstantEvolve(I, L)) return nullptr; 7682 7683 if (PHINode *PN = dyn_cast<PHINode>(I)) 7684 return PN; 7685 7686 // Record non-constant instructions contained by the loop. 7687 DenseMap<Instruction *, PHINode *> PHIMap; 7688 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7689 } 7690 7691 /// EvaluateExpression - Given an expression that passes the 7692 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7693 /// in the loop has the value PHIVal. If we can't fold this expression for some 7694 /// reason, return null. 7695 static Constant *EvaluateExpression(Value *V, const Loop *L, 7696 DenseMap<Instruction *, Constant *> &Vals, 7697 const DataLayout &DL, 7698 const TargetLibraryInfo *TLI) { 7699 // Convenient constant check, but redundant for recursive calls. 7700 if (Constant *C = dyn_cast<Constant>(V)) return C; 7701 Instruction *I = dyn_cast<Instruction>(V); 7702 if (!I) return nullptr; 7703 7704 if (Constant *C = Vals.lookup(I)) return C; 7705 7706 // An instruction inside the loop depends on a value outside the loop that we 7707 // weren't given a mapping for, or a value such as a call inside the loop. 7708 if (!canConstantEvolve(I, L)) return nullptr; 7709 7710 // An unmapped PHI can be due to a branch or another loop inside this loop, 7711 // or due to this not being the initial iteration through a loop where we 7712 // couldn't compute the evolution of this particular PHI last time. 7713 if (isa<PHINode>(I)) return nullptr; 7714 7715 std::vector<Constant*> Operands(I->getNumOperands()); 7716 7717 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7718 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7719 if (!Operand) { 7720 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7721 if (!Operands[i]) return nullptr; 7722 continue; 7723 } 7724 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7725 Vals[Operand] = C; 7726 if (!C) return nullptr; 7727 Operands[i] = C; 7728 } 7729 7730 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7731 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7732 Operands[1], DL, TLI); 7733 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7734 if (!LI->isVolatile()) 7735 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7736 } 7737 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7738 } 7739 7740 7741 // If every incoming value to PN except the one for BB is a specific Constant, 7742 // return that, else return nullptr. 7743 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7744 Constant *IncomingVal = nullptr; 7745 7746 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7747 if (PN->getIncomingBlock(i) == BB) 7748 continue; 7749 7750 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7751 if (!CurrentVal) 7752 return nullptr; 7753 7754 if (IncomingVal != CurrentVal) { 7755 if (IncomingVal) 7756 return nullptr; 7757 IncomingVal = CurrentVal; 7758 } 7759 } 7760 7761 return IncomingVal; 7762 } 7763 7764 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7765 /// in the header of its containing loop, we know the loop executes a 7766 /// constant number of times, and the PHI node is just a recurrence 7767 /// involving constants, fold it. 7768 Constant * 7769 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7770 const APInt &BEs, 7771 const Loop *L) { 7772 auto I = ConstantEvolutionLoopExitValue.find(PN); 7773 if (I != ConstantEvolutionLoopExitValue.end()) 7774 return I->second; 7775 7776 if (BEs.ugt(MaxBruteForceIterations)) 7777 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7778 7779 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7780 7781 DenseMap<Instruction *, Constant *> CurrentIterVals; 7782 BasicBlock *Header = L->getHeader(); 7783 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7784 7785 BasicBlock *Latch = L->getLoopLatch(); 7786 if (!Latch) 7787 return nullptr; 7788 7789 for (PHINode &PHI : Header->phis()) { 7790 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7791 CurrentIterVals[&PHI] = StartCST; 7792 } 7793 if (!CurrentIterVals.count(PN)) 7794 return RetVal = nullptr; 7795 7796 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7797 7798 // Execute the loop symbolically to determine the exit value. 7799 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7800 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7801 7802 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7803 unsigned IterationNum = 0; 7804 const DataLayout &DL = getDataLayout(); 7805 for (; ; ++IterationNum) { 7806 if (IterationNum == NumIterations) 7807 return RetVal = CurrentIterVals[PN]; // Got exit value! 7808 7809 // Compute the value of the PHIs for the next iteration. 7810 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7811 DenseMap<Instruction *, Constant *> NextIterVals; 7812 Constant *NextPHI = 7813 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7814 if (!NextPHI) 7815 return nullptr; // Couldn't evaluate! 7816 NextIterVals[PN] = NextPHI; 7817 7818 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7819 7820 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7821 // cease to be able to evaluate one of them or if they stop evolving, 7822 // because that doesn't necessarily prevent us from computing PN. 7823 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7824 for (const auto &I : CurrentIterVals) { 7825 PHINode *PHI = dyn_cast<PHINode>(I.first); 7826 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7827 PHIsToCompute.emplace_back(PHI, I.second); 7828 } 7829 // We use two distinct loops because EvaluateExpression may invalidate any 7830 // iterators into CurrentIterVals. 7831 for (const auto &I : PHIsToCompute) { 7832 PHINode *PHI = I.first; 7833 Constant *&NextPHI = NextIterVals[PHI]; 7834 if (!NextPHI) { // Not already computed. 7835 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7836 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7837 } 7838 if (NextPHI != I.second) 7839 StoppedEvolving = false; 7840 } 7841 7842 // If all entries in CurrentIterVals == NextIterVals then we can stop 7843 // iterating, the loop can't continue to change. 7844 if (StoppedEvolving) 7845 return RetVal = CurrentIterVals[PN]; 7846 7847 CurrentIterVals.swap(NextIterVals); 7848 } 7849 } 7850 7851 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7852 Value *Cond, 7853 bool ExitWhen) { 7854 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7855 if (!PN) return getCouldNotCompute(); 7856 7857 // If the loop is canonicalized, the PHI will have exactly two entries. 7858 // That's the only form we support here. 7859 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7860 7861 DenseMap<Instruction *, Constant *> CurrentIterVals; 7862 BasicBlock *Header = L->getHeader(); 7863 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7864 7865 BasicBlock *Latch = L->getLoopLatch(); 7866 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7867 7868 for (PHINode &PHI : Header->phis()) { 7869 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7870 CurrentIterVals[&PHI] = StartCST; 7871 } 7872 if (!CurrentIterVals.count(PN)) 7873 return getCouldNotCompute(); 7874 7875 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7876 // the loop symbolically to determine when the condition gets a value of 7877 // "ExitWhen". 7878 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7879 const DataLayout &DL = getDataLayout(); 7880 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7881 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7882 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7883 7884 // Couldn't symbolically evaluate. 7885 if (!CondVal) return getCouldNotCompute(); 7886 7887 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7888 ++NumBruteForceTripCountsComputed; 7889 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7890 } 7891 7892 // Update all the PHI nodes for the next iteration. 7893 DenseMap<Instruction *, Constant *> NextIterVals; 7894 7895 // Create a list of which PHIs we need to compute. We want to do this before 7896 // calling EvaluateExpression on them because that may invalidate iterators 7897 // into CurrentIterVals. 7898 SmallVector<PHINode *, 8> PHIsToCompute; 7899 for (const auto &I : CurrentIterVals) { 7900 PHINode *PHI = dyn_cast<PHINode>(I.first); 7901 if (!PHI || PHI->getParent() != Header) continue; 7902 PHIsToCompute.push_back(PHI); 7903 } 7904 for (PHINode *PHI : PHIsToCompute) { 7905 Constant *&NextPHI = NextIterVals[PHI]; 7906 if (NextPHI) continue; // Already computed! 7907 7908 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7909 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7910 } 7911 CurrentIterVals.swap(NextIterVals); 7912 } 7913 7914 // Too many iterations were needed to evaluate. 7915 return getCouldNotCompute(); 7916 } 7917 7918 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7919 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7920 ValuesAtScopes[V]; 7921 // Check to see if we've folded this expression at this loop before. 7922 for (auto &LS : Values) 7923 if (LS.first == L) 7924 return LS.second ? LS.second : V; 7925 7926 Values.emplace_back(L, nullptr); 7927 7928 // Otherwise compute it. 7929 const SCEV *C = computeSCEVAtScope(V, L); 7930 for (auto &LS : reverse(ValuesAtScopes[V])) 7931 if (LS.first == L) { 7932 LS.second = C; 7933 break; 7934 } 7935 return C; 7936 } 7937 7938 /// This builds up a Constant using the ConstantExpr interface. That way, we 7939 /// will return Constants for objects which aren't represented by a 7940 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7941 /// Returns NULL if the SCEV isn't representable as a Constant. 7942 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7943 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7944 case scCouldNotCompute: 7945 case scAddRecExpr: 7946 break; 7947 case scConstant: 7948 return cast<SCEVConstant>(V)->getValue(); 7949 case scUnknown: 7950 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7951 case scSignExtend: { 7952 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7953 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7954 return ConstantExpr::getSExt(CastOp, SS->getType()); 7955 break; 7956 } 7957 case scZeroExtend: { 7958 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7959 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7960 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7961 break; 7962 } 7963 case scTruncate: { 7964 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7965 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7966 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7967 break; 7968 } 7969 case scAddExpr: { 7970 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7971 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7972 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7973 unsigned AS = PTy->getAddressSpace(); 7974 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7975 C = ConstantExpr::getBitCast(C, DestPtrTy); 7976 } 7977 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7978 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7979 if (!C2) return nullptr; 7980 7981 // First pointer! 7982 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7983 unsigned AS = C2->getType()->getPointerAddressSpace(); 7984 std::swap(C, C2); 7985 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7986 // The offsets have been converted to bytes. We can add bytes to an 7987 // i8* by GEP with the byte count in the first index. 7988 C = ConstantExpr::getBitCast(C, DestPtrTy); 7989 } 7990 7991 // Don't bother trying to sum two pointers. We probably can't 7992 // statically compute a load that results from it anyway. 7993 if (C2->getType()->isPointerTy()) 7994 return nullptr; 7995 7996 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7997 if (PTy->getElementType()->isStructTy()) 7998 C2 = ConstantExpr::getIntegerCast( 7999 C2, Type::getInt32Ty(C->getContext()), true); 8000 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8001 } else 8002 C = ConstantExpr::getAdd(C, C2); 8003 } 8004 return C; 8005 } 8006 break; 8007 } 8008 case scMulExpr: { 8009 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8010 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8011 // Don't bother with pointers at all. 8012 if (C->getType()->isPointerTy()) return nullptr; 8013 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8014 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8015 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8016 C = ConstantExpr::getMul(C, C2); 8017 } 8018 return C; 8019 } 8020 break; 8021 } 8022 case scUDivExpr: { 8023 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8024 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8025 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8026 if (LHS->getType() == RHS->getType()) 8027 return ConstantExpr::getUDiv(LHS, RHS); 8028 break; 8029 } 8030 case scSMaxExpr: 8031 case scUMaxExpr: 8032 break; // TODO: smax, umax. 8033 } 8034 return nullptr; 8035 } 8036 8037 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8038 if (isa<SCEVConstant>(V)) return V; 8039 8040 // If this instruction is evolved from a constant-evolving PHI, compute the 8041 // exit value from the loop without using SCEVs. 8042 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8043 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8044 const Loop *LI = this->LI[I->getParent()]; 8045 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 8046 if (PHINode *PN = dyn_cast<PHINode>(I)) 8047 if (PN->getParent() == LI->getHeader()) { 8048 // Okay, there is no closed form solution for the PHI node. Check 8049 // to see if the loop that contains it has a known backedge-taken 8050 // count. If so, we may be able to force computation of the exit 8051 // value. 8052 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8053 if (const SCEVConstant *BTCC = 8054 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8055 8056 // This trivial case can show up in some degenerate cases where 8057 // the incoming IR has not yet been fully simplified. 8058 if (BTCC->getValue()->isZero()) { 8059 Value *InitValue = nullptr; 8060 bool MultipleInitValues = false; 8061 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8062 if (!LI->contains(PN->getIncomingBlock(i))) { 8063 if (!InitValue) 8064 InitValue = PN->getIncomingValue(i); 8065 else if (InitValue != PN->getIncomingValue(i)) { 8066 MultipleInitValues = true; 8067 break; 8068 } 8069 } 8070 if (!MultipleInitValues && InitValue) 8071 return getSCEV(InitValue); 8072 } 8073 } 8074 // Okay, we know how many times the containing loop executes. If 8075 // this is a constant evolving PHI node, get the final value at 8076 // the specified iteration number. 8077 Constant *RV = 8078 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8079 if (RV) return getSCEV(RV); 8080 } 8081 } 8082 8083 // Okay, this is an expression that we cannot symbolically evaluate 8084 // into a SCEV. Check to see if it's possible to symbolically evaluate 8085 // the arguments into constants, and if so, try to constant propagate the 8086 // result. This is particularly useful for computing loop exit values. 8087 if (CanConstantFold(I)) { 8088 SmallVector<Constant *, 4> Operands; 8089 bool MadeImprovement = false; 8090 for (Value *Op : I->operands()) { 8091 if (Constant *C = dyn_cast<Constant>(Op)) { 8092 Operands.push_back(C); 8093 continue; 8094 } 8095 8096 // If any of the operands is non-constant and if they are 8097 // non-integer and non-pointer, don't even try to analyze them 8098 // with scev techniques. 8099 if (!isSCEVable(Op->getType())) 8100 return V; 8101 8102 const SCEV *OrigV = getSCEV(Op); 8103 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8104 MadeImprovement |= OrigV != OpV; 8105 8106 Constant *C = BuildConstantFromSCEV(OpV); 8107 if (!C) return V; 8108 if (C->getType() != Op->getType()) 8109 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8110 Op->getType(), 8111 false), 8112 C, Op->getType()); 8113 Operands.push_back(C); 8114 } 8115 8116 // Check to see if getSCEVAtScope actually made an improvement. 8117 if (MadeImprovement) { 8118 Constant *C = nullptr; 8119 const DataLayout &DL = getDataLayout(); 8120 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8121 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8122 Operands[1], DL, &TLI); 8123 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8124 if (!LI->isVolatile()) 8125 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8126 } else 8127 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8128 if (!C) return V; 8129 return getSCEV(C); 8130 } 8131 } 8132 } 8133 8134 // This is some other type of SCEVUnknown, just return it. 8135 return V; 8136 } 8137 8138 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8139 // Avoid performing the look-up in the common case where the specified 8140 // expression has no loop-variant portions. 8141 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8142 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8143 if (OpAtScope != Comm->getOperand(i)) { 8144 // Okay, at least one of these operands is loop variant but might be 8145 // foldable. Build a new instance of the folded commutative expression. 8146 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8147 Comm->op_begin()+i); 8148 NewOps.push_back(OpAtScope); 8149 8150 for (++i; i != e; ++i) { 8151 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8152 NewOps.push_back(OpAtScope); 8153 } 8154 if (isa<SCEVAddExpr>(Comm)) 8155 return getAddExpr(NewOps); 8156 if (isa<SCEVMulExpr>(Comm)) 8157 return getMulExpr(NewOps); 8158 if (isa<SCEVSMaxExpr>(Comm)) 8159 return getSMaxExpr(NewOps); 8160 if (isa<SCEVUMaxExpr>(Comm)) 8161 return getUMaxExpr(NewOps); 8162 llvm_unreachable("Unknown commutative SCEV type!"); 8163 } 8164 } 8165 // If we got here, all operands are loop invariant. 8166 return Comm; 8167 } 8168 8169 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8170 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8171 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8172 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8173 return Div; // must be loop invariant 8174 return getUDivExpr(LHS, RHS); 8175 } 8176 8177 // If this is a loop recurrence for a loop that does not contain L, then we 8178 // are dealing with the final value computed by the loop. 8179 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8180 // First, attempt to evaluate each operand. 8181 // Avoid performing the look-up in the common case where the specified 8182 // expression has no loop-variant portions. 8183 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8184 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8185 if (OpAtScope == AddRec->getOperand(i)) 8186 continue; 8187 8188 // Okay, at least one of these operands is loop variant but might be 8189 // foldable. Build a new instance of the folded commutative expression. 8190 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8191 AddRec->op_begin()+i); 8192 NewOps.push_back(OpAtScope); 8193 for (++i; i != e; ++i) 8194 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8195 8196 const SCEV *FoldedRec = 8197 getAddRecExpr(NewOps, AddRec->getLoop(), 8198 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8199 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8200 // The addrec may be folded to a nonrecurrence, for example, if the 8201 // induction variable is multiplied by zero after constant folding. Go 8202 // ahead and return the folded value. 8203 if (!AddRec) 8204 return FoldedRec; 8205 break; 8206 } 8207 8208 // If the scope is outside the addrec's loop, evaluate it by using the 8209 // loop exit value of the addrec. 8210 if (!AddRec->getLoop()->contains(L)) { 8211 // To evaluate this recurrence, we need to know how many times the AddRec 8212 // loop iterates. Compute this now. 8213 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8214 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8215 8216 // Then, evaluate the AddRec. 8217 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8218 } 8219 8220 return AddRec; 8221 } 8222 8223 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8224 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8225 if (Op == Cast->getOperand()) 8226 return Cast; // must be loop invariant 8227 return getZeroExtendExpr(Op, Cast->getType()); 8228 } 8229 8230 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8231 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8232 if (Op == Cast->getOperand()) 8233 return Cast; // must be loop invariant 8234 return getSignExtendExpr(Op, Cast->getType()); 8235 } 8236 8237 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8238 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8239 if (Op == Cast->getOperand()) 8240 return Cast; // must be loop invariant 8241 return getTruncateExpr(Op, Cast->getType()); 8242 } 8243 8244 llvm_unreachable("Unknown SCEV type!"); 8245 } 8246 8247 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8248 return getSCEVAtScope(getSCEV(V), L); 8249 } 8250 8251 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8252 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8253 return stripInjectiveFunctions(ZExt->getOperand()); 8254 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8255 return stripInjectiveFunctions(SExt->getOperand()); 8256 return S; 8257 } 8258 8259 /// Finds the minimum unsigned root of the following equation: 8260 /// 8261 /// A * X = B (mod N) 8262 /// 8263 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8264 /// A and B isn't important. 8265 /// 8266 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8267 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8268 ScalarEvolution &SE) { 8269 uint32_t BW = A.getBitWidth(); 8270 assert(BW == SE.getTypeSizeInBits(B->getType())); 8271 assert(A != 0 && "A must be non-zero."); 8272 8273 // 1. D = gcd(A, N) 8274 // 8275 // The gcd of A and N may have only one prime factor: 2. The number of 8276 // trailing zeros in A is its multiplicity 8277 uint32_t Mult2 = A.countTrailingZeros(); 8278 // D = 2^Mult2 8279 8280 // 2. Check if B is divisible by D. 8281 // 8282 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8283 // is not less than multiplicity of this prime factor for D. 8284 if (SE.GetMinTrailingZeros(B) < Mult2) 8285 return SE.getCouldNotCompute(); 8286 8287 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8288 // modulo (N / D). 8289 // 8290 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8291 // (N / D) in general. The inverse itself always fits into BW bits, though, 8292 // so we immediately truncate it. 8293 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8294 APInt Mod(BW + 1, 0); 8295 Mod.setBit(BW - Mult2); // Mod = N / D 8296 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8297 8298 // 4. Compute the minimum unsigned root of the equation: 8299 // I * (B / D) mod (N / D) 8300 // To simplify the computation, we factor out the divide by D: 8301 // (I * B mod N) / D 8302 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8303 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8304 } 8305 8306 /// Find the roots of the quadratic equation for the given quadratic chrec 8307 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8308 /// two SCEVCouldNotCompute objects. 8309 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8310 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8311 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8312 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8313 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8314 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8315 8316 // We currently can only solve this if the coefficients are constants. 8317 if (!LC || !MC || !NC) 8318 return None; 8319 8320 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8321 const APInt &L = LC->getAPInt(); 8322 const APInt &M = MC->getAPInt(); 8323 const APInt &N = NC->getAPInt(); 8324 APInt Two(BitWidth, 2); 8325 8326 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8327 8328 // The A coefficient is N/2 8329 APInt A = N.sdiv(Two); 8330 8331 // The B coefficient is M-N/2 8332 APInt B = M; 8333 B -= A; // A is the same as N/2. 8334 8335 // The C coefficient is L. 8336 const APInt& C = L; 8337 8338 // Compute the B^2-4ac term. 8339 APInt SqrtTerm = B; 8340 SqrtTerm *= B; 8341 SqrtTerm -= 4 * (A * C); 8342 8343 if (SqrtTerm.isNegative()) { 8344 // The loop is provably infinite. 8345 return None; 8346 } 8347 8348 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8349 // integer value or else APInt::sqrt() will assert. 8350 APInt SqrtVal = SqrtTerm.sqrt(); 8351 8352 // Compute the two solutions for the quadratic formula. 8353 // The divisions must be performed as signed divisions. 8354 APInt NegB = -std::move(B); 8355 APInt TwoA = std::move(A); 8356 TwoA <<= 1; 8357 if (TwoA.isNullValue()) 8358 return None; 8359 8360 LLVMContext &Context = SE.getContext(); 8361 8362 ConstantInt *Solution1 = 8363 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8364 ConstantInt *Solution2 = 8365 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8366 8367 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8368 cast<SCEVConstant>(SE.getConstant(Solution2))); 8369 } 8370 8371 ScalarEvolution::ExitLimit 8372 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8373 bool AllowPredicates) { 8374 8375 // This is only used for loops with a "x != y" exit test. The exit condition 8376 // is now expressed as a single expression, V = x-y. So the exit test is 8377 // effectively V != 0. We know and take advantage of the fact that this 8378 // expression only being used in a comparison by zero context. 8379 8380 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8381 // If the value is a constant 8382 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8383 // If the value is already zero, the branch will execute zero times. 8384 if (C->getValue()->isZero()) return C; 8385 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8386 } 8387 8388 const SCEVAddRecExpr *AddRec = 8389 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8390 8391 if (!AddRec && AllowPredicates) 8392 // Try to make this an AddRec using runtime tests, in the first X 8393 // iterations of this loop, where X is the SCEV expression found by the 8394 // algorithm below. 8395 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8396 8397 if (!AddRec || AddRec->getLoop() != L) 8398 return getCouldNotCompute(); 8399 8400 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8401 // the quadratic equation to solve it. 8402 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8403 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8404 const SCEVConstant *R1 = Roots->first; 8405 const SCEVConstant *R2 = Roots->second; 8406 // Pick the smallest positive root value. 8407 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8408 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8409 if (!CB->getZExtValue()) 8410 std::swap(R1, R2); // R1 is the minimum root now. 8411 8412 // We can only use this value if the chrec ends up with an exact zero 8413 // value at this index. When solving for "X*X != 5", for example, we 8414 // should not accept a root of 2. 8415 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8416 if (Val->isZero()) 8417 // We found a quadratic root! 8418 return ExitLimit(R1, R1, false, Predicates); 8419 } 8420 } 8421 return getCouldNotCompute(); 8422 } 8423 8424 // Otherwise we can only handle this if it is affine. 8425 if (!AddRec->isAffine()) 8426 return getCouldNotCompute(); 8427 8428 // If this is an affine expression, the execution count of this branch is 8429 // the minimum unsigned root of the following equation: 8430 // 8431 // Start + Step*N = 0 (mod 2^BW) 8432 // 8433 // equivalent to: 8434 // 8435 // Step*N = -Start (mod 2^BW) 8436 // 8437 // where BW is the common bit width of Start and Step. 8438 8439 // Get the initial value for the loop. 8440 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8441 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8442 8443 // For now we handle only constant steps. 8444 // 8445 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8446 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8447 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8448 // We have not yet seen any such cases. 8449 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8450 if (!StepC || StepC->getValue()->isZero()) 8451 return getCouldNotCompute(); 8452 8453 // For positive steps (counting up until unsigned overflow): 8454 // N = -Start/Step (as unsigned) 8455 // For negative steps (counting down to zero): 8456 // N = Start/-Step 8457 // First compute the unsigned distance from zero in the direction of Step. 8458 bool CountDown = StepC->getAPInt().isNegative(); 8459 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8460 8461 // Handle unitary steps, which cannot wraparound. 8462 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8463 // N = Distance (as unsigned) 8464 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8465 APInt MaxBECount = getUnsignedRangeMax(Distance); 8466 8467 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8468 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8469 // case, and see if we can improve the bound. 8470 // 8471 // Explicitly handling this here is necessary because getUnsignedRange 8472 // isn't context-sensitive; it doesn't know that we only care about the 8473 // range inside the loop. 8474 const SCEV *Zero = getZero(Distance->getType()); 8475 const SCEV *One = getOne(Distance->getType()); 8476 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8477 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8478 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8479 // as "unsigned_max(Distance + 1) - 1". 8480 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8481 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8482 } 8483 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8484 } 8485 8486 // If the condition controls loop exit (the loop exits only if the expression 8487 // is true) and the addition is no-wrap we can use unsigned divide to 8488 // compute the backedge count. In this case, the step may not divide the 8489 // distance, but we don't care because if the condition is "missed" the loop 8490 // will have undefined behavior due to wrapping. 8491 if (ControlsExit && AddRec->hasNoSelfWrap() && 8492 loopHasNoAbnormalExits(AddRec->getLoop())) { 8493 const SCEV *Exact = 8494 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8495 const SCEV *Max = 8496 Exact == getCouldNotCompute() 8497 ? Exact 8498 : getConstant(getUnsignedRangeMax(Exact)); 8499 return ExitLimit(Exact, Max, false, Predicates); 8500 } 8501 8502 // Solve the general equation. 8503 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8504 getNegativeSCEV(Start), *this); 8505 const SCEV *M = E == getCouldNotCompute() 8506 ? E 8507 : getConstant(getUnsignedRangeMax(E)); 8508 return ExitLimit(E, M, false, Predicates); 8509 } 8510 8511 ScalarEvolution::ExitLimit 8512 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8513 // Loops that look like: while (X == 0) are very strange indeed. We don't 8514 // handle them yet except for the trivial case. This could be expanded in the 8515 // future as needed. 8516 8517 // If the value is a constant, check to see if it is known to be non-zero 8518 // already. If so, the backedge will execute zero times. 8519 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8520 if (!C->getValue()->isZero()) 8521 return getZero(C->getType()); 8522 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8523 } 8524 8525 // We could implement others, but I really doubt anyone writes loops like 8526 // this, and if they did, they would already be constant folded. 8527 return getCouldNotCompute(); 8528 } 8529 8530 std::pair<BasicBlock *, BasicBlock *> 8531 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8532 // If the block has a unique predecessor, then there is no path from the 8533 // predecessor to the block that does not go through the direct edge 8534 // from the predecessor to the block. 8535 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8536 return {Pred, BB}; 8537 8538 // A loop's header is defined to be a block that dominates the loop. 8539 // If the header has a unique predecessor outside the loop, it must be 8540 // a block that has exactly one successor that can reach the loop. 8541 if (Loop *L = LI.getLoopFor(BB)) 8542 return {L->getLoopPredecessor(), L->getHeader()}; 8543 8544 return {nullptr, nullptr}; 8545 } 8546 8547 /// SCEV structural equivalence is usually sufficient for testing whether two 8548 /// expressions are equal, however for the purposes of looking for a condition 8549 /// guarding a loop, it can be useful to be a little more general, since a 8550 /// front-end may have replicated the controlling expression. 8551 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8552 // Quick check to see if they are the same SCEV. 8553 if (A == B) return true; 8554 8555 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8556 // Not all instructions that are "identical" compute the same value. For 8557 // instance, two distinct alloca instructions allocating the same type are 8558 // identical and do not read memory; but compute distinct values. 8559 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8560 }; 8561 8562 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8563 // two different instructions with the same value. Check for this case. 8564 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8565 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8566 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8567 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8568 if (ComputesEqualValues(AI, BI)) 8569 return true; 8570 8571 // Otherwise assume they may have a different value. 8572 return false; 8573 } 8574 8575 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8576 const SCEV *&LHS, const SCEV *&RHS, 8577 unsigned Depth) { 8578 bool Changed = false; 8579 8580 // If we hit the max recursion limit bail out. 8581 if (Depth >= 3) 8582 return false; 8583 8584 // Canonicalize a constant to the right side. 8585 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8586 // Check for both operands constant. 8587 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8588 if (ConstantExpr::getICmp(Pred, 8589 LHSC->getValue(), 8590 RHSC->getValue())->isNullValue()) 8591 goto trivially_false; 8592 else 8593 goto trivially_true; 8594 } 8595 // Otherwise swap the operands to put the constant on the right. 8596 std::swap(LHS, RHS); 8597 Pred = ICmpInst::getSwappedPredicate(Pred); 8598 Changed = true; 8599 } 8600 8601 // If we're comparing an addrec with a value which is loop-invariant in the 8602 // addrec's loop, put the addrec on the left. Also make a dominance check, 8603 // as both operands could be addrecs loop-invariant in each other's loop. 8604 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8605 const Loop *L = AR->getLoop(); 8606 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8607 std::swap(LHS, RHS); 8608 Pred = ICmpInst::getSwappedPredicate(Pred); 8609 Changed = true; 8610 } 8611 } 8612 8613 // If there's a constant operand, canonicalize comparisons with boundary 8614 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8615 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8616 const APInt &RA = RC->getAPInt(); 8617 8618 bool SimplifiedByConstantRange = false; 8619 8620 if (!ICmpInst::isEquality(Pred)) { 8621 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8622 if (ExactCR.isFullSet()) 8623 goto trivially_true; 8624 else if (ExactCR.isEmptySet()) 8625 goto trivially_false; 8626 8627 APInt NewRHS; 8628 CmpInst::Predicate NewPred; 8629 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8630 ICmpInst::isEquality(NewPred)) { 8631 // We were able to convert an inequality to an equality. 8632 Pred = NewPred; 8633 RHS = getConstant(NewRHS); 8634 Changed = SimplifiedByConstantRange = true; 8635 } 8636 } 8637 8638 if (!SimplifiedByConstantRange) { 8639 switch (Pred) { 8640 default: 8641 break; 8642 case ICmpInst::ICMP_EQ: 8643 case ICmpInst::ICMP_NE: 8644 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8645 if (!RA) 8646 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8647 if (const SCEVMulExpr *ME = 8648 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8649 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8650 ME->getOperand(0)->isAllOnesValue()) { 8651 RHS = AE->getOperand(1); 8652 LHS = ME->getOperand(1); 8653 Changed = true; 8654 } 8655 break; 8656 8657 8658 // The "Should have been caught earlier!" messages refer to the fact 8659 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8660 // should have fired on the corresponding cases, and canonicalized the 8661 // check to trivially_true or trivially_false. 8662 8663 case ICmpInst::ICMP_UGE: 8664 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8665 Pred = ICmpInst::ICMP_UGT; 8666 RHS = getConstant(RA - 1); 8667 Changed = true; 8668 break; 8669 case ICmpInst::ICMP_ULE: 8670 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8671 Pred = ICmpInst::ICMP_ULT; 8672 RHS = getConstant(RA + 1); 8673 Changed = true; 8674 break; 8675 case ICmpInst::ICMP_SGE: 8676 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8677 Pred = ICmpInst::ICMP_SGT; 8678 RHS = getConstant(RA - 1); 8679 Changed = true; 8680 break; 8681 case ICmpInst::ICMP_SLE: 8682 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8683 Pred = ICmpInst::ICMP_SLT; 8684 RHS = getConstant(RA + 1); 8685 Changed = true; 8686 break; 8687 } 8688 } 8689 } 8690 8691 // Check for obvious equality. 8692 if (HasSameValue(LHS, RHS)) { 8693 if (ICmpInst::isTrueWhenEqual(Pred)) 8694 goto trivially_true; 8695 if (ICmpInst::isFalseWhenEqual(Pred)) 8696 goto trivially_false; 8697 } 8698 8699 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8700 // adding or subtracting 1 from one of the operands. 8701 switch (Pred) { 8702 case ICmpInst::ICMP_SLE: 8703 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8704 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8705 SCEV::FlagNSW); 8706 Pred = ICmpInst::ICMP_SLT; 8707 Changed = true; 8708 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8709 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8710 SCEV::FlagNSW); 8711 Pred = ICmpInst::ICMP_SLT; 8712 Changed = true; 8713 } 8714 break; 8715 case ICmpInst::ICMP_SGE: 8716 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8717 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8718 SCEV::FlagNSW); 8719 Pred = ICmpInst::ICMP_SGT; 8720 Changed = true; 8721 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8722 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8723 SCEV::FlagNSW); 8724 Pred = ICmpInst::ICMP_SGT; 8725 Changed = true; 8726 } 8727 break; 8728 case ICmpInst::ICMP_ULE: 8729 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8730 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8731 SCEV::FlagNUW); 8732 Pred = ICmpInst::ICMP_ULT; 8733 Changed = true; 8734 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8735 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8736 Pred = ICmpInst::ICMP_ULT; 8737 Changed = true; 8738 } 8739 break; 8740 case ICmpInst::ICMP_UGE: 8741 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8742 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8743 Pred = ICmpInst::ICMP_UGT; 8744 Changed = true; 8745 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8746 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8747 SCEV::FlagNUW); 8748 Pred = ICmpInst::ICMP_UGT; 8749 Changed = true; 8750 } 8751 break; 8752 default: 8753 break; 8754 } 8755 8756 // TODO: More simplifications are possible here. 8757 8758 // Recursively simplify until we either hit a recursion limit or nothing 8759 // changes. 8760 if (Changed) 8761 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8762 8763 return Changed; 8764 8765 trivially_true: 8766 // Return 0 == 0. 8767 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8768 Pred = ICmpInst::ICMP_EQ; 8769 return true; 8770 8771 trivially_false: 8772 // Return 0 != 0. 8773 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8774 Pred = ICmpInst::ICMP_NE; 8775 return true; 8776 } 8777 8778 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8779 return getSignedRangeMax(S).isNegative(); 8780 } 8781 8782 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8783 return getSignedRangeMin(S).isStrictlyPositive(); 8784 } 8785 8786 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8787 return !getSignedRangeMin(S).isNegative(); 8788 } 8789 8790 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8791 return !getSignedRangeMax(S).isStrictlyPositive(); 8792 } 8793 8794 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8795 return isKnownNegative(S) || isKnownPositive(S); 8796 } 8797 8798 std::pair<const SCEV *, const SCEV *> 8799 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8800 // Compute SCEV on entry of loop L. 8801 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8802 if (Start == getCouldNotCompute()) 8803 return { Start, Start }; 8804 // Compute post increment SCEV for loop L. 8805 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8806 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8807 return { Start, PostInc }; 8808 } 8809 8810 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8811 const SCEV *LHS, const SCEV *RHS) { 8812 // First collect all loops. 8813 SmallPtrSet<const Loop *, 8> LoopsUsed; 8814 getUsedLoops(LHS, LoopsUsed); 8815 getUsedLoops(RHS, LoopsUsed); 8816 8817 if (LoopsUsed.empty()) 8818 return false; 8819 8820 // Domination relationship must be a linear order on collected loops. 8821 #ifndef NDEBUG 8822 for (auto *L1 : LoopsUsed) 8823 for (auto *L2 : LoopsUsed) 8824 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8825 DT.dominates(L2->getHeader(), L1->getHeader())) && 8826 "Domination relationship is not a linear order"); 8827 #endif 8828 8829 const Loop *MDL = 8830 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8831 [&](const Loop *L1, const Loop *L2) { 8832 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 8833 }); 8834 8835 // Get init and post increment value for LHS. 8836 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 8837 // if LHS contains unknown non-invariant SCEV then bail out. 8838 if (SplitLHS.first == getCouldNotCompute()) 8839 return false; 8840 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 8841 // Get init and post increment value for RHS. 8842 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 8843 // if RHS contains unknown non-invariant SCEV then bail out. 8844 if (SplitRHS.first == getCouldNotCompute()) 8845 return false; 8846 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 8847 // It is possible that init SCEV contains an invariant load but it does 8848 // not dominate MDL and is not available at MDL loop entry, so we should 8849 // check it here. 8850 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 8851 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 8852 return false; 8853 8854 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 8855 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 8856 SplitRHS.second); 8857 } 8858 8859 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8860 const SCEV *LHS, const SCEV *RHS) { 8861 // Canonicalize the inputs first. 8862 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8863 8864 if (isKnownViaInduction(Pred, LHS, RHS)) 8865 return true; 8866 8867 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8868 return true; 8869 8870 // Otherwise see what can be done with some simple reasoning. 8871 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 8872 } 8873 8874 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 8875 const SCEVAddRecExpr *LHS, 8876 const SCEV *RHS) { 8877 const Loop *L = LHS->getLoop(); 8878 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 8879 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 8880 } 8881 8882 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8883 ICmpInst::Predicate Pred, 8884 bool &Increasing) { 8885 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8886 8887 #ifndef NDEBUG 8888 // Verify an invariant: inverting the predicate should turn a monotonically 8889 // increasing change to a monotonically decreasing one, and vice versa. 8890 bool IncreasingSwapped; 8891 bool ResultSwapped = isMonotonicPredicateImpl( 8892 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8893 8894 assert(Result == ResultSwapped && "should be able to analyze both!"); 8895 if (ResultSwapped) 8896 assert(Increasing == !IncreasingSwapped && 8897 "monotonicity should flip as we flip the predicate"); 8898 #endif 8899 8900 return Result; 8901 } 8902 8903 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8904 ICmpInst::Predicate Pred, 8905 bool &Increasing) { 8906 8907 // A zero step value for LHS means the induction variable is essentially a 8908 // loop invariant value. We don't really depend on the predicate actually 8909 // flipping from false to true (for increasing predicates, and the other way 8910 // around for decreasing predicates), all we care about is that *if* the 8911 // predicate changes then it only changes from false to true. 8912 // 8913 // A zero step value in itself is not very useful, but there may be places 8914 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8915 // as general as possible. 8916 8917 switch (Pred) { 8918 default: 8919 return false; // Conservative answer 8920 8921 case ICmpInst::ICMP_UGT: 8922 case ICmpInst::ICMP_UGE: 8923 case ICmpInst::ICMP_ULT: 8924 case ICmpInst::ICMP_ULE: 8925 if (!LHS->hasNoUnsignedWrap()) 8926 return false; 8927 8928 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8929 return true; 8930 8931 case ICmpInst::ICMP_SGT: 8932 case ICmpInst::ICMP_SGE: 8933 case ICmpInst::ICMP_SLT: 8934 case ICmpInst::ICMP_SLE: { 8935 if (!LHS->hasNoSignedWrap()) 8936 return false; 8937 8938 const SCEV *Step = LHS->getStepRecurrence(*this); 8939 8940 if (isKnownNonNegative(Step)) { 8941 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8942 return true; 8943 } 8944 8945 if (isKnownNonPositive(Step)) { 8946 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8947 return true; 8948 } 8949 8950 return false; 8951 } 8952 8953 } 8954 8955 llvm_unreachable("switch has default clause!"); 8956 } 8957 8958 bool ScalarEvolution::isLoopInvariantPredicate( 8959 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8960 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8961 const SCEV *&InvariantRHS) { 8962 8963 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8964 if (!isLoopInvariant(RHS, L)) { 8965 if (!isLoopInvariant(LHS, L)) 8966 return false; 8967 8968 std::swap(LHS, RHS); 8969 Pred = ICmpInst::getSwappedPredicate(Pred); 8970 } 8971 8972 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8973 if (!ArLHS || ArLHS->getLoop() != L) 8974 return false; 8975 8976 bool Increasing; 8977 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8978 return false; 8979 8980 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8981 // true as the loop iterates, and the backedge is control dependent on 8982 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8983 // 8984 // * if the predicate was false in the first iteration then the predicate 8985 // is never evaluated again, since the loop exits without taking the 8986 // backedge. 8987 // * if the predicate was true in the first iteration then it will 8988 // continue to be true for all future iterations since it is 8989 // monotonically increasing. 8990 // 8991 // For both the above possibilities, we can replace the loop varying 8992 // predicate with its value on the first iteration of the loop (which is 8993 // loop invariant). 8994 // 8995 // A similar reasoning applies for a monotonically decreasing predicate, by 8996 // replacing true with false and false with true in the above two bullets. 8997 8998 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8999 9000 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9001 return false; 9002 9003 InvariantPred = Pred; 9004 InvariantLHS = ArLHS->getStart(); 9005 InvariantRHS = RHS; 9006 return true; 9007 } 9008 9009 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9010 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9011 if (HasSameValue(LHS, RHS)) 9012 return ICmpInst::isTrueWhenEqual(Pred); 9013 9014 // This code is split out from isKnownPredicate because it is called from 9015 // within isLoopEntryGuardedByCond. 9016 9017 auto CheckRanges = 9018 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9019 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9020 .contains(RangeLHS); 9021 }; 9022 9023 // The check at the top of the function catches the case where the values are 9024 // known to be equal. 9025 if (Pred == CmpInst::ICMP_EQ) 9026 return false; 9027 9028 if (Pred == CmpInst::ICMP_NE) 9029 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9030 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9031 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9032 9033 if (CmpInst::isSigned(Pred)) 9034 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9035 9036 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9037 } 9038 9039 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9040 const SCEV *LHS, 9041 const SCEV *RHS) { 9042 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9043 // Return Y via OutY. 9044 auto MatchBinaryAddToConst = 9045 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9046 SCEV::NoWrapFlags ExpectedFlags) { 9047 const SCEV *NonConstOp, *ConstOp; 9048 SCEV::NoWrapFlags FlagsPresent; 9049 9050 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9051 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9052 return false; 9053 9054 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9055 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9056 }; 9057 9058 APInt C; 9059 9060 switch (Pred) { 9061 default: 9062 break; 9063 9064 case ICmpInst::ICMP_SGE: 9065 std::swap(LHS, RHS); 9066 LLVM_FALLTHROUGH; 9067 case ICmpInst::ICMP_SLE: 9068 // X s<= (X + C)<nsw> if C >= 0 9069 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9070 return true; 9071 9072 // (X + C)<nsw> s<= X if C <= 0 9073 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9074 !C.isStrictlyPositive()) 9075 return true; 9076 break; 9077 9078 case ICmpInst::ICMP_SGT: 9079 std::swap(LHS, RHS); 9080 LLVM_FALLTHROUGH; 9081 case ICmpInst::ICMP_SLT: 9082 // X s< (X + C)<nsw> if C > 0 9083 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9084 C.isStrictlyPositive()) 9085 return true; 9086 9087 // (X + C)<nsw> s< X if C < 0 9088 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9089 return true; 9090 break; 9091 } 9092 9093 return false; 9094 } 9095 9096 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9097 const SCEV *LHS, 9098 const SCEV *RHS) { 9099 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9100 return false; 9101 9102 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9103 // the stack can result in exponential time complexity. 9104 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9105 9106 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9107 // 9108 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9109 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9110 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9111 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9112 // use isKnownPredicate later if needed. 9113 return isKnownNonNegative(RHS) && 9114 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9115 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9116 } 9117 9118 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9119 ICmpInst::Predicate Pred, 9120 const SCEV *LHS, const SCEV *RHS) { 9121 // No need to even try if we know the module has no guards. 9122 if (!HasGuards) 9123 return false; 9124 9125 return any_of(*BB, [&](Instruction &I) { 9126 using namespace llvm::PatternMatch; 9127 9128 Value *Condition; 9129 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9130 m_Value(Condition))) && 9131 isImpliedCond(Pred, LHS, RHS, Condition, false); 9132 }); 9133 } 9134 9135 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9136 /// protected by a conditional between LHS and RHS. This is used to 9137 /// to eliminate casts. 9138 bool 9139 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9140 ICmpInst::Predicate Pred, 9141 const SCEV *LHS, const SCEV *RHS) { 9142 // Interpret a null as meaning no loop, where there is obviously no guard 9143 // (interprocedural conditions notwithstanding). 9144 if (!L) return true; 9145 9146 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9147 return true; 9148 9149 BasicBlock *Latch = L->getLoopLatch(); 9150 if (!Latch) 9151 return false; 9152 9153 BranchInst *LoopContinuePredicate = 9154 dyn_cast<BranchInst>(Latch->getTerminator()); 9155 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9156 isImpliedCond(Pred, LHS, RHS, 9157 LoopContinuePredicate->getCondition(), 9158 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9159 return true; 9160 9161 // We don't want more than one activation of the following loops on the stack 9162 // -- that can lead to O(n!) time complexity. 9163 if (WalkingBEDominatingConds) 9164 return false; 9165 9166 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9167 9168 // See if we can exploit a trip count to prove the predicate. 9169 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9170 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9171 if (LatchBECount != getCouldNotCompute()) { 9172 // We know that Latch branches back to the loop header exactly 9173 // LatchBECount times. This means the backdege condition at Latch is 9174 // equivalent to "{0,+,1} u< LatchBECount". 9175 Type *Ty = LatchBECount->getType(); 9176 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9177 const SCEV *LoopCounter = 9178 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9179 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9180 LatchBECount)) 9181 return true; 9182 } 9183 9184 // Check conditions due to any @llvm.assume intrinsics. 9185 for (auto &AssumeVH : AC.assumptions()) { 9186 if (!AssumeVH) 9187 continue; 9188 auto *CI = cast<CallInst>(AssumeVH); 9189 if (!DT.dominates(CI, Latch->getTerminator())) 9190 continue; 9191 9192 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9193 return true; 9194 } 9195 9196 // If the loop is not reachable from the entry block, we risk running into an 9197 // infinite loop as we walk up into the dom tree. These loops do not matter 9198 // anyway, so we just return a conservative answer when we see them. 9199 if (!DT.isReachableFromEntry(L->getHeader())) 9200 return false; 9201 9202 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9203 return true; 9204 9205 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9206 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9207 assert(DTN && "should reach the loop header before reaching the root!"); 9208 9209 BasicBlock *BB = DTN->getBlock(); 9210 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9211 return true; 9212 9213 BasicBlock *PBB = BB->getSinglePredecessor(); 9214 if (!PBB) 9215 continue; 9216 9217 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9218 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9219 continue; 9220 9221 Value *Condition = ContinuePredicate->getCondition(); 9222 9223 // If we have an edge `E` within the loop body that dominates the only 9224 // latch, the condition guarding `E` also guards the backedge. This 9225 // reasoning works only for loops with a single latch. 9226 9227 BasicBlockEdge DominatingEdge(PBB, BB); 9228 if (DominatingEdge.isSingleEdge()) { 9229 // We're constructively (and conservatively) enumerating edges within the 9230 // loop body that dominate the latch. The dominator tree better agree 9231 // with us on this: 9232 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9233 9234 if (isImpliedCond(Pred, LHS, RHS, Condition, 9235 BB != ContinuePredicate->getSuccessor(0))) 9236 return true; 9237 } 9238 } 9239 9240 return false; 9241 } 9242 9243 bool 9244 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9245 ICmpInst::Predicate Pred, 9246 const SCEV *LHS, const SCEV *RHS) { 9247 // Interpret a null as meaning no loop, where there is obviously no guard 9248 // (interprocedural conditions notwithstanding). 9249 if (!L) return false; 9250 9251 // Both LHS and RHS must be available at loop entry. 9252 assert(isAvailableAtLoopEntry(LHS, L) && 9253 "LHS is not available at Loop Entry"); 9254 assert(isAvailableAtLoopEntry(RHS, L) && 9255 "RHS is not available at Loop Entry"); 9256 9257 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9258 return true; 9259 9260 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9261 // the facts (a >= b && a != b) separately. A typical situation is when the 9262 // non-strict comparison is known from ranges and non-equality is known from 9263 // dominating predicates. If we are proving strict comparison, we always try 9264 // to prove non-equality and non-strict comparison separately. 9265 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9266 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9267 bool ProvedNonStrictComparison = false; 9268 bool ProvedNonEquality = false; 9269 9270 if (ProvingStrictComparison) { 9271 ProvedNonStrictComparison = 9272 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9273 ProvedNonEquality = 9274 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9275 if (ProvedNonStrictComparison && ProvedNonEquality) 9276 return true; 9277 } 9278 9279 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9280 auto ProveViaGuard = [&](BasicBlock *Block) { 9281 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9282 return true; 9283 if (ProvingStrictComparison) { 9284 if (!ProvedNonStrictComparison) 9285 ProvedNonStrictComparison = 9286 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9287 if (!ProvedNonEquality) 9288 ProvedNonEquality = 9289 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9290 if (ProvedNonStrictComparison && ProvedNonEquality) 9291 return true; 9292 } 9293 return false; 9294 }; 9295 9296 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9297 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9298 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9299 return true; 9300 if (ProvingStrictComparison) { 9301 if (!ProvedNonStrictComparison) 9302 ProvedNonStrictComparison = 9303 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9304 if (!ProvedNonEquality) 9305 ProvedNonEquality = 9306 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9307 if (ProvedNonStrictComparison && ProvedNonEquality) 9308 return true; 9309 } 9310 return false; 9311 }; 9312 9313 // Starting at the loop predecessor, climb up the predecessor chain, as long 9314 // as there are predecessors that can be found that have unique successors 9315 // leading to the original header. 9316 for (std::pair<BasicBlock *, BasicBlock *> 9317 Pair(L->getLoopPredecessor(), L->getHeader()); 9318 Pair.first; 9319 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9320 9321 if (ProveViaGuard(Pair.first)) 9322 return true; 9323 9324 BranchInst *LoopEntryPredicate = 9325 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9326 if (!LoopEntryPredicate || 9327 LoopEntryPredicate->isUnconditional()) 9328 continue; 9329 9330 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9331 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9332 return true; 9333 } 9334 9335 // Check conditions due to any @llvm.assume intrinsics. 9336 for (auto &AssumeVH : AC.assumptions()) { 9337 if (!AssumeVH) 9338 continue; 9339 auto *CI = cast<CallInst>(AssumeVH); 9340 if (!DT.dominates(CI, L->getHeader())) 9341 continue; 9342 9343 if (ProveViaCond(CI->getArgOperand(0), false)) 9344 return true; 9345 } 9346 9347 return false; 9348 } 9349 9350 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9351 const SCEV *LHS, const SCEV *RHS, 9352 Value *FoundCondValue, 9353 bool Inverse) { 9354 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9355 return false; 9356 9357 auto ClearOnExit = 9358 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9359 9360 // Recursively handle And and Or conditions. 9361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9362 if (BO->getOpcode() == Instruction::And) { 9363 if (!Inverse) 9364 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9365 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9366 } else if (BO->getOpcode() == Instruction::Or) { 9367 if (Inverse) 9368 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9369 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9370 } 9371 } 9372 9373 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9374 if (!ICI) return false; 9375 9376 // Now that we found a conditional branch that dominates the loop or controls 9377 // the loop latch. Check to see if it is the comparison we are looking for. 9378 ICmpInst::Predicate FoundPred; 9379 if (Inverse) 9380 FoundPred = ICI->getInversePredicate(); 9381 else 9382 FoundPred = ICI->getPredicate(); 9383 9384 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9385 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9386 9387 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9388 } 9389 9390 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9391 const SCEV *RHS, 9392 ICmpInst::Predicate FoundPred, 9393 const SCEV *FoundLHS, 9394 const SCEV *FoundRHS) { 9395 // Balance the types. 9396 if (getTypeSizeInBits(LHS->getType()) < 9397 getTypeSizeInBits(FoundLHS->getType())) { 9398 if (CmpInst::isSigned(Pred)) { 9399 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9400 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9401 } else { 9402 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9403 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9404 } 9405 } else if (getTypeSizeInBits(LHS->getType()) > 9406 getTypeSizeInBits(FoundLHS->getType())) { 9407 if (CmpInst::isSigned(FoundPred)) { 9408 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9409 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9410 } else { 9411 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9412 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9413 } 9414 } 9415 9416 // Canonicalize the query to match the way instcombine will have 9417 // canonicalized the comparison. 9418 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9419 if (LHS == RHS) 9420 return CmpInst::isTrueWhenEqual(Pred); 9421 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9422 if (FoundLHS == FoundRHS) 9423 return CmpInst::isFalseWhenEqual(FoundPred); 9424 9425 // Check to see if we can make the LHS or RHS match. 9426 if (LHS == FoundRHS || RHS == FoundLHS) { 9427 if (isa<SCEVConstant>(RHS)) { 9428 std::swap(FoundLHS, FoundRHS); 9429 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9430 } else { 9431 std::swap(LHS, RHS); 9432 Pred = ICmpInst::getSwappedPredicate(Pred); 9433 } 9434 } 9435 9436 // Check whether the found predicate is the same as the desired predicate. 9437 if (FoundPred == Pred) 9438 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9439 9440 // Check whether swapping the found predicate makes it the same as the 9441 // desired predicate. 9442 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9443 if (isa<SCEVConstant>(RHS)) 9444 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9445 else 9446 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9447 RHS, LHS, FoundLHS, FoundRHS); 9448 } 9449 9450 // Unsigned comparison is the same as signed comparison when both the operands 9451 // are non-negative. 9452 if (CmpInst::isUnsigned(FoundPred) && 9453 CmpInst::getSignedPredicate(FoundPred) == Pred && 9454 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9455 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9456 9457 // Check if we can make progress by sharpening ranges. 9458 if (FoundPred == ICmpInst::ICMP_NE && 9459 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9460 9461 const SCEVConstant *C = nullptr; 9462 const SCEV *V = nullptr; 9463 9464 if (isa<SCEVConstant>(FoundLHS)) { 9465 C = cast<SCEVConstant>(FoundLHS); 9466 V = FoundRHS; 9467 } else { 9468 C = cast<SCEVConstant>(FoundRHS); 9469 V = FoundLHS; 9470 } 9471 9472 // The guarding predicate tells us that C != V. If the known range 9473 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9474 // range we consider has to correspond to same signedness as the 9475 // predicate we're interested in folding. 9476 9477 APInt Min = ICmpInst::isSigned(Pred) ? 9478 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9479 9480 if (Min == C->getAPInt()) { 9481 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9482 // This is true even if (Min + 1) wraps around -- in case of 9483 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9484 9485 APInt SharperMin = Min + 1; 9486 9487 switch (Pred) { 9488 case ICmpInst::ICMP_SGE: 9489 case ICmpInst::ICMP_UGE: 9490 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9491 // RHS, we're done. 9492 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9493 getConstant(SharperMin))) 9494 return true; 9495 LLVM_FALLTHROUGH; 9496 9497 case ICmpInst::ICMP_SGT: 9498 case ICmpInst::ICMP_UGT: 9499 // We know from the range information that (V `Pred` Min || 9500 // V == Min). We know from the guarding condition that !(V 9501 // == Min). This gives us 9502 // 9503 // V `Pred` Min || V == Min && !(V == Min) 9504 // => V `Pred` Min 9505 // 9506 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9507 9508 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9509 return true; 9510 LLVM_FALLTHROUGH; 9511 9512 default: 9513 // No change 9514 break; 9515 } 9516 } 9517 } 9518 9519 // Check whether the actual condition is beyond sufficient. 9520 if (FoundPred == ICmpInst::ICMP_EQ) 9521 if (ICmpInst::isTrueWhenEqual(Pred)) 9522 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9523 return true; 9524 if (Pred == ICmpInst::ICMP_NE) 9525 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9526 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9527 return true; 9528 9529 // Otherwise assume the worst. 9530 return false; 9531 } 9532 9533 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9534 const SCEV *&L, const SCEV *&R, 9535 SCEV::NoWrapFlags &Flags) { 9536 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9537 if (!AE || AE->getNumOperands() != 2) 9538 return false; 9539 9540 L = AE->getOperand(0); 9541 R = AE->getOperand(1); 9542 Flags = AE->getNoWrapFlags(); 9543 return true; 9544 } 9545 9546 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9547 const SCEV *Less) { 9548 // We avoid subtracting expressions here because this function is usually 9549 // fairly deep in the call stack (i.e. is called many times). 9550 9551 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9552 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9553 const auto *MAR = cast<SCEVAddRecExpr>(More); 9554 9555 if (LAR->getLoop() != MAR->getLoop()) 9556 return None; 9557 9558 // We look at affine expressions only; not for correctness but to keep 9559 // getStepRecurrence cheap. 9560 if (!LAR->isAffine() || !MAR->isAffine()) 9561 return None; 9562 9563 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9564 return None; 9565 9566 Less = LAR->getStart(); 9567 More = MAR->getStart(); 9568 9569 // fall through 9570 } 9571 9572 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9573 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9574 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9575 return M - L; 9576 } 9577 9578 SCEV::NoWrapFlags Flags; 9579 const SCEV *LLess = nullptr, *RLess = nullptr; 9580 const SCEV *LMore = nullptr, *RMore = nullptr; 9581 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9582 // Compare (X + C1) vs X. 9583 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9584 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9585 if (RLess == More) 9586 return -(C1->getAPInt()); 9587 9588 // Compare X vs (X + C2). 9589 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9590 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9591 if (RMore == Less) 9592 return C2->getAPInt(); 9593 9594 // Compare (X + C1) vs (X + C2). 9595 if (C1 && C2 && RLess == RMore) 9596 return C2->getAPInt() - C1->getAPInt(); 9597 9598 return None; 9599 } 9600 9601 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9602 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9603 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9604 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9605 return false; 9606 9607 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9608 if (!AddRecLHS) 9609 return false; 9610 9611 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9612 if (!AddRecFoundLHS) 9613 return false; 9614 9615 // We'd like to let SCEV reason about control dependencies, so we constrain 9616 // both the inequalities to be about add recurrences on the same loop. This 9617 // way we can use isLoopEntryGuardedByCond later. 9618 9619 const Loop *L = AddRecFoundLHS->getLoop(); 9620 if (L != AddRecLHS->getLoop()) 9621 return false; 9622 9623 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9624 // 9625 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9626 // ... (2) 9627 // 9628 // Informal proof for (2), assuming (1) [*]: 9629 // 9630 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9631 // 9632 // Then 9633 // 9634 // FoundLHS s< FoundRHS s< INT_MIN - C 9635 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9636 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9637 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9638 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9639 // <=> FoundLHS + C s< FoundRHS + C 9640 // 9641 // [*]: (1) can be proved by ruling out overflow. 9642 // 9643 // [**]: This can be proved by analyzing all the four possibilities: 9644 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9645 // (A s>= 0, B s>= 0). 9646 // 9647 // Note: 9648 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9649 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9650 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9651 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9652 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9653 // C)". 9654 9655 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9656 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9657 if (!LDiff || !RDiff || *LDiff != *RDiff) 9658 return false; 9659 9660 if (LDiff->isMinValue()) 9661 return true; 9662 9663 APInt FoundRHSLimit; 9664 9665 if (Pred == CmpInst::ICMP_ULT) { 9666 FoundRHSLimit = -(*RDiff); 9667 } else { 9668 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9669 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9670 } 9671 9672 // Try to prove (1) or (2), as needed. 9673 return isAvailableAtLoopEntry(FoundRHS, L) && 9674 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9675 getConstant(FoundRHSLimit)); 9676 } 9677 9678 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9679 const SCEV *LHS, const SCEV *RHS, 9680 const SCEV *FoundLHS, 9681 const SCEV *FoundRHS, unsigned Depth) { 9682 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9683 9684 auto ClearOnExit = make_scope_exit([&]() { 9685 if (LPhi) { 9686 bool Erased = PendingMerges.erase(LPhi); 9687 assert(Erased && "Failed to erase LPhi!"); 9688 (void)Erased; 9689 } 9690 if (RPhi) { 9691 bool Erased = PendingMerges.erase(RPhi); 9692 assert(Erased && "Failed to erase RPhi!"); 9693 (void)Erased; 9694 } 9695 }); 9696 9697 // Find respective Phis and check that they are not being pending. 9698 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9699 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9700 if (!PendingMerges.insert(Phi).second) 9701 return false; 9702 LPhi = Phi; 9703 } 9704 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9705 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9706 // If we detect a loop of Phi nodes being processed by this method, for 9707 // example: 9708 // 9709 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9710 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9711 // 9712 // we don't want to deal with a case that complex, so return conservative 9713 // answer false. 9714 if (!PendingMerges.insert(Phi).second) 9715 return false; 9716 RPhi = Phi; 9717 } 9718 9719 // If none of LHS, RHS is a Phi, nothing to do here. 9720 if (!LPhi && !RPhi) 9721 return false; 9722 9723 // If there is a SCEVUnknown Phi we are interested in, make it left. 9724 if (!LPhi) { 9725 std::swap(LHS, RHS); 9726 std::swap(FoundLHS, FoundRHS); 9727 std::swap(LPhi, RPhi); 9728 Pred = ICmpInst::getSwappedPredicate(Pred); 9729 } 9730 9731 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9732 const BasicBlock *LBB = LPhi->getParent(); 9733 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9734 9735 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9736 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9737 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9738 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9739 }; 9740 9741 if (RPhi && RPhi->getParent() == LBB) { 9742 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9743 // If we compare two Phis from the same block, and for each entry block 9744 // the predicate is true for incoming values from this block, then the 9745 // predicate is also true for the Phis. 9746 for (const BasicBlock *IncBB : predecessors(LBB)) { 9747 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9748 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9749 if (!ProvedEasily(L, R)) 9750 return false; 9751 } 9752 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9753 // Case two: RHS is also a Phi from the same basic block, and it is an 9754 // AddRec. It means that there is a loop which has both AddRec and Unknown 9755 // PHIs, for it we can compare incoming values of AddRec from above the loop 9756 // and latch with their respective incoming values of LPhi. 9757 // TODO: Generalize to handle loops with many inputs in a header. 9758 if (LPhi->getNumIncomingValues() != 2) return false; 9759 9760 auto *RLoop = RAR->getLoop(); 9761 auto *Predecessor = RLoop->getLoopPredecessor(); 9762 assert(Predecessor && "Loop with AddRec with no predecessor?"); 9763 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 9764 if (!ProvedEasily(L1, RAR->getStart())) 9765 return false; 9766 auto *Latch = RLoop->getLoopLatch(); 9767 assert(Latch && "Loop with AddRec with no latch?"); 9768 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 9769 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 9770 return false; 9771 } else { 9772 // In all other cases go over inputs of LHS and compare each of them to RHS, 9773 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 9774 // At this point RHS is either a non-Phi, or it is a Phi from some block 9775 // different from LBB. 9776 for (const BasicBlock *IncBB : predecessors(LBB)) { 9777 // Check that RHS is available in this block. 9778 if (!dominates(RHS, IncBB)) 9779 return false; 9780 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9781 if (!ProvedEasily(L, RHS)) 9782 return false; 9783 } 9784 } 9785 return true; 9786 } 9787 9788 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9789 const SCEV *LHS, const SCEV *RHS, 9790 const SCEV *FoundLHS, 9791 const SCEV *FoundRHS) { 9792 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9793 return true; 9794 9795 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9796 return true; 9797 9798 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9799 FoundLHS, FoundRHS) || 9800 // ~x < ~y --> x > y 9801 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9802 getNotSCEV(FoundRHS), 9803 getNotSCEV(FoundLHS)); 9804 } 9805 9806 /// If Expr computes ~A, return A else return nullptr 9807 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9808 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9809 if (!Add || Add->getNumOperands() != 2 || 9810 !Add->getOperand(0)->isAllOnesValue()) 9811 return nullptr; 9812 9813 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9814 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9815 !AddRHS->getOperand(0)->isAllOnesValue()) 9816 return nullptr; 9817 9818 return AddRHS->getOperand(1); 9819 } 9820 9821 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9822 template<typename MaxExprType> 9823 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9824 const SCEV *Candidate) { 9825 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9826 if (!MaxExpr) return false; 9827 9828 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9829 } 9830 9831 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9832 template<typename MaxExprType> 9833 static bool IsMinConsistingOf(ScalarEvolution &SE, 9834 const SCEV *MaybeMinExpr, 9835 const SCEV *Candidate) { 9836 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9837 if (!MaybeMaxExpr) 9838 return false; 9839 9840 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9841 } 9842 9843 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9844 ICmpInst::Predicate Pred, 9845 const SCEV *LHS, const SCEV *RHS) { 9846 // If both sides are affine addrecs for the same loop, with equal 9847 // steps, and we know the recurrences don't wrap, then we only 9848 // need to check the predicate on the starting values. 9849 9850 if (!ICmpInst::isRelational(Pred)) 9851 return false; 9852 9853 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9854 if (!LAR) 9855 return false; 9856 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9857 if (!RAR) 9858 return false; 9859 if (LAR->getLoop() != RAR->getLoop()) 9860 return false; 9861 if (!LAR->isAffine() || !RAR->isAffine()) 9862 return false; 9863 9864 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9865 return false; 9866 9867 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9868 SCEV::FlagNSW : SCEV::FlagNUW; 9869 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9870 return false; 9871 9872 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9873 } 9874 9875 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9876 /// expression? 9877 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9878 ICmpInst::Predicate Pred, 9879 const SCEV *LHS, const SCEV *RHS) { 9880 switch (Pred) { 9881 default: 9882 return false; 9883 9884 case ICmpInst::ICMP_SGE: 9885 std::swap(LHS, RHS); 9886 LLVM_FALLTHROUGH; 9887 case ICmpInst::ICMP_SLE: 9888 return 9889 // min(A, ...) <= A 9890 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9891 // A <= max(A, ...) 9892 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9893 9894 case ICmpInst::ICMP_UGE: 9895 std::swap(LHS, RHS); 9896 LLVM_FALLTHROUGH; 9897 case ICmpInst::ICMP_ULE: 9898 return 9899 // min(A, ...) <= A 9900 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9901 // A <= max(A, ...) 9902 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9903 } 9904 9905 llvm_unreachable("covered switch fell through?!"); 9906 } 9907 9908 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9909 const SCEV *LHS, const SCEV *RHS, 9910 const SCEV *FoundLHS, 9911 const SCEV *FoundRHS, 9912 unsigned Depth) { 9913 assert(getTypeSizeInBits(LHS->getType()) == 9914 getTypeSizeInBits(RHS->getType()) && 9915 "LHS and RHS have different sizes?"); 9916 assert(getTypeSizeInBits(FoundLHS->getType()) == 9917 getTypeSizeInBits(FoundRHS->getType()) && 9918 "FoundLHS and FoundRHS have different sizes?"); 9919 // We want to avoid hurting the compile time with analysis of too big trees. 9920 if (Depth > MaxSCEVOperationsImplicationDepth) 9921 return false; 9922 // We only want to work with ICMP_SGT comparison so far. 9923 // TODO: Extend to ICMP_UGT? 9924 if (Pred == ICmpInst::ICMP_SLT) { 9925 Pred = ICmpInst::ICMP_SGT; 9926 std::swap(LHS, RHS); 9927 std::swap(FoundLHS, FoundRHS); 9928 } 9929 if (Pred != ICmpInst::ICMP_SGT) 9930 return false; 9931 9932 auto GetOpFromSExt = [&](const SCEV *S) { 9933 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9934 return Ext->getOperand(); 9935 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9936 // the constant in some cases. 9937 return S; 9938 }; 9939 9940 // Acquire values from extensions. 9941 auto *OrigLHS = LHS; 9942 auto *OrigFoundLHS = FoundLHS; 9943 LHS = GetOpFromSExt(LHS); 9944 FoundLHS = GetOpFromSExt(FoundLHS); 9945 9946 // Is the SGT predicate can be proved trivially or using the found context. 9947 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9948 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9949 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9950 FoundRHS, Depth + 1); 9951 }; 9952 9953 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9954 // We want to avoid creation of any new non-constant SCEV. Since we are 9955 // going to compare the operands to RHS, we should be certain that we don't 9956 // need any size extensions for this. So let's decline all cases when the 9957 // sizes of types of LHS and RHS do not match. 9958 // TODO: Maybe try to get RHS from sext to catch more cases? 9959 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9960 return false; 9961 9962 // Should not overflow. 9963 if (!LHSAddExpr->hasNoSignedWrap()) 9964 return false; 9965 9966 auto *LL = LHSAddExpr->getOperand(0); 9967 auto *LR = LHSAddExpr->getOperand(1); 9968 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9969 9970 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9971 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9972 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9973 }; 9974 // Try to prove the following rule: 9975 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9976 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9977 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9978 return true; 9979 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9980 Value *LL, *LR; 9981 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9982 9983 using namespace llvm::PatternMatch; 9984 9985 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9986 // Rules for division. 9987 // We are going to perform some comparisons with Denominator and its 9988 // derivative expressions. In general case, creating a SCEV for it may 9989 // lead to a complex analysis of the entire graph, and in particular it 9990 // can request trip count recalculation for the same loop. This would 9991 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9992 // this, we only want to create SCEVs that are constants in this section. 9993 // So we bail if Denominator is not a constant. 9994 if (!isa<ConstantInt>(LR)) 9995 return false; 9996 9997 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9998 9999 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10000 // then a SCEV for the numerator already exists and matches with FoundLHS. 10001 auto *Numerator = getExistingSCEV(LL); 10002 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10003 return false; 10004 10005 // Make sure that the numerator matches with FoundLHS and the denominator 10006 // is positive. 10007 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10008 return false; 10009 10010 auto *DTy = Denominator->getType(); 10011 auto *FRHSTy = FoundRHS->getType(); 10012 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10013 // One of types is a pointer and another one is not. We cannot extend 10014 // them properly to a wider type, so let us just reject this case. 10015 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10016 // to avoid this check. 10017 return false; 10018 10019 // Given that: 10020 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10021 auto *WTy = getWiderType(DTy, FRHSTy); 10022 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10023 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10024 10025 // Try to prove the following rule: 10026 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10027 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10028 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10029 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10030 if (isKnownNonPositive(RHS) && 10031 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10032 return true; 10033 10034 // Try to prove the following rule: 10035 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10036 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10037 // If we divide it by Denominator > 2, then: 10038 // 1. If FoundLHS is negative, then the result is 0. 10039 // 2. If FoundLHS is non-negative, then the result is non-negative. 10040 // Anyways, the result is non-negative. 10041 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10042 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10043 if (isKnownNegative(RHS) && 10044 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10045 return true; 10046 } 10047 } 10048 10049 // If our expression contained SCEVUnknown Phis, and we split it down and now 10050 // need to prove something for them, try to prove the predicate for every 10051 // possible incoming values of those Phis. 10052 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10053 return true; 10054 10055 return false; 10056 } 10057 10058 bool 10059 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10060 const SCEV *LHS, const SCEV *RHS) { 10061 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10062 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10063 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10064 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10065 } 10066 10067 bool 10068 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10069 const SCEV *LHS, const SCEV *RHS, 10070 const SCEV *FoundLHS, 10071 const SCEV *FoundRHS) { 10072 switch (Pred) { 10073 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10074 case ICmpInst::ICMP_EQ: 10075 case ICmpInst::ICMP_NE: 10076 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10077 return true; 10078 break; 10079 case ICmpInst::ICMP_SLT: 10080 case ICmpInst::ICMP_SLE: 10081 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10082 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10083 return true; 10084 break; 10085 case ICmpInst::ICMP_SGT: 10086 case ICmpInst::ICMP_SGE: 10087 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10088 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10089 return true; 10090 break; 10091 case ICmpInst::ICMP_ULT: 10092 case ICmpInst::ICMP_ULE: 10093 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10094 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10095 return true; 10096 break; 10097 case ICmpInst::ICMP_UGT: 10098 case ICmpInst::ICMP_UGE: 10099 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10100 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10101 return true; 10102 break; 10103 } 10104 10105 // Maybe it can be proved via operations? 10106 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10107 return true; 10108 10109 return false; 10110 } 10111 10112 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10113 const SCEV *LHS, 10114 const SCEV *RHS, 10115 const SCEV *FoundLHS, 10116 const SCEV *FoundRHS) { 10117 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10118 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10119 // reduce the compile time impact of this optimization. 10120 return false; 10121 10122 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10123 if (!Addend) 10124 return false; 10125 10126 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10127 10128 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10129 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10130 ConstantRange FoundLHSRange = 10131 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10132 10133 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10134 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10135 10136 // We can also compute the range of values for `LHS` that satisfy the 10137 // consequent, "`LHS` `Pred` `RHS`": 10138 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10139 ConstantRange SatisfyingLHSRange = 10140 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10141 10142 // The antecedent implies the consequent if every value of `LHS` that 10143 // satisfies the antecedent also satisfies the consequent. 10144 return SatisfyingLHSRange.contains(LHSRange); 10145 } 10146 10147 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10148 bool IsSigned, bool NoWrap) { 10149 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10150 10151 if (NoWrap) return false; 10152 10153 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10154 const SCEV *One = getOne(Stride->getType()); 10155 10156 if (IsSigned) { 10157 APInt MaxRHS = getSignedRangeMax(RHS); 10158 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10159 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10160 10161 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10162 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10163 } 10164 10165 APInt MaxRHS = getUnsignedRangeMax(RHS); 10166 APInt MaxValue = APInt::getMaxValue(BitWidth); 10167 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10168 10169 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10170 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10171 } 10172 10173 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10174 bool IsSigned, bool NoWrap) { 10175 if (NoWrap) return false; 10176 10177 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10178 const SCEV *One = getOne(Stride->getType()); 10179 10180 if (IsSigned) { 10181 APInt MinRHS = getSignedRangeMin(RHS); 10182 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10183 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10184 10185 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10186 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10187 } 10188 10189 APInt MinRHS = getUnsignedRangeMin(RHS); 10190 APInt MinValue = APInt::getMinValue(BitWidth); 10191 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10192 10193 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10194 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10195 } 10196 10197 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10198 bool Equality) { 10199 const SCEV *One = getOne(Step->getType()); 10200 Delta = Equality ? getAddExpr(Delta, Step) 10201 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10202 return getUDivExpr(Delta, Step); 10203 } 10204 10205 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10206 const SCEV *Stride, 10207 const SCEV *End, 10208 unsigned BitWidth, 10209 bool IsSigned) { 10210 10211 assert(!isKnownNonPositive(Stride) && 10212 "Stride is expected strictly positive!"); 10213 // Calculate the maximum backedge count based on the range of values 10214 // permitted by Start, End, and Stride. 10215 const SCEV *MaxBECount; 10216 APInt MinStart = 10217 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10218 10219 APInt StrideForMaxBECount = 10220 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10221 10222 // We already know that the stride is positive, so we paper over conservatism 10223 // in our range computation by forcing StrideForMaxBECount to be at least one. 10224 // In theory this is unnecessary, but we expect MaxBECount to be a 10225 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10226 // is nothing to constant fold it to). 10227 APInt One(BitWidth, 1, IsSigned); 10228 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10229 10230 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10231 : APInt::getMaxValue(BitWidth); 10232 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10233 10234 // Although End can be a MAX expression we estimate MaxEnd considering only 10235 // the case End = RHS of the loop termination condition. This is safe because 10236 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10237 // taken count. 10238 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10239 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10240 10241 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10242 getConstant(StrideForMaxBECount) /* Step */, 10243 false /* Equality */); 10244 10245 return MaxBECount; 10246 } 10247 10248 ScalarEvolution::ExitLimit 10249 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10250 const Loop *L, bool IsSigned, 10251 bool ControlsExit, bool AllowPredicates) { 10252 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10253 10254 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10255 bool PredicatedIV = false; 10256 10257 if (!IV && AllowPredicates) { 10258 // Try to make this an AddRec using runtime tests, in the first X 10259 // iterations of this loop, where X is the SCEV expression found by the 10260 // algorithm below. 10261 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10262 PredicatedIV = true; 10263 } 10264 10265 // Avoid weird loops 10266 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10267 return getCouldNotCompute(); 10268 10269 bool NoWrap = ControlsExit && 10270 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10271 10272 const SCEV *Stride = IV->getStepRecurrence(*this); 10273 10274 bool PositiveStride = isKnownPositive(Stride); 10275 10276 // Avoid negative or zero stride values. 10277 if (!PositiveStride) { 10278 // We can compute the correct backedge taken count for loops with unknown 10279 // strides if we can prove that the loop is not an infinite loop with side 10280 // effects. Here's the loop structure we are trying to handle - 10281 // 10282 // i = start 10283 // do { 10284 // A[i] = i; 10285 // i += s; 10286 // } while (i < end); 10287 // 10288 // The backedge taken count for such loops is evaluated as - 10289 // (max(end, start + stride) - start - 1) /u stride 10290 // 10291 // The additional preconditions that we need to check to prove correctness 10292 // of the above formula is as follows - 10293 // 10294 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10295 // NoWrap flag). 10296 // b) loop is single exit with no side effects. 10297 // 10298 // 10299 // Precondition a) implies that if the stride is negative, this is a single 10300 // trip loop. The backedge taken count formula reduces to zero in this case. 10301 // 10302 // Precondition b) implies that the unknown stride cannot be zero otherwise 10303 // we have UB. 10304 // 10305 // The positive stride case is the same as isKnownPositive(Stride) returning 10306 // true (original behavior of the function). 10307 // 10308 // We want to make sure that the stride is truly unknown as there are edge 10309 // cases where ScalarEvolution propagates no wrap flags to the 10310 // post-increment/decrement IV even though the increment/decrement operation 10311 // itself is wrapping. The computed backedge taken count may be wrong in 10312 // such cases. This is prevented by checking that the stride is not known to 10313 // be either positive or non-positive. For example, no wrap flags are 10314 // propagated to the post-increment IV of this loop with a trip count of 2 - 10315 // 10316 // unsigned char i; 10317 // for(i=127; i<128; i+=129) 10318 // A[i] = i; 10319 // 10320 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10321 !loopHasNoSideEffects(L)) 10322 return getCouldNotCompute(); 10323 } else if (!Stride->isOne() && 10324 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10325 // Avoid proven overflow cases: this will ensure that the backedge taken 10326 // count will not generate any unsigned overflow. Relaxed no-overflow 10327 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10328 // undefined behaviors like the case of C language. 10329 return getCouldNotCompute(); 10330 10331 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10332 : ICmpInst::ICMP_ULT; 10333 const SCEV *Start = IV->getStart(); 10334 const SCEV *End = RHS; 10335 // When the RHS is not invariant, we do not know the end bound of the loop and 10336 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10337 // calculate the MaxBECount, given the start, stride and max value for the end 10338 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10339 // checked above). 10340 if (!isLoopInvariant(RHS, L)) { 10341 const SCEV *MaxBECount = computeMaxBECountForLT( 10342 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10343 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10344 false /*MaxOrZero*/, Predicates); 10345 } 10346 // If the backedge is taken at least once, then it will be taken 10347 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10348 // is the LHS value of the less-than comparison the first time it is evaluated 10349 // and End is the RHS. 10350 const SCEV *BECountIfBackedgeTaken = 10351 computeBECount(getMinusSCEV(End, Start), Stride, false); 10352 // If the loop entry is guarded by the result of the backedge test of the 10353 // first loop iteration, then we know the backedge will be taken at least 10354 // once and so the backedge taken count is as above. If not then we use the 10355 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10356 // as if the backedge is taken at least once max(End,Start) is End and so the 10357 // result is as above, and if not max(End,Start) is Start so we get a backedge 10358 // count of zero. 10359 const SCEV *BECount; 10360 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10361 BECount = BECountIfBackedgeTaken; 10362 else { 10363 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10364 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10365 } 10366 10367 const SCEV *MaxBECount; 10368 bool MaxOrZero = false; 10369 if (isa<SCEVConstant>(BECount)) 10370 MaxBECount = BECount; 10371 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10372 // If we know exactly how many times the backedge will be taken if it's 10373 // taken at least once, then the backedge count will either be that or 10374 // zero. 10375 MaxBECount = BECountIfBackedgeTaken; 10376 MaxOrZero = true; 10377 } else { 10378 MaxBECount = computeMaxBECountForLT( 10379 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10380 } 10381 10382 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10383 !isa<SCEVCouldNotCompute>(BECount)) 10384 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10385 10386 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10387 } 10388 10389 ScalarEvolution::ExitLimit 10390 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10391 const Loop *L, bool IsSigned, 10392 bool ControlsExit, bool AllowPredicates) { 10393 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10394 // We handle only IV > Invariant 10395 if (!isLoopInvariant(RHS, L)) 10396 return getCouldNotCompute(); 10397 10398 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10399 if (!IV && AllowPredicates) 10400 // Try to make this an AddRec using runtime tests, in the first X 10401 // iterations of this loop, where X is the SCEV expression found by the 10402 // algorithm below. 10403 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10404 10405 // Avoid weird loops 10406 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10407 return getCouldNotCompute(); 10408 10409 bool NoWrap = ControlsExit && 10410 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10411 10412 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10413 10414 // Avoid negative or zero stride values 10415 if (!isKnownPositive(Stride)) 10416 return getCouldNotCompute(); 10417 10418 // Avoid proven overflow cases: this will ensure that the backedge taken count 10419 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10420 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10421 // behaviors like the case of C language. 10422 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10423 return getCouldNotCompute(); 10424 10425 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10426 : ICmpInst::ICMP_UGT; 10427 10428 const SCEV *Start = IV->getStart(); 10429 const SCEV *End = RHS; 10430 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10431 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10432 10433 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10434 10435 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10436 : getUnsignedRangeMax(Start); 10437 10438 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10439 : getUnsignedRangeMin(Stride); 10440 10441 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10442 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10443 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10444 10445 // Although End can be a MIN expression we estimate MinEnd considering only 10446 // the case End = RHS. This is safe because in the other case (Start - End) 10447 // is zero, leading to a zero maximum backedge taken count. 10448 APInt MinEnd = 10449 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10450 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10451 10452 10453 const SCEV *MaxBECount = getCouldNotCompute(); 10454 if (isa<SCEVConstant>(BECount)) 10455 MaxBECount = BECount; 10456 else 10457 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10458 getConstant(MinStride), false); 10459 10460 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10461 MaxBECount = BECount; 10462 10463 return ExitLimit(BECount, MaxBECount, false, Predicates); 10464 } 10465 10466 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10467 ScalarEvolution &SE) const { 10468 if (Range.isFullSet()) // Infinite loop. 10469 return SE.getCouldNotCompute(); 10470 10471 // If the start is a non-zero constant, shift the range to simplify things. 10472 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10473 if (!SC->getValue()->isZero()) { 10474 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10475 Operands[0] = SE.getZero(SC->getType()); 10476 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10477 getNoWrapFlags(FlagNW)); 10478 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10479 return ShiftedAddRec->getNumIterationsInRange( 10480 Range.subtract(SC->getAPInt()), SE); 10481 // This is strange and shouldn't happen. 10482 return SE.getCouldNotCompute(); 10483 } 10484 10485 // The only time we can solve this is when we have all constant indices. 10486 // Otherwise, we cannot determine the overflow conditions. 10487 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10488 return SE.getCouldNotCompute(); 10489 10490 // Okay at this point we know that all elements of the chrec are constants and 10491 // that the start element is zero. 10492 10493 // First check to see if the range contains zero. If not, the first 10494 // iteration exits. 10495 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10496 if (!Range.contains(APInt(BitWidth, 0))) 10497 return SE.getZero(getType()); 10498 10499 if (isAffine()) { 10500 // If this is an affine expression then we have this situation: 10501 // Solve {0,+,A} in Range === Ax in Range 10502 10503 // We know that zero is in the range. If A is positive then we know that 10504 // the upper value of the range must be the first possible exit value. 10505 // If A is negative then the lower of the range is the last possible loop 10506 // value. Also note that we already checked for a full range. 10507 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10508 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10509 10510 // The exit value should be (End+A)/A. 10511 APInt ExitVal = (End + A).udiv(A); 10512 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10513 10514 // Evaluate at the exit value. If we really did fall out of the valid 10515 // range, then we computed our trip count, otherwise wrap around or other 10516 // things must have happened. 10517 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10518 if (Range.contains(Val->getValue())) 10519 return SE.getCouldNotCompute(); // Something strange happened 10520 10521 // Ensure that the previous value is in the range. This is a sanity check. 10522 assert(Range.contains( 10523 EvaluateConstantChrecAtConstant(this, 10524 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10525 "Linear scev computation is off in a bad way!"); 10526 return SE.getConstant(ExitValue); 10527 } else if (isQuadratic()) { 10528 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10529 // quadratic equation to solve it. To do this, we must frame our problem in 10530 // terms of figuring out when zero is crossed, instead of when 10531 // Range.getUpper() is crossed. 10532 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10533 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10534 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10535 10536 // Next, solve the constructed addrec 10537 if (auto Roots = 10538 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10539 const SCEVConstant *R1 = Roots->first; 10540 const SCEVConstant *R2 = Roots->second; 10541 // Pick the smallest positive root value. 10542 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10543 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10544 if (!CB->getZExtValue()) 10545 std::swap(R1, R2); // R1 is the minimum root now. 10546 10547 // Make sure the root is not off by one. The returned iteration should 10548 // not be in the range, but the previous one should be. When solving 10549 // for "X*X < 5", for example, we should not return a root of 2. 10550 ConstantInt *R1Val = 10551 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10552 if (Range.contains(R1Val->getValue())) { 10553 // The next iteration must be out of the range... 10554 ConstantInt *NextVal = 10555 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10556 10557 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10558 if (!Range.contains(R1Val->getValue())) 10559 return SE.getConstant(NextVal); 10560 return SE.getCouldNotCompute(); // Something strange happened 10561 } 10562 10563 // If R1 was not in the range, then it is a good return value. Make 10564 // sure that R1-1 WAS in the range though, just in case. 10565 ConstantInt *NextVal = 10566 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10567 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10568 if (Range.contains(R1Val->getValue())) 10569 return R1; 10570 return SE.getCouldNotCompute(); // Something strange happened 10571 } 10572 } 10573 } 10574 10575 return SE.getCouldNotCompute(); 10576 } 10577 10578 const SCEVAddRecExpr * 10579 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10580 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10581 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10582 // but in this case we cannot guarantee that the value returned will be an 10583 // AddRec because SCEV does not have a fixed point where it stops 10584 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10585 // may happen if we reach arithmetic depth limit while simplifying. So we 10586 // construct the returned value explicitly. 10587 SmallVector<const SCEV *, 3> Ops; 10588 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10589 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10590 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10591 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10592 // We know that the last operand is not a constant zero (otherwise it would 10593 // have been popped out earlier). This guarantees us that if the result has 10594 // the same last operand, then it will also not be popped out, meaning that 10595 // the returned value will be an AddRec. 10596 const SCEV *Last = getOperand(getNumOperands() - 1); 10597 assert(!Last->isZero() && "Recurrency with zero step?"); 10598 Ops.push_back(Last); 10599 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10600 SCEV::FlagAnyWrap)); 10601 } 10602 10603 // Return true when S contains at least an undef value. 10604 static inline bool containsUndefs(const SCEV *S) { 10605 return SCEVExprContains(S, [](const SCEV *S) { 10606 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10607 return isa<UndefValue>(SU->getValue()); 10608 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10609 return isa<UndefValue>(SC->getValue()); 10610 return false; 10611 }); 10612 } 10613 10614 namespace { 10615 10616 // Collect all steps of SCEV expressions. 10617 struct SCEVCollectStrides { 10618 ScalarEvolution &SE; 10619 SmallVectorImpl<const SCEV *> &Strides; 10620 10621 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10622 : SE(SE), Strides(S) {} 10623 10624 bool follow(const SCEV *S) { 10625 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10626 Strides.push_back(AR->getStepRecurrence(SE)); 10627 return true; 10628 } 10629 10630 bool isDone() const { return false; } 10631 }; 10632 10633 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10634 struct SCEVCollectTerms { 10635 SmallVectorImpl<const SCEV *> &Terms; 10636 10637 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10638 10639 bool follow(const SCEV *S) { 10640 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10641 isa<SCEVSignExtendExpr>(S)) { 10642 if (!containsUndefs(S)) 10643 Terms.push_back(S); 10644 10645 // Stop recursion: once we collected a term, do not walk its operands. 10646 return false; 10647 } 10648 10649 // Keep looking. 10650 return true; 10651 } 10652 10653 bool isDone() const { return false; } 10654 }; 10655 10656 // Check if a SCEV contains an AddRecExpr. 10657 struct SCEVHasAddRec { 10658 bool &ContainsAddRec; 10659 10660 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10661 ContainsAddRec = false; 10662 } 10663 10664 bool follow(const SCEV *S) { 10665 if (isa<SCEVAddRecExpr>(S)) { 10666 ContainsAddRec = true; 10667 10668 // Stop recursion: once we collected a term, do not walk its operands. 10669 return false; 10670 } 10671 10672 // Keep looking. 10673 return true; 10674 } 10675 10676 bool isDone() const { return false; } 10677 }; 10678 10679 // Find factors that are multiplied with an expression that (possibly as a 10680 // subexpression) contains an AddRecExpr. In the expression: 10681 // 10682 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10683 // 10684 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10685 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10686 // parameters as they form a product with an induction variable. 10687 // 10688 // This collector expects all array size parameters to be in the same MulExpr. 10689 // It might be necessary to later add support for collecting parameters that are 10690 // spread over different nested MulExpr. 10691 struct SCEVCollectAddRecMultiplies { 10692 SmallVectorImpl<const SCEV *> &Terms; 10693 ScalarEvolution &SE; 10694 10695 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10696 : Terms(T), SE(SE) {} 10697 10698 bool follow(const SCEV *S) { 10699 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10700 bool HasAddRec = false; 10701 SmallVector<const SCEV *, 0> Operands; 10702 for (auto Op : Mul->operands()) { 10703 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10704 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10705 Operands.push_back(Op); 10706 } else if (Unknown) { 10707 HasAddRec = true; 10708 } else { 10709 bool ContainsAddRec; 10710 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10711 visitAll(Op, ContiansAddRec); 10712 HasAddRec |= ContainsAddRec; 10713 } 10714 } 10715 if (Operands.size() == 0) 10716 return true; 10717 10718 if (!HasAddRec) 10719 return false; 10720 10721 Terms.push_back(SE.getMulExpr(Operands)); 10722 // Stop recursion: once we collected a term, do not walk its operands. 10723 return false; 10724 } 10725 10726 // Keep looking. 10727 return true; 10728 } 10729 10730 bool isDone() const { return false; } 10731 }; 10732 10733 } // end anonymous namespace 10734 10735 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10736 /// two places: 10737 /// 1) The strides of AddRec expressions. 10738 /// 2) Unknowns that are multiplied with AddRec expressions. 10739 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10740 SmallVectorImpl<const SCEV *> &Terms) { 10741 SmallVector<const SCEV *, 4> Strides; 10742 SCEVCollectStrides StrideCollector(*this, Strides); 10743 visitAll(Expr, StrideCollector); 10744 10745 LLVM_DEBUG({ 10746 dbgs() << "Strides:\n"; 10747 for (const SCEV *S : Strides) 10748 dbgs() << *S << "\n"; 10749 }); 10750 10751 for (const SCEV *S : Strides) { 10752 SCEVCollectTerms TermCollector(Terms); 10753 visitAll(S, TermCollector); 10754 } 10755 10756 LLVM_DEBUG({ 10757 dbgs() << "Terms:\n"; 10758 for (const SCEV *T : Terms) 10759 dbgs() << *T << "\n"; 10760 }); 10761 10762 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10763 visitAll(Expr, MulCollector); 10764 } 10765 10766 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10767 SmallVectorImpl<const SCEV *> &Terms, 10768 SmallVectorImpl<const SCEV *> &Sizes) { 10769 int Last = Terms.size() - 1; 10770 const SCEV *Step = Terms[Last]; 10771 10772 // End of recursion. 10773 if (Last == 0) { 10774 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10775 SmallVector<const SCEV *, 2> Qs; 10776 for (const SCEV *Op : M->operands()) 10777 if (!isa<SCEVConstant>(Op)) 10778 Qs.push_back(Op); 10779 10780 Step = SE.getMulExpr(Qs); 10781 } 10782 10783 Sizes.push_back(Step); 10784 return true; 10785 } 10786 10787 for (const SCEV *&Term : Terms) { 10788 // Normalize the terms before the next call to findArrayDimensionsRec. 10789 const SCEV *Q, *R; 10790 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10791 10792 // Bail out when GCD does not evenly divide one of the terms. 10793 if (!R->isZero()) 10794 return false; 10795 10796 Term = Q; 10797 } 10798 10799 // Remove all SCEVConstants. 10800 Terms.erase( 10801 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10802 Terms.end()); 10803 10804 if (Terms.size() > 0) 10805 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10806 return false; 10807 10808 Sizes.push_back(Step); 10809 return true; 10810 } 10811 10812 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10813 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10814 for (const SCEV *T : Terms) 10815 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10816 return true; 10817 return false; 10818 } 10819 10820 // Return the number of product terms in S. 10821 static inline int numberOfTerms(const SCEV *S) { 10822 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10823 return Expr->getNumOperands(); 10824 return 1; 10825 } 10826 10827 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10828 if (isa<SCEVConstant>(T)) 10829 return nullptr; 10830 10831 if (isa<SCEVUnknown>(T)) 10832 return T; 10833 10834 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10835 SmallVector<const SCEV *, 2> Factors; 10836 for (const SCEV *Op : M->operands()) 10837 if (!isa<SCEVConstant>(Op)) 10838 Factors.push_back(Op); 10839 10840 return SE.getMulExpr(Factors); 10841 } 10842 10843 return T; 10844 } 10845 10846 /// Return the size of an element read or written by Inst. 10847 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10848 Type *Ty; 10849 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10850 Ty = Store->getValueOperand()->getType(); 10851 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10852 Ty = Load->getType(); 10853 else 10854 return nullptr; 10855 10856 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10857 return getSizeOfExpr(ETy, Ty); 10858 } 10859 10860 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10861 SmallVectorImpl<const SCEV *> &Sizes, 10862 const SCEV *ElementSize) { 10863 if (Terms.size() < 1 || !ElementSize) 10864 return; 10865 10866 // Early return when Terms do not contain parameters: we do not delinearize 10867 // non parametric SCEVs. 10868 if (!containsParameters(Terms)) 10869 return; 10870 10871 LLVM_DEBUG({ 10872 dbgs() << "Terms:\n"; 10873 for (const SCEV *T : Terms) 10874 dbgs() << *T << "\n"; 10875 }); 10876 10877 // Remove duplicates. 10878 array_pod_sort(Terms.begin(), Terms.end()); 10879 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10880 10881 // Put larger terms first. 10882 llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10883 return numberOfTerms(LHS) > numberOfTerms(RHS); 10884 }); 10885 10886 // Try to divide all terms by the element size. If term is not divisible by 10887 // element size, proceed with the original term. 10888 for (const SCEV *&Term : Terms) { 10889 const SCEV *Q, *R; 10890 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10891 if (!Q->isZero()) 10892 Term = Q; 10893 } 10894 10895 SmallVector<const SCEV *, 4> NewTerms; 10896 10897 // Remove constant factors. 10898 for (const SCEV *T : Terms) 10899 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10900 NewTerms.push_back(NewT); 10901 10902 LLVM_DEBUG({ 10903 dbgs() << "Terms after sorting:\n"; 10904 for (const SCEV *T : NewTerms) 10905 dbgs() << *T << "\n"; 10906 }); 10907 10908 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10909 Sizes.clear(); 10910 return; 10911 } 10912 10913 // The last element to be pushed into Sizes is the size of an element. 10914 Sizes.push_back(ElementSize); 10915 10916 LLVM_DEBUG({ 10917 dbgs() << "Sizes:\n"; 10918 for (const SCEV *S : Sizes) 10919 dbgs() << *S << "\n"; 10920 }); 10921 } 10922 10923 void ScalarEvolution::computeAccessFunctions( 10924 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10925 SmallVectorImpl<const SCEV *> &Sizes) { 10926 // Early exit in case this SCEV is not an affine multivariate function. 10927 if (Sizes.empty()) 10928 return; 10929 10930 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10931 if (!AR->isAffine()) 10932 return; 10933 10934 const SCEV *Res = Expr; 10935 int Last = Sizes.size() - 1; 10936 for (int i = Last; i >= 0; i--) { 10937 const SCEV *Q, *R; 10938 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10939 10940 LLVM_DEBUG({ 10941 dbgs() << "Res: " << *Res << "\n"; 10942 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10943 dbgs() << "Res divided by Sizes[i]:\n"; 10944 dbgs() << "Quotient: " << *Q << "\n"; 10945 dbgs() << "Remainder: " << *R << "\n"; 10946 }); 10947 10948 Res = Q; 10949 10950 // Do not record the last subscript corresponding to the size of elements in 10951 // the array. 10952 if (i == Last) { 10953 10954 // Bail out if the remainder is too complex. 10955 if (isa<SCEVAddRecExpr>(R)) { 10956 Subscripts.clear(); 10957 Sizes.clear(); 10958 return; 10959 } 10960 10961 continue; 10962 } 10963 10964 // Record the access function for the current subscript. 10965 Subscripts.push_back(R); 10966 } 10967 10968 // Also push in last position the remainder of the last division: it will be 10969 // the access function of the innermost dimension. 10970 Subscripts.push_back(Res); 10971 10972 std::reverse(Subscripts.begin(), Subscripts.end()); 10973 10974 LLVM_DEBUG({ 10975 dbgs() << "Subscripts:\n"; 10976 for (const SCEV *S : Subscripts) 10977 dbgs() << *S << "\n"; 10978 }); 10979 } 10980 10981 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10982 /// sizes of an array access. Returns the remainder of the delinearization that 10983 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10984 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10985 /// expressions in the stride and base of a SCEV corresponding to the 10986 /// computation of a GCD (greatest common divisor) of base and stride. When 10987 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10988 /// 10989 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10990 /// 10991 /// void foo(long n, long m, long o, double A[n][m][o]) { 10992 /// 10993 /// for (long i = 0; i < n; i++) 10994 /// for (long j = 0; j < m; j++) 10995 /// for (long k = 0; k < o; k++) 10996 /// A[i][j][k] = 1.0; 10997 /// } 10998 /// 10999 /// the delinearization input is the following AddRec SCEV: 11000 /// 11001 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11002 /// 11003 /// From this SCEV, we are able to say that the base offset of the access is %A 11004 /// because it appears as an offset that does not divide any of the strides in 11005 /// the loops: 11006 /// 11007 /// CHECK: Base offset: %A 11008 /// 11009 /// and then SCEV->delinearize determines the size of some of the dimensions of 11010 /// the array as these are the multiples by which the strides are happening: 11011 /// 11012 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11013 /// 11014 /// Note that the outermost dimension remains of UnknownSize because there are 11015 /// no strides that would help identifying the size of the last dimension: when 11016 /// the array has been statically allocated, one could compute the size of that 11017 /// dimension by dividing the overall size of the array by the size of the known 11018 /// dimensions: %m * %o * 8. 11019 /// 11020 /// Finally delinearize provides the access functions for the array reference 11021 /// that does correspond to A[i][j][k] of the above C testcase: 11022 /// 11023 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11024 /// 11025 /// The testcases are checking the output of a function pass: 11026 /// DelinearizationPass that walks through all loads and stores of a function 11027 /// asking for the SCEV of the memory access with respect to all enclosing 11028 /// loops, calling SCEV->delinearize on that and printing the results. 11029 void ScalarEvolution::delinearize(const SCEV *Expr, 11030 SmallVectorImpl<const SCEV *> &Subscripts, 11031 SmallVectorImpl<const SCEV *> &Sizes, 11032 const SCEV *ElementSize) { 11033 // First step: collect parametric terms. 11034 SmallVector<const SCEV *, 4> Terms; 11035 collectParametricTerms(Expr, Terms); 11036 11037 if (Terms.empty()) 11038 return; 11039 11040 // Second step: find subscript sizes. 11041 findArrayDimensions(Terms, Sizes, ElementSize); 11042 11043 if (Sizes.empty()) 11044 return; 11045 11046 // Third step: compute the access functions for each subscript. 11047 computeAccessFunctions(Expr, Subscripts, Sizes); 11048 11049 if (Subscripts.empty()) 11050 return; 11051 11052 LLVM_DEBUG({ 11053 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11054 dbgs() << "ArrayDecl[UnknownSize]"; 11055 for (const SCEV *S : Sizes) 11056 dbgs() << "[" << *S << "]"; 11057 11058 dbgs() << "\nArrayRef"; 11059 for (const SCEV *S : Subscripts) 11060 dbgs() << "[" << *S << "]"; 11061 dbgs() << "\n"; 11062 }); 11063 } 11064 11065 //===----------------------------------------------------------------------===// 11066 // SCEVCallbackVH Class Implementation 11067 //===----------------------------------------------------------------------===// 11068 11069 void ScalarEvolution::SCEVCallbackVH::deleted() { 11070 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11071 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11072 SE->ConstantEvolutionLoopExitValue.erase(PN); 11073 SE->eraseValueFromMap(getValPtr()); 11074 // this now dangles! 11075 } 11076 11077 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11078 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11079 11080 // Forget all the expressions associated with users of the old value, 11081 // so that future queries will recompute the expressions using the new 11082 // value. 11083 Value *Old = getValPtr(); 11084 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11085 SmallPtrSet<User *, 8> Visited; 11086 while (!Worklist.empty()) { 11087 User *U = Worklist.pop_back_val(); 11088 // Deleting the Old value will cause this to dangle. Postpone 11089 // that until everything else is done. 11090 if (U == Old) 11091 continue; 11092 if (!Visited.insert(U).second) 11093 continue; 11094 if (PHINode *PN = dyn_cast<PHINode>(U)) 11095 SE->ConstantEvolutionLoopExitValue.erase(PN); 11096 SE->eraseValueFromMap(U); 11097 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11098 } 11099 // Delete the Old value. 11100 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11101 SE->ConstantEvolutionLoopExitValue.erase(PN); 11102 SE->eraseValueFromMap(Old); 11103 // this now dangles! 11104 } 11105 11106 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11107 : CallbackVH(V), SE(se) {} 11108 11109 //===----------------------------------------------------------------------===// 11110 // ScalarEvolution Class Implementation 11111 //===----------------------------------------------------------------------===// 11112 11113 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11114 AssumptionCache &AC, DominatorTree &DT, 11115 LoopInfo &LI) 11116 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11117 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11118 LoopDispositions(64), BlockDispositions(64) { 11119 // To use guards for proving predicates, we need to scan every instruction in 11120 // relevant basic blocks, and not just terminators. Doing this is a waste of 11121 // time if the IR does not actually contain any calls to 11122 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11123 // 11124 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11125 // to _add_ guards to the module when there weren't any before, and wants 11126 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11127 // efficient in lieu of being smart in that rather obscure case. 11128 11129 auto *GuardDecl = F.getParent()->getFunction( 11130 Intrinsic::getName(Intrinsic::experimental_guard)); 11131 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11132 } 11133 11134 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11135 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11136 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11137 ValueExprMap(std::move(Arg.ValueExprMap)), 11138 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11139 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11140 PendingMerges(std::move(Arg.PendingMerges)), 11141 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11142 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11143 PredicatedBackedgeTakenCounts( 11144 std::move(Arg.PredicatedBackedgeTakenCounts)), 11145 ConstantEvolutionLoopExitValue( 11146 std::move(Arg.ConstantEvolutionLoopExitValue)), 11147 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11148 LoopDispositions(std::move(Arg.LoopDispositions)), 11149 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11150 BlockDispositions(std::move(Arg.BlockDispositions)), 11151 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11152 SignedRanges(std::move(Arg.SignedRanges)), 11153 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11154 UniquePreds(std::move(Arg.UniquePreds)), 11155 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11156 LoopUsers(std::move(Arg.LoopUsers)), 11157 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11158 FirstUnknown(Arg.FirstUnknown) { 11159 Arg.FirstUnknown = nullptr; 11160 } 11161 11162 ScalarEvolution::~ScalarEvolution() { 11163 // Iterate through all the SCEVUnknown instances and call their 11164 // destructors, so that they release their references to their values. 11165 for (SCEVUnknown *U = FirstUnknown; U;) { 11166 SCEVUnknown *Tmp = U; 11167 U = U->Next; 11168 Tmp->~SCEVUnknown(); 11169 } 11170 FirstUnknown = nullptr; 11171 11172 ExprValueMap.clear(); 11173 ValueExprMap.clear(); 11174 HasRecMap.clear(); 11175 11176 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11177 // that a loop had multiple computable exits. 11178 for (auto &BTCI : BackedgeTakenCounts) 11179 BTCI.second.clear(); 11180 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11181 BTCI.second.clear(); 11182 11183 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11184 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11185 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11186 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11187 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11188 } 11189 11190 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11191 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11192 } 11193 11194 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11195 const Loop *L) { 11196 // Print all inner loops first 11197 for (Loop *I : *L) 11198 PrintLoopInfo(OS, SE, I); 11199 11200 OS << "Loop "; 11201 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11202 OS << ": "; 11203 11204 SmallVector<BasicBlock *, 8> ExitBlocks; 11205 L->getExitBlocks(ExitBlocks); 11206 if (ExitBlocks.size() != 1) 11207 OS << "<multiple exits> "; 11208 11209 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11210 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11211 } else { 11212 OS << "Unpredictable backedge-taken count. "; 11213 } 11214 11215 OS << "\n" 11216 "Loop "; 11217 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11218 OS << ": "; 11219 11220 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11221 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11222 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11223 OS << ", actual taken count either this or zero."; 11224 } else { 11225 OS << "Unpredictable max backedge-taken count. "; 11226 } 11227 11228 OS << "\n" 11229 "Loop "; 11230 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11231 OS << ": "; 11232 11233 SCEVUnionPredicate Pred; 11234 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11235 if (!isa<SCEVCouldNotCompute>(PBT)) { 11236 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11237 OS << " Predicates:\n"; 11238 Pred.print(OS, 4); 11239 } else { 11240 OS << "Unpredictable predicated backedge-taken count. "; 11241 } 11242 OS << "\n"; 11243 11244 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11245 OS << "Loop "; 11246 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11247 OS << ": "; 11248 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11249 } 11250 } 11251 11252 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11253 switch (LD) { 11254 case ScalarEvolution::LoopVariant: 11255 return "Variant"; 11256 case ScalarEvolution::LoopInvariant: 11257 return "Invariant"; 11258 case ScalarEvolution::LoopComputable: 11259 return "Computable"; 11260 } 11261 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11262 } 11263 11264 void ScalarEvolution::print(raw_ostream &OS) const { 11265 // ScalarEvolution's implementation of the print method is to print 11266 // out SCEV values of all instructions that are interesting. Doing 11267 // this potentially causes it to create new SCEV objects though, 11268 // which technically conflicts with the const qualifier. This isn't 11269 // observable from outside the class though, so casting away the 11270 // const isn't dangerous. 11271 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11272 11273 OS << "Classifying expressions for: "; 11274 F.printAsOperand(OS, /*PrintType=*/false); 11275 OS << "\n"; 11276 for (Instruction &I : instructions(F)) 11277 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11278 OS << I << '\n'; 11279 OS << " --> "; 11280 const SCEV *SV = SE.getSCEV(&I); 11281 SV->print(OS); 11282 if (!isa<SCEVCouldNotCompute>(SV)) { 11283 OS << " U: "; 11284 SE.getUnsignedRange(SV).print(OS); 11285 OS << " S: "; 11286 SE.getSignedRange(SV).print(OS); 11287 } 11288 11289 const Loop *L = LI.getLoopFor(I.getParent()); 11290 11291 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11292 if (AtUse != SV) { 11293 OS << " --> "; 11294 AtUse->print(OS); 11295 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11296 OS << " U: "; 11297 SE.getUnsignedRange(AtUse).print(OS); 11298 OS << " S: "; 11299 SE.getSignedRange(AtUse).print(OS); 11300 } 11301 } 11302 11303 if (L) { 11304 OS << "\t\t" "Exits: "; 11305 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11306 if (!SE.isLoopInvariant(ExitValue, L)) { 11307 OS << "<<Unknown>>"; 11308 } else { 11309 OS << *ExitValue; 11310 } 11311 11312 bool First = true; 11313 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11314 if (First) { 11315 OS << "\t\t" "LoopDispositions: { "; 11316 First = false; 11317 } else { 11318 OS << ", "; 11319 } 11320 11321 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11322 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11323 } 11324 11325 for (auto *InnerL : depth_first(L)) { 11326 if (InnerL == L) 11327 continue; 11328 if (First) { 11329 OS << "\t\t" "LoopDispositions: { "; 11330 First = false; 11331 } else { 11332 OS << ", "; 11333 } 11334 11335 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11336 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11337 } 11338 11339 OS << " }"; 11340 } 11341 11342 OS << "\n"; 11343 } 11344 11345 OS << "Determining loop execution counts for: "; 11346 F.printAsOperand(OS, /*PrintType=*/false); 11347 OS << "\n"; 11348 for (Loop *I : LI) 11349 PrintLoopInfo(OS, &SE, I); 11350 } 11351 11352 ScalarEvolution::LoopDisposition 11353 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11354 auto &Values = LoopDispositions[S]; 11355 for (auto &V : Values) { 11356 if (V.getPointer() == L) 11357 return V.getInt(); 11358 } 11359 Values.emplace_back(L, LoopVariant); 11360 LoopDisposition D = computeLoopDisposition(S, L); 11361 auto &Values2 = LoopDispositions[S]; 11362 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11363 if (V.getPointer() == L) { 11364 V.setInt(D); 11365 break; 11366 } 11367 } 11368 return D; 11369 } 11370 11371 ScalarEvolution::LoopDisposition 11372 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11373 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11374 case scConstant: 11375 return LoopInvariant; 11376 case scTruncate: 11377 case scZeroExtend: 11378 case scSignExtend: 11379 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11380 case scAddRecExpr: { 11381 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11382 11383 // If L is the addrec's loop, it's computable. 11384 if (AR->getLoop() == L) 11385 return LoopComputable; 11386 11387 // Add recurrences are never invariant in the function-body (null loop). 11388 if (!L) 11389 return LoopVariant; 11390 11391 // Everything that is not defined at loop entry is variant. 11392 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11393 return LoopVariant; 11394 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11395 " dominate the contained loop's header?"); 11396 11397 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11398 if (AR->getLoop()->contains(L)) 11399 return LoopInvariant; 11400 11401 // This recurrence is variant w.r.t. L if any of its operands 11402 // are variant. 11403 for (auto *Op : AR->operands()) 11404 if (!isLoopInvariant(Op, L)) 11405 return LoopVariant; 11406 11407 // Otherwise it's loop-invariant. 11408 return LoopInvariant; 11409 } 11410 case scAddExpr: 11411 case scMulExpr: 11412 case scUMaxExpr: 11413 case scSMaxExpr: { 11414 bool HasVarying = false; 11415 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11416 LoopDisposition D = getLoopDisposition(Op, L); 11417 if (D == LoopVariant) 11418 return LoopVariant; 11419 if (D == LoopComputable) 11420 HasVarying = true; 11421 } 11422 return HasVarying ? LoopComputable : LoopInvariant; 11423 } 11424 case scUDivExpr: { 11425 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11426 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11427 if (LD == LoopVariant) 11428 return LoopVariant; 11429 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11430 if (RD == LoopVariant) 11431 return LoopVariant; 11432 return (LD == LoopInvariant && RD == LoopInvariant) ? 11433 LoopInvariant : LoopComputable; 11434 } 11435 case scUnknown: 11436 // All non-instruction values are loop invariant. All instructions are loop 11437 // invariant if they are not contained in the specified loop. 11438 // Instructions are never considered invariant in the function body 11439 // (null loop) because they are defined within the "loop". 11440 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11441 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11442 return LoopInvariant; 11443 case scCouldNotCompute: 11444 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11445 } 11446 llvm_unreachable("Unknown SCEV kind!"); 11447 } 11448 11449 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11450 return getLoopDisposition(S, L) == LoopInvariant; 11451 } 11452 11453 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11454 return getLoopDisposition(S, L) == LoopComputable; 11455 } 11456 11457 ScalarEvolution::BlockDisposition 11458 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11459 auto &Values = BlockDispositions[S]; 11460 for (auto &V : Values) { 11461 if (V.getPointer() == BB) 11462 return V.getInt(); 11463 } 11464 Values.emplace_back(BB, DoesNotDominateBlock); 11465 BlockDisposition D = computeBlockDisposition(S, BB); 11466 auto &Values2 = BlockDispositions[S]; 11467 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11468 if (V.getPointer() == BB) { 11469 V.setInt(D); 11470 break; 11471 } 11472 } 11473 return D; 11474 } 11475 11476 ScalarEvolution::BlockDisposition 11477 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11478 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11479 case scConstant: 11480 return ProperlyDominatesBlock; 11481 case scTruncate: 11482 case scZeroExtend: 11483 case scSignExtend: 11484 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11485 case scAddRecExpr: { 11486 // This uses a "dominates" query instead of "properly dominates" query 11487 // to test for proper dominance too, because the instruction which 11488 // produces the addrec's value is a PHI, and a PHI effectively properly 11489 // dominates its entire containing block. 11490 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11491 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11492 return DoesNotDominateBlock; 11493 11494 // Fall through into SCEVNAryExpr handling. 11495 LLVM_FALLTHROUGH; 11496 } 11497 case scAddExpr: 11498 case scMulExpr: 11499 case scUMaxExpr: 11500 case scSMaxExpr: { 11501 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11502 bool Proper = true; 11503 for (const SCEV *NAryOp : NAry->operands()) { 11504 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11505 if (D == DoesNotDominateBlock) 11506 return DoesNotDominateBlock; 11507 if (D == DominatesBlock) 11508 Proper = false; 11509 } 11510 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11511 } 11512 case scUDivExpr: { 11513 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11514 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11515 BlockDisposition LD = getBlockDisposition(LHS, BB); 11516 if (LD == DoesNotDominateBlock) 11517 return DoesNotDominateBlock; 11518 BlockDisposition RD = getBlockDisposition(RHS, BB); 11519 if (RD == DoesNotDominateBlock) 11520 return DoesNotDominateBlock; 11521 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11522 ProperlyDominatesBlock : DominatesBlock; 11523 } 11524 case scUnknown: 11525 if (Instruction *I = 11526 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11527 if (I->getParent() == BB) 11528 return DominatesBlock; 11529 if (DT.properlyDominates(I->getParent(), BB)) 11530 return ProperlyDominatesBlock; 11531 return DoesNotDominateBlock; 11532 } 11533 return ProperlyDominatesBlock; 11534 case scCouldNotCompute: 11535 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11536 } 11537 llvm_unreachable("Unknown SCEV kind!"); 11538 } 11539 11540 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11541 return getBlockDisposition(S, BB) >= DominatesBlock; 11542 } 11543 11544 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11545 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11546 } 11547 11548 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11549 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11550 } 11551 11552 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11553 auto IsS = [&](const SCEV *X) { return S == X; }; 11554 auto ContainsS = [&](const SCEV *X) { 11555 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11556 }; 11557 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11558 } 11559 11560 void 11561 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11562 ValuesAtScopes.erase(S); 11563 LoopDispositions.erase(S); 11564 BlockDispositions.erase(S); 11565 UnsignedRanges.erase(S); 11566 SignedRanges.erase(S); 11567 ExprValueMap.erase(S); 11568 HasRecMap.erase(S); 11569 MinTrailingZerosCache.erase(S); 11570 11571 for (auto I = PredicatedSCEVRewrites.begin(); 11572 I != PredicatedSCEVRewrites.end();) { 11573 std::pair<const SCEV *, const Loop *> Entry = I->first; 11574 if (Entry.first == S) 11575 PredicatedSCEVRewrites.erase(I++); 11576 else 11577 ++I; 11578 } 11579 11580 auto RemoveSCEVFromBackedgeMap = 11581 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11582 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11583 BackedgeTakenInfo &BEInfo = I->second; 11584 if (BEInfo.hasOperand(S, this)) { 11585 BEInfo.clear(); 11586 Map.erase(I++); 11587 } else 11588 ++I; 11589 } 11590 }; 11591 11592 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11593 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11594 } 11595 11596 void 11597 ScalarEvolution::getUsedLoops(const SCEV *S, 11598 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11599 struct FindUsedLoops { 11600 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11601 : LoopsUsed(LoopsUsed) {} 11602 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11603 bool follow(const SCEV *S) { 11604 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11605 LoopsUsed.insert(AR->getLoop()); 11606 return true; 11607 } 11608 11609 bool isDone() const { return false; } 11610 }; 11611 11612 FindUsedLoops F(LoopsUsed); 11613 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11614 } 11615 11616 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11617 SmallPtrSet<const Loop *, 8> LoopsUsed; 11618 getUsedLoops(S, LoopsUsed); 11619 for (auto *L : LoopsUsed) 11620 LoopUsers[L].push_back(S); 11621 } 11622 11623 void ScalarEvolution::verify() const { 11624 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11625 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11626 11627 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11628 11629 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11630 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11631 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11632 11633 const SCEV *visitConstant(const SCEVConstant *Constant) { 11634 return SE.getConstant(Constant->getAPInt()); 11635 } 11636 11637 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11638 return SE.getUnknown(Expr->getValue()); 11639 } 11640 11641 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11642 return SE.getCouldNotCompute(); 11643 } 11644 }; 11645 11646 SCEVMapper SCM(SE2); 11647 11648 while (!LoopStack.empty()) { 11649 auto *L = LoopStack.pop_back_val(); 11650 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11651 11652 auto *CurBECount = SCM.visit( 11653 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11654 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11655 11656 if (CurBECount == SE2.getCouldNotCompute() || 11657 NewBECount == SE2.getCouldNotCompute()) { 11658 // NB! This situation is legal, but is very suspicious -- whatever pass 11659 // change the loop to make a trip count go from could not compute to 11660 // computable or vice-versa *should have* invalidated SCEV. However, we 11661 // choose not to assert here (for now) since we don't want false 11662 // positives. 11663 continue; 11664 } 11665 11666 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11667 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11668 // not propagate undef aggressively). This means we can (and do) fail 11669 // verification in cases where a transform makes the trip count of a loop 11670 // go from "undef" to "undef+1" (say). The transform is fine, since in 11671 // both cases the loop iterates "undef" times, but SCEV thinks we 11672 // increased the trip count of the loop by 1 incorrectly. 11673 continue; 11674 } 11675 11676 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11677 SE.getTypeSizeInBits(NewBECount->getType())) 11678 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11679 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11680 SE.getTypeSizeInBits(NewBECount->getType())) 11681 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11682 11683 auto *ConstantDelta = 11684 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11685 11686 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11687 dbgs() << "Trip Count Changed!\n"; 11688 dbgs() << "Old: " << *CurBECount << "\n"; 11689 dbgs() << "New: " << *NewBECount << "\n"; 11690 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11691 std::abort(); 11692 } 11693 } 11694 } 11695 11696 bool ScalarEvolution::invalidate( 11697 Function &F, const PreservedAnalyses &PA, 11698 FunctionAnalysisManager::Invalidator &Inv) { 11699 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11700 // of its dependencies is invalidated. 11701 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11702 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11703 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11704 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11705 Inv.invalidate<LoopAnalysis>(F, PA); 11706 } 11707 11708 AnalysisKey ScalarEvolutionAnalysis::Key; 11709 11710 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11711 FunctionAnalysisManager &AM) { 11712 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11713 AM.getResult<AssumptionAnalysis>(F), 11714 AM.getResult<DominatorTreeAnalysis>(F), 11715 AM.getResult<LoopAnalysis>(F)); 11716 } 11717 11718 PreservedAnalyses 11719 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11720 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11721 return PreservedAnalyses::all(); 11722 } 11723 11724 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11725 "Scalar Evolution Analysis", false, true) 11726 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11727 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11728 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11729 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11730 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11731 "Scalar Evolution Analysis", false, true) 11732 11733 char ScalarEvolutionWrapperPass::ID = 0; 11734 11735 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11736 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11737 } 11738 11739 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11740 SE.reset(new ScalarEvolution( 11741 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11742 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11743 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11744 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11745 return false; 11746 } 11747 11748 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11749 11750 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11751 SE->print(OS); 11752 } 11753 11754 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11755 if (!VerifySCEV) 11756 return; 11757 11758 SE->verify(); 11759 } 11760 11761 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11762 AU.setPreservesAll(); 11763 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11764 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11765 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11766 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11767 } 11768 11769 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11770 const SCEV *RHS) { 11771 FoldingSetNodeID ID; 11772 assert(LHS->getType() == RHS->getType() && 11773 "Type mismatch between LHS and RHS"); 11774 // Unique this node based on the arguments 11775 ID.AddInteger(SCEVPredicate::P_Equal); 11776 ID.AddPointer(LHS); 11777 ID.AddPointer(RHS); 11778 void *IP = nullptr; 11779 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11780 return S; 11781 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11782 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11783 UniquePreds.InsertNode(Eq, IP); 11784 return Eq; 11785 } 11786 11787 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11788 const SCEVAddRecExpr *AR, 11789 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11790 FoldingSetNodeID ID; 11791 // Unique this node based on the arguments 11792 ID.AddInteger(SCEVPredicate::P_Wrap); 11793 ID.AddPointer(AR); 11794 ID.AddInteger(AddedFlags); 11795 void *IP = nullptr; 11796 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11797 return S; 11798 auto *OF = new (SCEVAllocator) 11799 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11800 UniquePreds.InsertNode(OF, IP); 11801 return OF; 11802 } 11803 11804 namespace { 11805 11806 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11807 public: 11808 11809 /// Rewrites \p S in the context of a loop L and the SCEV predication 11810 /// infrastructure. 11811 /// 11812 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11813 /// equivalences present in \p Pred. 11814 /// 11815 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11816 /// \p NewPreds such that the result will be an AddRecExpr. 11817 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11818 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11819 SCEVUnionPredicate *Pred) { 11820 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11821 return Rewriter.visit(S); 11822 } 11823 11824 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11825 if (Pred) { 11826 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11827 for (auto *Pred : ExprPreds) 11828 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11829 if (IPred->getLHS() == Expr) 11830 return IPred->getRHS(); 11831 } 11832 return convertToAddRecWithPreds(Expr); 11833 } 11834 11835 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11836 const SCEV *Operand = visit(Expr->getOperand()); 11837 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11838 if (AR && AR->getLoop() == L && AR->isAffine()) { 11839 // This couldn't be folded because the operand didn't have the nuw 11840 // flag. Add the nusw flag as an assumption that we could make. 11841 const SCEV *Step = AR->getStepRecurrence(SE); 11842 Type *Ty = Expr->getType(); 11843 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11844 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11845 SE.getSignExtendExpr(Step, Ty), L, 11846 AR->getNoWrapFlags()); 11847 } 11848 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11849 } 11850 11851 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11852 const SCEV *Operand = visit(Expr->getOperand()); 11853 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11854 if (AR && AR->getLoop() == L && AR->isAffine()) { 11855 // This couldn't be folded because the operand didn't have the nsw 11856 // flag. Add the nssw flag as an assumption that we could make. 11857 const SCEV *Step = AR->getStepRecurrence(SE); 11858 Type *Ty = Expr->getType(); 11859 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11860 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11861 SE.getSignExtendExpr(Step, Ty), L, 11862 AR->getNoWrapFlags()); 11863 } 11864 return SE.getSignExtendExpr(Operand, Expr->getType()); 11865 } 11866 11867 private: 11868 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11869 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11870 SCEVUnionPredicate *Pred) 11871 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11872 11873 bool addOverflowAssumption(const SCEVPredicate *P) { 11874 if (!NewPreds) { 11875 // Check if we've already made this assumption. 11876 return Pred && Pred->implies(P); 11877 } 11878 NewPreds->insert(P); 11879 return true; 11880 } 11881 11882 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11883 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11884 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11885 return addOverflowAssumption(A); 11886 } 11887 11888 // If \p Expr represents a PHINode, we try to see if it can be represented 11889 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11890 // to add this predicate as a runtime overflow check, we return the AddRec. 11891 // If \p Expr does not meet these conditions (is not a PHI node, or we 11892 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11893 // return \p Expr. 11894 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11895 if (!isa<PHINode>(Expr->getValue())) 11896 return Expr; 11897 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11898 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11899 if (!PredicatedRewrite) 11900 return Expr; 11901 for (auto *P : PredicatedRewrite->second){ 11902 // Wrap predicates from outer loops are not supported. 11903 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 11904 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 11905 if (L != AR->getLoop()) 11906 return Expr; 11907 } 11908 if (!addOverflowAssumption(P)) 11909 return Expr; 11910 } 11911 return PredicatedRewrite->first; 11912 } 11913 11914 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11915 SCEVUnionPredicate *Pred; 11916 const Loop *L; 11917 }; 11918 11919 } // end anonymous namespace 11920 11921 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11922 SCEVUnionPredicate &Preds) { 11923 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11924 } 11925 11926 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11927 const SCEV *S, const Loop *L, 11928 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11929 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11930 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11931 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11932 11933 if (!AddRec) 11934 return nullptr; 11935 11936 // Since the transformation was successful, we can now transfer the SCEV 11937 // predicates. 11938 for (auto *P : TransformPreds) 11939 Preds.insert(P); 11940 11941 return AddRec; 11942 } 11943 11944 /// SCEV predicates 11945 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11946 SCEVPredicateKind Kind) 11947 : FastID(ID), Kind(Kind) {} 11948 11949 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11950 const SCEV *LHS, const SCEV *RHS) 11951 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11952 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11953 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11954 } 11955 11956 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11957 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11958 11959 if (!Op) 11960 return false; 11961 11962 return Op->LHS == LHS && Op->RHS == RHS; 11963 } 11964 11965 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11966 11967 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11968 11969 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11970 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11971 } 11972 11973 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11974 const SCEVAddRecExpr *AR, 11975 IncrementWrapFlags Flags) 11976 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11977 11978 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11979 11980 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11981 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11982 11983 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11984 } 11985 11986 bool SCEVWrapPredicate::isAlwaysTrue() const { 11987 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11988 IncrementWrapFlags IFlags = Flags; 11989 11990 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11991 IFlags = clearFlags(IFlags, IncrementNSSW); 11992 11993 return IFlags == IncrementAnyWrap; 11994 } 11995 11996 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11997 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11998 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11999 OS << "<nusw>"; 12000 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12001 OS << "<nssw>"; 12002 OS << "\n"; 12003 } 12004 12005 SCEVWrapPredicate::IncrementWrapFlags 12006 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12007 ScalarEvolution &SE) { 12008 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12009 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12010 12011 // We can safely transfer the NSW flag as NSSW. 12012 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12013 ImpliedFlags = IncrementNSSW; 12014 12015 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12016 // If the increment is positive, the SCEV NUW flag will also imply the 12017 // WrapPredicate NUSW flag. 12018 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12019 if (Step->getValue()->getValue().isNonNegative()) 12020 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12021 } 12022 12023 return ImpliedFlags; 12024 } 12025 12026 /// Union predicates don't get cached so create a dummy set ID for it. 12027 SCEVUnionPredicate::SCEVUnionPredicate() 12028 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12029 12030 bool SCEVUnionPredicate::isAlwaysTrue() const { 12031 return all_of(Preds, 12032 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12033 } 12034 12035 ArrayRef<const SCEVPredicate *> 12036 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12037 auto I = SCEVToPreds.find(Expr); 12038 if (I == SCEVToPreds.end()) 12039 return ArrayRef<const SCEVPredicate *>(); 12040 return I->second; 12041 } 12042 12043 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12044 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12045 return all_of(Set->Preds, 12046 [this](const SCEVPredicate *I) { return this->implies(I); }); 12047 12048 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12049 if (ScevPredsIt == SCEVToPreds.end()) 12050 return false; 12051 auto &SCEVPreds = ScevPredsIt->second; 12052 12053 return any_of(SCEVPreds, 12054 [N](const SCEVPredicate *I) { return I->implies(N); }); 12055 } 12056 12057 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12058 12059 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12060 for (auto Pred : Preds) 12061 Pred->print(OS, Depth); 12062 } 12063 12064 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12065 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12066 for (auto Pred : Set->Preds) 12067 add(Pred); 12068 return; 12069 } 12070 12071 if (implies(N)) 12072 return; 12073 12074 const SCEV *Key = N->getExpr(); 12075 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12076 " associated expression!"); 12077 12078 SCEVToPreds[Key].push_back(N); 12079 Preds.push_back(N); 12080 } 12081 12082 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12083 Loop &L) 12084 : SE(SE), L(L) {} 12085 12086 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12087 const SCEV *Expr = SE.getSCEV(V); 12088 RewriteEntry &Entry = RewriteMap[Expr]; 12089 12090 // If we already have an entry and the version matches, return it. 12091 if (Entry.second && Generation == Entry.first) 12092 return Entry.second; 12093 12094 // We found an entry but it's stale. Rewrite the stale entry 12095 // according to the current predicate. 12096 if (Entry.second) 12097 Expr = Entry.second; 12098 12099 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12100 Entry = {Generation, NewSCEV}; 12101 12102 return NewSCEV; 12103 } 12104 12105 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12106 if (!BackedgeCount) { 12107 SCEVUnionPredicate BackedgePred; 12108 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12109 addPredicate(BackedgePred); 12110 } 12111 return BackedgeCount; 12112 } 12113 12114 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12115 if (Preds.implies(&Pred)) 12116 return; 12117 Preds.add(&Pred); 12118 updateGeneration(); 12119 } 12120 12121 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12122 return Preds; 12123 } 12124 12125 void PredicatedScalarEvolution::updateGeneration() { 12126 // If the generation number wrapped recompute everything. 12127 if (++Generation == 0) { 12128 for (auto &II : RewriteMap) { 12129 const SCEV *Rewritten = II.second.second; 12130 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12131 } 12132 } 12133 } 12134 12135 void PredicatedScalarEvolution::setNoOverflow( 12136 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12137 const SCEV *Expr = getSCEV(V); 12138 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12139 12140 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12141 12142 // Clear the statically implied flags. 12143 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12144 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12145 12146 auto II = FlagsMap.insert({V, Flags}); 12147 if (!II.second) 12148 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12149 } 12150 12151 bool PredicatedScalarEvolution::hasNoOverflow( 12152 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12153 const SCEV *Expr = getSCEV(V); 12154 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12155 12156 Flags = SCEVWrapPredicate::clearFlags( 12157 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12158 12159 auto II = FlagsMap.find(V); 12160 12161 if (II != FlagsMap.end()) 12162 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12163 12164 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12165 } 12166 12167 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12168 const SCEV *Expr = this->getSCEV(V); 12169 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12170 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12171 12172 if (!New) 12173 return nullptr; 12174 12175 for (auto *P : NewPreds) 12176 Preds.add(P); 12177 12178 updateGeneration(); 12179 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12180 return New; 12181 } 12182 12183 PredicatedScalarEvolution::PredicatedScalarEvolution( 12184 const PredicatedScalarEvolution &Init) 12185 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12186 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12187 for (const auto &I : Init.FlagsMap) 12188 FlagsMap.insert(I); 12189 } 12190 12191 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12192 // For each block. 12193 for (auto *BB : L.getBlocks()) 12194 for (auto &I : *BB) { 12195 if (!SE.isSCEVable(I.getType())) 12196 continue; 12197 12198 auto *Expr = SE.getSCEV(&I); 12199 auto II = RewriteMap.find(Expr); 12200 12201 if (II == RewriteMap.end()) 12202 continue; 12203 12204 // Don't print things that are not interesting. 12205 if (II->second.second == Expr) 12206 continue; 12207 12208 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12209 OS.indent(Depth + 2) << *Expr << "\n"; 12210 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12211 } 12212 } 12213 12214 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12215 // arbitrary expressions. 12216 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12217 // 4, A / B becomes X / 8). 12218 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12219 const SCEV *&RHS) { 12220 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12221 if (Add == nullptr || Add->getNumOperands() != 2) 12222 return false; 12223 12224 const SCEV *A = Add->getOperand(1); 12225 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12226 12227 if (Mul == nullptr) 12228 return false; 12229 12230 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12231 // (SomeExpr + (-(SomeExpr / B) * B)). 12232 if (Expr == getURemExpr(A, B)) { 12233 LHS = A; 12234 RHS = B; 12235 return true; 12236 } 12237 return false; 12238 }; 12239 12240 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12241 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12242 return MatchURemWithDivisor(Mul->getOperand(1)) || 12243 MatchURemWithDivisor(Mul->getOperand(2)); 12244 12245 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12246 if (Mul->getNumOperands() == 2) 12247 return MatchURemWithDivisor(Mul->getOperand(1)) || 12248 MatchURemWithDivisor(Mul->getOperand(0)) || 12249 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12250 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12251 return false; 12252 } 12253