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 1782 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1783 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1784 if (SM->hasNoUnsignedWrap()) { 1785 // If the multiply does not unsign overflow then we can, by definition, 1786 // commute the zero extension with the multiply operation. 1787 SmallVector<const SCEV *, 4> Ops; 1788 for (const auto *Op : SM->operands()) 1789 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1790 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1791 } 1792 1793 // zext(2^K * (trunc X to iN)) to iM -> 1794 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1795 // 1796 // Proof: 1797 // 1798 // zext(2^K * (trunc X to iN)) to iM 1799 // = zext((trunc X to iN) << K) to iM 1800 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1801 // (because shl removes the top K bits) 1802 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1803 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1804 // 1805 if (SM->getNumOperands() == 2) 1806 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1807 if (MulLHS->getAPInt().isPowerOf2()) 1808 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1809 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1810 MulLHS->getAPInt().logBase2(); 1811 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1812 return getMulExpr( 1813 getZeroExtendExpr(MulLHS, Ty), 1814 getZeroExtendExpr( 1815 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1816 SCEV::FlagNUW, Depth + 1); 1817 } 1818 } 1819 1820 // The cast wasn't folded; create an explicit cast node. 1821 // Recompute the insert position, as it may have been invalidated. 1822 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1823 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1824 Op, Ty); 1825 UniqueSCEVs.InsertNode(S, IP); 1826 addToLoopUseLists(S); 1827 return S; 1828 } 1829 1830 const SCEV * 1831 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1832 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1833 "This is not an extending conversion!"); 1834 assert(isSCEVable(Ty) && 1835 "This is not a conversion to a SCEVable type!"); 1836 Ty = getEffectiveSCEVType(Ty); 1837 1838 // Fold if the operand is constant. 1839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1840 return getConstant( 1841 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1842 1843 // sext(sext(x)) --> sext(x) 1844 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1845 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1846 1847 // sext(zext(x)) --> zext(x) 1848 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1849 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1850 1851 // Before doing any expensive analysis, check to see if we've already 1852 // computed a SCEV for this Op and Ty. 1853 FoldingSetNodeID ID; 1854 ID.AddInteger(scSignExtend); 1855 ID.AddPointer(Op); 1856 ID.AddPointer(Ty); 1857 void *IP = nullptr; 1858 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1859 // Limit recursion depth. 1860 if (Depth > MaxExtDepth) { 1861 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1862 Op, Ty); 1863 UniqueSCEVs.InsertNode(S, IP); 1864 addToLoopUseLists(S); 1865 return S; 1866 } 1867 1868 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1869 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1870 // It's possible the bits taken off by the truncate were all sign bits. If 1871 // so, we should be able to simplify this further. 1872 const SCEV *X = ST->getOperand(); 1873 ConstantRange CR = getSignedRange(X); 1874 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1875 unsigned NewBits = getTypeSizeInBits(Ty); 1876 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1877 CR.sextOrTrunc(NewBits))) 1878 return getTruncateOrSignExtend(X, Ty); 1879 } 1880 1881 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1882 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1883 if (SA->getNumOperands() == 2) { 1884 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1885 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1886 if (SMul && SC1) { 1887 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1888 const APInt &C1 = SC1->getAPInt(); 1889 const APInt &C2 = SC2->getAPInt(); 1890 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1891 C2.ugt(C1) && C2.isPowerOf2()) 1892 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1893 getSignExtendExpr(SMul, Ty, Depth + 1), 1894 SCEV::FlagAnyWrap, Depth + 1); 1895 } 1896 } 1897 } 1898 1899 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1900 if (SA->hasNoSignedWrap()) { 1901 // If the addition does not sign overflow then we can, by definition, 1902 // commute the sign extension with the addition operation. 1903 SmallVector<const SCEV *, 4> Ops; 1904 for (const auto *Op : SA->operands()) 1905 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1906 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1907 } 1908 } 1909 // If the input value is a chrec scev, and we can prove that the value 1910 // did not overflow the old, smaller, value, we can sign extend all of the 1911 // operands (often constants). This allows analysis of something like 1912 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1914 if (AR->isAffine()) { 1915 const SCEV *Start = AR->getStart(); 1916 const SCEV *Step = AR->getStepRecurrence(*this); 1917 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1918 const Loop *L = AR->getLoop(); 1919 1920 if (!AR->hasNoSignedWrap()) { 1921 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1922 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1923 } 1924 1925 // If we have special knowledge that this addrec won't overflow, 1926 // we don't need to do any further analysis. 1927 if (AR->hasNoSignedWrap()) 1928 return getAddRecExpr( 1929 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1930 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1931 1932 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1933 // Note that this serves two purposes: It filters out loops that are 1934 // simply not analyzable, and it covers the case where this code is 1935 // being called from within backedge-taken count analysis, such that 1936 // attempting to ask for the backedge-taken count would likely result 1937 // in infinite recursion. In the later case, the analysis code will 1938 // cope with a conservative value, and it will take care to purge 1939 // that value once it has finished. 1940 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1941 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1942 // Manually compute the final value for AR, checking for 1943 // overflow. 1944 1945 // Check whether the backedge-taken count can be losslessly casted to 1946 // the addrec's type. The count is always unsigned. 1947 const SCEV *CastedMaxBECount = 1948 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1949 const SCEV *RecastedMaxBECount = 1950 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1951 if (MaxBECount == RecastedMaxBECount) { 1952 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1953 // Check whether Start+Step*MaxBECount has no signed overflow. 1954 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1955 SCEV::FlagAnyWrap, Depth + 1); 1956 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1957 SCEV::FlagAnyWrap, 1958 Depth + 1), 1959 WideTy, Depth + 1); 1960 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1961 const SCEV *WideMaxBECount = 1962 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1963 const SCEV *OperandExtendedAdd = 1964 getAddExpr(WideStart, 1965 getMulExpr(WideMaxBECount, 1966 getSignExtendExpr(Step, WideTy, Depth + 1), 1967 SCEV::FlagAnyWrap, Depth + 1), 1968 SCEV::FlagAnyWrap, Depth + 1); 1969 if (SAdd == OperandExtendedAdd) { 1970 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1971 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1972 // Return the expression with the addrec on the outside. 1973 return getAddRecExpr( 1974 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1975 Depth + 1), 1976 getSignExtendExpr(Step, Ty, Depth + 1), L, 1977 AR->getNoWrapFlags()); 1978 } 1979 // Similar to above, only this time treat the step value as unsigned. 1980 // This covers loops that count up with an unsigned step. 1981 OperandExtendedAdd = 1982 getAddExpr(WideStart, 1983 getMulExpr(WideMaxBECount, 1984 getZeroExtendExpr(Step, WideTy, Depth + 1), 1985 SCEV::FlagAnyWrap, Depth + 1), 1986 SCEV::FlagAnyWrap, Depth + 1); 1987 if (SAdd == OperandExtendedAdd) { 1988 // If AR wraps around then 1989 // 1990 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1991 // => SAdd != OperandExtendedAdd 1992 // 1993 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1994 // (SAdd == OperandExtendedAdd => AR is NW) 1995 1996 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1997 1998 // Return the expression with the addrec on the outside. 1999 return getAddRecExpr( 2000 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2001 Depth + 1), 2002 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2003 AR->getNoWrapFlags()); 2004 } 2005 } 2006 } 2007 2008 // Normally, in the cases we can prove no-overflow via a 2009 // backedge guarding condition, we can also compute a backedge 2010 // taken count for the loop. The exceptions are assumptions and 2011 // guards present in the loop -- SCEV is not great at exploiting 2012 // these to compute max backedge taken counts, but can still use 2013 // these to prove lack of overflow. Use this fact to avoid 2014 // doing extra work that may not pay off. 2015 2016 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2017 !AC.assumptions().empty()) { 2018 // If the backedge is guarded by a comparison with the pre-inc 2019 // value the addrec is safe. Also, if the entry is guarded by 2020 // a comparison with the start value and the backedge is 2021 // guarded by a comparison with the post-inc value, the addrec 2022 // is safe. 2023 ICmpInst::Predicate Pred; 2024 const SCEV *OverflowLimit = 2025 getSignedOverflowLimitForStep(Step, &Pred, this); 2026 if (OverflowLimit && 2027 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2028 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2029 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2030 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2031 return getAddRecExpr( 2032 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2033 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2034 } 2035 } 2036 2037 // If Start and Step are constants, check if we can apply this 2038 // transformation: 2039 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2040 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2041 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2042 if (SC1 && SC2) { 2043 const APInt &C1 = SC1->getAPInt(); 2044 const APInt &C2 = SC2->getAPInt(); 2045 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2046 C2.isPowerOf2()) { 2047 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2048 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2049 AR->getNoWrapFlags()); 2050 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2051 SCEV::FlagAnyWrap, Depth + 1); 2052 } 2053 } 2054 2055 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2056 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2057 return getAddRecExpr( 2058 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2059 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2060 } 2061 } 2062 2063 // If the input value is provably positive and we could not simplify 2064 // away the sext build a zext instead. 2065 if (isKnownNonNegative(Op)) 2066 return getZeroExtendExpr(Op, Ty, Depth + 1); 2067 2068 // The cast wasn't folded; create an explicit cast node. 2069 // Recompute the insert position, as it may have been invalidated. 2070 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2071 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2072 Op, Ty); 2073 UniqueSCEVs.InsertNode(S, IP); 2074 addToLoopUseLists(S); 2075 return S; 2076 } 2077 2078 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2079 /// unspecified bits out to the given type. 2080 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2081 Type *Ty) { 2082 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2083 "This is not an extending conversion!"); 2084 assert(isSCEVable(Ty) && 2085 "This is not a conversion to a SCEVable type!"); 2086 Ty = getEffectiveSCEVType(Ty); 2087 2088 // Sign-extend negative constants. 2089 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2090 if (SC->getAPInt().isNegative()) 2091 return getSignExtendExpr(Op, Ty); 2092 2093 // Peel off a truncate cast. 2094 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2095 const SCEV *NewOp = T->getOperand(); 2096 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2097 return getAnyExtendExpr(NewOp, Ty); 2098 return getTruncateOrNoop(NewOp, Ty); 2099 } 2100 2101 // Next try a zext cast. If the cast is folded, use it. 2102 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2103 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2104 return ZExt; 2105 2106 // Next try a sext cast. If the cast is folded, use it. 2107 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2108 if (!isa<SCEVSignExtendExpr>(SExt)) 2109 return SExt; 2110 2111 // Force the cast to be folded into the operands of an addrec. 2112 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2113 SmallVector<const SCEV *, 4> Ops; 2114 for (const SCEV *Op : AR->operands()) 2115 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2116 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2117 } 2118 2119 // If the expression is obviously signed, use the sext cast value. 2120 if (isa<SCEVSMaxExpr>(Op)) 2121 return SExt; 2122 2123 // Absent any other information, use the zext cast value. 2124 return ZExt; 2125 } 2126 2127 /// Process the given Ops list, which is a list of operands to be added under 2128 /// the given scale, update the given map. This is a helper function for 2129 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2130 /// that would form an add expression like this: 2131 /// 2132 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2133 /// 2134 /// where A and B are constants, update the map with these values: 2135 /// 2136 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2137 /// 2138 /// and add 13 + A*B*29 to AccumulatedConstant. 2139 /// This will allow getAddRecExpr to produce this: 2140 /// 2141 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2142 /// 2143 /// This form often exposes folding opportunities that are hidden in 2144 /// the original operand list. 2145 /// 2146 /// Return true iff it appears that any interesting folding opportunities 2147 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2148 /// the common case where no interesting opportunities are present, and 2149 /// is also used as a check to avoid infinite recursion. 2150 static bool 2151 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2152 SmallVectorImpl<const SCEV *> &NewOps, 2153 APInt &AccumulatedConstant, 2154 const SCEV *const *Ops, size_t NumOperands, 2155 const APInt &Scale, 2156 ScalarEvolution &SE) { 2157 bool Interesting = false; 2158 2159 // Iterate over the add operands. They are sorted, with constants first. 2160 unsigned i = 0; 2161 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2162 ++i; 2163 // Pull a buried constant out to the outside. 2164 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2165 Interesting = true; 2166 AccumulatedConstant += Scale * C->getAPInt(); 2167 } 2168 2169 // Next comes everything else. We're especially interested in multiplies 2170 // here, but they're in the middle, so just visit the rest with one loop. 2171 for (; i != NumOperands; ++i) { 2172 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2173 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2174 APInt NewScale = 2175 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2176 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2177 // A multiplication of a constant with another add; recurse. 2178 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2179 Interesting |= 2180 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2181 Add->op_begin(), Add->getNumOperands(), 2182 NewScale, SE); 2183 } else { 2184 // A multiplication of a constant with some other value. Update 2185 // the map. 2186 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2187 const SCEV *Key = SE.getMulExpr(MulOps); 2188 auto Pair = M.insert({Key, NewScale}); 2189 if (Pair.second) { 2190 NewOps.push_back(Pair.first->first); 2191 } else { 2192 Pair.first->second += NewScale; 2193 // The map already had an entry for this value, which may indicate 2194 // a folding opportunity. 2195 Interesting = true; 2196 } 2197 } 2198 } else { 2199 // An ordinary operand. Update the map. 2200 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2201 M.insert({Ops[i], Scale}); 2202 if (Pair.second) { 2203 NewOps.push_back(Pair.first->first); 2204 } else { 2205 Pair.first->second += Scale; 2206 // The map already had an entry for this value, which may indicate 2207 // a folding opportunity. 2208 Interesting = true; 2209 } 2210 } 2211 } 2212 2213 return Interesting; 2214 } 2215 2216 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2217 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2218 // can't-overflow flags for the operation if possible. 2219 static SCEV::NoWrapFlags 2220 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2221 const SmallVectorImpl<const SCEV *> &Ops, 2222 SCEV::NoWrapFlags Flags) { 2223 using namespace std::placeholders; 2224 2225 using OBO = OverflowingBinaryOperator; 2226 2227 bool CanAnalyze = 2228 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2229 (void)CanAnalyze; 2230 assert(CanAnalyze && "don't call from other places!"); 2231 2232 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2233 SCEV::NoWrapFlags SignOrUnsignWrap = 2234 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2235 2236 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2237 auto IsKnownNonNegative = [&](const SCEV *S) { 2238 return SE->isKnownNonNegative(S); 2239 }; 2240 2241 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2242 Flags = 2243 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2244 2245 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2246 2247 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2248 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2249 2250 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2251 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2252 2253 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2254 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2255 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2256 Instruction::Add, C, OBO::NoSignedWrap); 2257 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2258 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2259 } 2260 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2261 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2262 Instruction::Add, C, OBO::NoUnsignedWrap); 2263 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2264 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2265 } 2266 } 2267 2268 return Flags; 2269 } 2270 2271 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2272 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2273 } 2274 2275 /// Get a canonical add expression, or something simpler if possible. 2276 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2277 SCEV::NoWrapFlags Flags, 2278 unsigned Depth) { 2279 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2280 "only nuw or nsw allowed"); 2281 assert(!Ops.empty() && "Cannot get empty add!"); 2282 if (Ops.size() == 1) return Ops[0]; 2283 #ifndef NDEBUG 2284 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2285 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2286 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2287 "SCEVAddExpr operand types don't match!"); 2288 #endif 2289 2290 // Sort by complexity, this groups all similar expression types together. 2291 GroupByComplexity(Ops, &LI, DT); 2292 2293 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2294 2295 // If there are any constants, fold them together. 2296 unsigned Idx = 0; 2297 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2298 ++Idx; 2299 assert(Idx < Ops.size()); 2300 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2301 // We found two constants, fold them together! 2302 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2303 if (Ops.size() == 2) return Ops[0]; 2304 Ops.erase(Ops.begin()+1); // Erase the folded element 2305 LHSC = cast<SCEVConstant>(Ops[0]); 2306 } 2307 2308 // If we are left with a constant zero being added, strip it off. 2309 if (LHSC->getValue()->isZero()) { 2310 Ops.erase(Ops.begin()); 2311 --Idx; 2312 } 2313 2314 if (Ops.size() == 1) return Ops[0]; 2315 } 2316 2317 // Limit recursion calls depth. 2318 if (Depth > MaxArithDepth) 2319 return getOrCreateAddExpr(Ops, Flags); 2320 2321 // Okay, check to see if the same value occurs in the operand list more than 2322 // once. If so, merge them together into an multiply expression. Since we 2323 // sorted the list, these values are required to be adjacent. 2324 Type *Ty = Ops[0]->getType(); 2325 bool FoundMatch = false; 2326 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2327 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2328 // Scan ahead to count how many equal operands there are. 2329 unsigned Count = 2; 2330 while (i+Count != e && Ops[i+Count] == Ops[i]) 2331 ++Count; 2332 // Merge the values into a multiply. 2333 const SCEV *Scale = getConstant(Ty, Count); 2334 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2335 if (Ops.size() == Count) 2336 return Mul; 2337 Ops[i] = Mul; 2338 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2339 --i; e -= Count - 1; 2340 FoundMatch = true; 2341 } 2342 if (FoundMatch) 2343 return getAddExpr(Ops, Flags, Depth + 1); 2344 2345 // Check for truncates. If all the operands are truncated from the same 2346 // type, see if factoring out the truncate would permit the result to be 2347 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2348 // if the contents of the resulting outer trunc fold to something simple. 2349 auto FindTruncSrcType = [&]() -> Type * { 2350 // We're ultimately looking to fold an addrec of truncs and muls of only 2351 // constants and truncs, so if we find any other types of SCEV 2352 // as operands of the addrec then we bail and return nullptr here. 2353 // Otherwise, we return the type of the operand of a trunc that we find. 2354 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2355 return T->getOperand()->getType(); 2356 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2357 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2358 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2359 return T->getOperand()->getType(); 2360 } 2361 return nullptr; 2362 }; 2363 if (auto *SrcType = FindTruncSrcType()) { 2364 SmallVector<const SCEV *, 8> LargeOps; 2365 bool Ok = true; 2366 // Check all the operands to see if they can be represented in the 2367 // source type of the truncate. 2368 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2369 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2370 if (T->getOperand()->getType() != SrcType) { 2371 Ok = false; 2372 break; 2373 } 2374 LargeOps.push_back(T->getOperand()); 2375 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2376 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2377 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2378 SmallVector<const SCEV *, 8> LargeMulOps; 2379 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2380 if (const SCEVTruncateExpr *T = 2381 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2382 if (T->getOperand()->getType() != SrcType) { 2383 Ok = false; 2384 break; 2385 } 2386 LargeMulOps.push_back(T->getOperand()); 2387 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2388 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2389 } else { 2390 Ok = false; 2391 break; 2392 } 2393 } 2394 if (Ok) 2395 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2396 } else { 2397 Ok = false; 2398 break; 2399 } 2400 } 2401 if (Ok) { 2402 // Evaluate the expression in the larger type. 2403 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2404 // If it folds to something simple, use it. Otherwise, don't. 2405 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2406 return getTruncateExpr(Fold, Ty); 2407 } 2408 } 2409 2410 // Skip past any other cast SCEVs. 2411 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2412 ++Idx; 2413 2414 // If there are add operands they would be next. 2415 if (Idx < Ops.size()) { 2416 bool DeletedAdd = false; 2417 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2418 if (Ops.size() > AddOpsInlineThreshold || 2419 Add->getNumOperands() > AddOpsInlineThreshold) 2420 break; 2421 // If we have an add, expand the add operands onto the end of the operands 2422 // list. 2423 Ops.erase(Ops.begin()+Idx); 2424 Ops.append(Add->op_begin(), Add->op_end()); 2425 DeletedAdd = true; 2426 } 2427 2428 // If we deleted at least one add, we added operands to the end of the list, 2429 // and they are not necessarily sorted. Recurse to resort and resimplify 2430 // any operands we just acquired. 2431 if (DeletedAdd) 2432 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2433 } 2434 2435 // Skip over the add expression until we get to a multiply. 2436 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2437 ++Idx; 2438 2439 // Check to see if there are any folding opportunities present with 2440 // operands multiplied by constant values. 2441 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2442 uint64_t BitWidth = getTypeSizeInBits(Ty); 2443 DenseMap<const SCEV *, APInt> M; 2444 SmallVector<const SCEV *, 8> NewOps; 2445 APInt AccumulatedConstant(BitWidth, 0); 2446 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2447 Ops.data(), Ops.size(), 2448 APInt(BitWidth, 1), *this)) { 2449 struct APIntCompare { 2450 bool operator()(const APInt &LHS, const APInt &RHS) const { 2451 return LHS.ult(RHS); 2452 } 2453 }; 2454 2455 // Some interesting folding opportunity is present, so its worthwhile to 2456 // re-generate the operands list. Group the operands by constant scale, 2457 // to avoid multiplying by the same constant scale multiple times. 2458 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2459 for (const SCEV *NewOp : NewOps) 2460 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2461 // Re-generate the operands list. 2462 Ops.clear(); 2463 if (AccumulatedConstant != 0) 2464 Ops.push_back(getConstant(AccumulatedConstant)); 2465 for (auto &MulOp : MulOpLists) 2466 if (MulOp.first != 0) 2467 Ops.push_back(getMulExpr( 2468 getConstant(MulOp.first), 2469 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2470 SCEV::FlagAnyWrap, Depth + 1)); 2471 if (Ops.empty()) 2472 return getZero(Ty); 2473 if (Ops.size() == 1) 2474 return Ops[0]; 2475 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2476 } 2477 } 2478 2479 // If we are adding something to a multiply expression, make sure the 2480 // something is not already an operand of the multiply. If so, merge it into 2481 // the multiply. 2482 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2483 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2484 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2485 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2486 if (isa<SCEVConstant>(MulOpSCEV)) 2487 continue; 2488 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2489 if (MulOpSCEV == Ops[AddOp]) { 2490 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2491 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2492 if (Mul->getNumOperands() != 2) { 2493 // If the multiply has more than two operands, we must get the 2494 // Y*Z term. 2495 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2496 Mul->op_begin()+MulOp); 2497 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2498 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2499 } 2500 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2501 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2502 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2503 SCEV::FlagAnyWrap, Depth + 1); 2504 if (Ops.size() == 2) return OuterMul; 2505 if (AddOp < Idx) { 2506 Ops.erase(Ops.begin()+AddOp); 2507 Ops.erase(Ops.begin()+Idx-1); 2508 } else { 2509 Ops.erase(Ops.begin()+Idx); 2510 Ops.erase(Ops.begin()+AddOp-1); 2511 } 2512 Ops.push_back(OuterMul); 2513 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2514 } 2515 2516 // Check this multiply against other multiplies being added together. 2517 for (unsigned OtherMulIdx = Idx+1; 2518 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2519 ++OtherMulIdx) { 2520 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2521 // If MulOp occurs in OtherMul, we can fold the two multiplies 2522 // together. 2523 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2524 OMulOp != e; ++OMulOp) 2525 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2526 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2527 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2528 if (Mul->getNumOperands() != 2) { 2529 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2530 Mul->op_begin()+MulOp); 2531 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2532 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2533 } 2534 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2535 if (OtherMul->getNumOperands() != 2) { 2536 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2537 OtherMul->op_begin()+OMulOp); 2538 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2539 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2540 } 2541 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2542 const SCEV *InnerMulSum = 2543 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2544 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2545 SCEV::FlagAnyWrap, Depth + 1); 2546 if (Ops.size() == 2) return OuterMul; 2547 Ops.erase(Ops.begin()+Idx); 2548 Ops.erase(Ops.begin()+OtherMulIdx-1); 2549 Ops.push_back(OuterMul); 2550 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2551 } 2552 } 2553 } 2554 } 2555 2556 // If there are any add recurrences in the operands list, see if any other 2557 // added values are loop invariant. If so, we can fold them into the 2558 // recurrence. 2559 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2560 ++Idx; 2561 2562 // Scan over all recurrences, trying to fold loop invariants into them. 2563 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2564 // Scan all of the other operands to this add and add them to the vector if 2565 // they are loop invariant w.r.t. the recurrence. 2566 SmallVector<const SCEV *, 8> LIOps; 2567 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2568 const Loop *AddRecLoop = AddRec->getLoop(); 2569 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2570 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2571 LIOps.push_back(Ops[i]); 2572 Ops.erase(Ops.begin()+i); 2573 --i; --e; 2574 } 2575 2576 // If we found some loop invariants, fold them into the recurrence. 2577 if (!LIOps.empty()) { 2578 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2579 LIOps.push_back(AddRec->getStart()); 2580 2581 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2582 AddRec->op_end()); 2583 // This follows from the fact that the no-wrap flags on the outer add 2584 // expression are applicable on the 0th iteration, when the add recurrence 2585 // will be equal to its start value. 2586 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2587 2588 // Build the new addrec. Propagate the NUW and NSW flags if both the 2589 // outer add and the inner addrec are guaranteed to have no overflow. 2590 // Always propagate NW. 2591 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2592 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2593 2594 // If all of the other operands were loop invariant, we are done. 2595 if (Ops.size() == 1) return NewRec; 2596 2597 // Otherwise, add the folded AddRec by the non-invariant parts. 2598 for (unsigned i = 0;; ++i) 2599 if (Ops[i] == AddRec) { 2600 Ops[i] = NewRec; 2601 break; 2602 } 2603 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2604 } 2605 2606 // Okay, if there weren't any loop invariants to be folded, check to see if 2607 // there are multiple AddRec's with the same loop induction variable being 2608 // added together. If so, we can fold them. 2609 for (unsigned OtherIdx = Idx+1; 2610 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2611 ++OtherIdx) { 2612 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2613 // so that the 1st found AddRecExpr is dominated by all others. 2614 assert(DT.dominates( 2615 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2616 AddRec->getLoop()->getHeader()) && 2617 "AddRecExprs are not sorted in reverse dominance order?"); 2618 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2619 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2620 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2621 AddRec->op_end()); 2622 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2623 ++OtherIdx) { 2624 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2625 if (OtherAddRec->getLoop() == AddRecLoop) { 2626 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2627 i != e; ++i) { 2628 if (i >= AddRecOps.size()) { 2629 AddRecOps.append(OtherAddRec->op_begin()+i, 2630 OtherAddRec->op_end()); 2631 break; 2632 } 2633 SmallVector<const SCEV *, 2> TwoOps = { 2634 AddRecOps[i], OtherAddRec->getOperand(i)}; 2635 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2636 } 2637 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2638 } 2639 } 2640 // Step size has changed, so we cannot guarantee no self-wraparound. 2641 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2642 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2643 } 2644 } 2645 2646 // Otherwise couldn't fold anything into this recurrence. Move onto the 2647 // next one. 2648 } 2649 2650 // Okay, it looks like we really DO need an add expr. Check to see if we 2651 // already have one, otherwise create a new one. 2652 return getOrCreateAddExpr(Ops, Flags); 2653 } 2654 2655 const SCEV * 2656 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2657 SCEV::NoWrapFlags Flags) { 2658 FoldingSetNodeID ID; 2659 ID.AddInteger(scAddExpr); 2660 for (const SCEV *Op : Ops) 2661 ID.AddPointer(Op); 2662 void *IP = nullptr; 2663 SCEVAddExpr *S = 2664 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2665 if (!S) { 2666 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2667 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2668 S = new (SCEVAllocator) 2669 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2670 UniqueSCEVs.InsertNode(S, IP); 2671 addToLoopUseLists(S); 2672 } 2673 S->setNoWrapFlags(Flags); 2674 return S; 2675 } 2676 2677 const SCEV * 2678 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2679 SCEV::NoWrapFlags Flags) { 2680 FoldingSetNodeID ID; 2681 ID.AddInteger(scMulExpr); 2682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2683 ID.AddPointer(Ops[i]); 2684 void *IP = nullptr; 2685 SCEVMulExpr *S = 2686 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2687 if (!S) { 2688 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2689 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2690 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2691 O, Ops.size()); 2692 UniqueSCEVs.InsertNode(S, IP); 2693 addToLoopUseLists(S); 2694 } 2695 S->setNoWrapFlags(Flags); 2696 return S; 2697 } 2698 2699 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2700 uint64_t k = i*j; 2701 if (j > 1 && k / j != i) Overflow = true; 2702 return k; 2703 } 2704 2705 /// Compute the result of "n choose k", the binomial coefficient. If an 2706 /// intermediate computation overflows, Overflow will be set and the return will 2707 /// be garbage. Overflow is not cleared on absence of overflow. 2708 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2709 // We use the multiplicative formula: 2710 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2711 // At each iteration, we take the n-th term of the numeral and divide by the 2712 // (k-n)th term of the denominator. This division will always produce an 2713 // integral result, and helps reduce the chance of overflow in the 2714 // intermediate computations. However, we can still overflow even when the 2715 // final result would fit. 2716 2717 if (n == 0 || n == k) return 1; 2718 if (k > n) return 0; 2719 2720 if (k > n/2) 2721 k = n-k; 2722 2723 uint64_t r = 1; 2724 for (uint64_t i = 1; i <= k; ++i) { 2725 r = umul_ov(r, n-(i-1), Overflow); 2726 r /= i; 2727 } 2728 return r; 2729 } 2730 2731 /// Determine if any of the operands in this SCEV are a constant or if 2732 /// any of the add or multiply expressions in this SCEV contain a constant. 2733 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2734 struct FindConstantInAddMulChain { 2735 bool FoundConstant = false; 2736 2737 bool follow(const SCEV *S) { 2738 FoundConstant |= isa<SCEVConstant>(S); 2739 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2740 } 2741 2742 bool isDone() const { 2743 return FoundConstant; 2744 } 2745 }; 2746 2747 FindConstantInAddMulChain F; 2748 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2749 ST.visitAll(StartExpr); 2750 return F.FoundConstant; 2751 } 2752 2753 /// Get a canonical multiply expression, or something simpler if possible. 2754 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2755 SCEV::NoWrapFlags Flags, 2756 unsigned Depth) { 2757 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2758 "only nuw or nsw allowed"); 2759 assert(!Ops.empty() && "Cannot get empty mul!"); 2760 if (Ops.size() == 1) return Ops[0]; 2761 #ifndef NDEBUG 2762 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2763 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2764 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2765 "SCEVMulExpr operand types don't match!"); 2766 #endif 2767 2768 // Sort by complexity, this groups all similar expression types together. 2769 GroupByComplexity(Ops, &LI, DT); 2770 2771 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2772 2773 // Limit recursion calls depth. 2774 if (Depth > MaxArithDepth) 2775 return getOrCreateMulExpr(Ops, Flags); 2776 2777 // If there are any constants, fold them together. 2778 unsigned Idx = 0; 2779 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2780 2781 if (Ops.size() == 2) 2782 // C1*(C2+V) -> C1*C2 + C1*V 2783 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2784 // If any of Add's ops are Adds or Muls with a constant, apply this 2785 // transformation as well. 2786 // 2787 // TODO: There are some cases where this transformation is not 2788 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2789 // this transformation should be narrowed down. 2790 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2791 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2792 SCEV::FlagAnyWrap, Depth + 1), 2793 getMulExpr(LHSC, Add->getOperand(1), 2794 SCEV::FlagAnyWrap, Depth + 1), 2795 SCEV::FlagAnyWrap, Depth + 1); 2796 2797 ++Idx; 2798 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2799 // We found two constants, fold them together! 2800 ConstantInt *Fold = 2801 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2802 Ops[0] = getConstant(Fold); 2803 Ops.erase(Ops.begin()+1); // Erase the folded element 2804 if (Ops.size() == 1) return Ops[0]; 2805 LHSC = cast<SCEVConstant>(Ops[0]); 2806 } 2807 2808 // If we are left with a constant one being multiplied, strip it off. 2809 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2810 Ops.erase(Ops.begin()); 2811 --Idx; 2812 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2813 // If we have a multiply of zero, it will always be zero. 2814 return Ops[0]; 2815 } else if (Ops[0]->isAllOnesValue()) { 2816 // If we have a mul by -1 of an add, try distributing the -1 among the 2817 // add operands. 2818 if (Ops.size() == 2) { 2819 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2820 SmallVector<const SCEV *, 4> NewOps; 2821 bool AnyFolded = false; 2822 for (const SCEV *AddOp : Add->operands()) { 2823 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2824 Depth + 1); 2825 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2826 NewOps.push_back(Mul); 2827 } 2828 if (AnyFolded) 2829 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2830 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2831 // Negation preserves a recurrence's no self-wrap property. 2832 SmallVector<const SCEV *, 4> Operands; 2833 for (const SCEV *AddRecOp : AddRec->operands()) 2834 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2835 Depth + 1)); 2836 2837 return getAddRecExpr(Operands, AddRec->getLoop(), 2838 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2839 } 2840 } 2841 } 2842 2843 if (Ops.size() == 1) 2844 return Ops[0]; 2845 } 2846 2847 // Skip over the add expression until we get to a multiply. 2848 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2849 ++Idx; 2850 2851 // If there are mul operands inline them all into this expression. 2852 if (Idx < Ops.size()) { 2853 bool DeletedMul = false; 2854 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2855 if (Ops.size() > MulOpsInlineThreshold) 2856 break; 2857 // If we have an mul, expand the mul operands onto the end of the 2858 // operands list. 2859 Ops.erase(Ops.begin()+Idx); 2860 Ops.append(Mul->op_begin(), Mul->op_end()); 2861 DeletedMul = true; 2862 } 2863 2864 // If we deleted at least one mul, we added operands to the end of the 2865 // list, and they are not necessarily sorted. Recurse to resort and 2866 // resimplify any operands we just acquired. 2867 if (DeletedMul) 2868 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2869 } 2870 2871 // If there are any add recurrences in the operands list, see if any other 2872 // added values are loop invariant. If so, we can fold them into the 2873 // recurrence. 2874 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2875 ++Idx; 2876 2877 // Scan over all recurrences, trying to fold loop invariants into them. 2878 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2879 // Scan all of the other operands to this mul and add them to the vector 2880 // if they are loop invariant w.r.t. the recurrence. 2881 SmallVector<const SCEV *, 8> LIOps; 2882 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2883 const Loop *AddRecLoop = AddRec->getLoop(); 2884 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2885 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2886 LIOps.push_back(Ops[i]); 2887 Ops.erase(Ops.begin()+i); 2888 --i; --e; 2889 } 2890 2891 // If we found some loop invariants, fold them into the recurrence. 2892 if (!LIOps.empty()) { 2893 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2894 SmallVector<const SCEV *, 4> NewOps; 2895 NewOps.reserve(AddRec->getNumOperands()); 2896 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2897 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2898 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2899 SCEV::FlagAnyWrap, Depth + 1)); 2900 2901 // Build the new addrec. Propagate the NUW and NSW flags if both the 2902 // outer mul and the inner addrec are guaranteed to have no overflow. 2903 // 2904 // No self-wrap cannot be guaranteed after changing the step size, but 2905 // will be inferred if either NUW or NSW is true. 2906 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2907 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2908 2909 // If all of the other operands were loop invariant, we are done. 2910 if (Ops.size() == 1) return NewRec; 2911 2912 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2913 for (unsigned i = 0;; ++i) 2914 if (Ops[i] == AddRec) { 2915 Ops[i] = NewRec; 2916 break; 2917 } 2918 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2919 } 2920 2921 // Okay, if there weren't any loop invariants to be folded, check to see 2922 // if there are multiple AddRec's with the same loop induction variable 2923 // being multiplied together. If so, we can fold them. 2924 2925 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2926 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2927 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2928 // ]]],+,...up to x=2n}. 2929 // Note that the arguments to choose() are always integers with values 2930 // known at compile time, never SCEV objects. 2931 // 2932 // The implementation avoids pointless extra computations when the two 2933 // addrec's are of different length (mathematically, it's equivalent to 2934 // an infinite stream of zeros on the right). 2935 bool OpsModified = false; 2936 for (unsigned OtherIdx = Idx+1; 2937 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2938 ++OtherIdx) { 2939 const SCEVAddRecExpr *OtherAddRec = 2940 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2941 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2942 continue; 2943 2944 // Limit max number of arguments to avoid creation of unreasonably big 2945 // SCEVAddRecs with very complex operands. 2946 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2947 MaxAddRecSize) 2948 continue; 2949 2950 bool Overflow = false; 2951 Type *Ty = AddRec->getType(); 2952 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2953 SmallVector<const SCEV*, 7> AddRecOps; 2954 for (int x = 0, xe = AddRec->getNumOperands() + 2955 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2956 const SCEV *Term = getZero(Ty); 2957 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2958 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2959 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2960 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2961 z < ze && !Overflow; ++z) { 2962 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2963 uint64_t Coeff; 2964 if (LargerThan64Bits) 2965 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2966 else 2967 Coeff = Coeff1*Coeff2; 2968 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2969 const SCEV *Term1 = AddRec->getOperand(y-z); 2970 const SCEV *Term2 = OtherAddRec->getOperand(z); 2971 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2972 SCEV::FlagAnyWrap, Depth + 1), 2973 SCEV::FlagAnyWrap, Depth + 1); 2974 } 2975 } 2976 AddRecOps.push_back(Term); 2977 } 2978 if (!Overflow) { 2979 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2980 SCEV::FlagAnyWrap); 2981 if (Ops.size() == 2) return NewAddRec; 2982 Ops[Idx] = NewAddRec; 2983 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2984 OpsModified = true; 2985 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2986 if (!AddRec) 2987 break; 2988 } 2989 } 2990 if (OpsModified) 2991 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2992 2993 // Otherwise couldn't fold anything into this recurrence. Move onto the 2994 // next one. 2995 } 2996 2997 // Okay, it looks like we really DO need an mul expr. Check to see if we 2998 // already have one, otherwise create a new one. 2999 return getOrCreateMulExpr(Ops, Flags); 3000 } 3001 3002 /// Represents an unsigned remainder expression based on unsigned division. 3003 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3004 const SCEV *RHS) { 3005 assert(getEffectiveSCEVType(LHS->getType()) == 3006 getEffectiveSCEVType(RHS->getType()) && 3007 "SCEVURemExpr operand types don't match!"); 3008 3009 // Short-circuit easy cases 3010 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3011 // If constant is one, the result is trivial 3012 if (RHSC->getValue()->isOne()) 3013 return getZero(LHS->getType()); // X urem 1 --> 0 3014 3015 // If constant is a power of two, fold into a zext(trunc(LHS)). 3016 if (RHSC->getAPInt().isPowerOf2()) { 3017 Type *FullTy = LHS->getType(); 3018 Type *TruncTy = 3019 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3020 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3021 } 3022 } 3023 3024 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3025 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3026 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3027 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3028 } 3029 3030 /// Get a canonical unsigned division expression, or something simpler if 3031 /// possible. 3032 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3033 const SCEV *RHS) { 3034 assert(getEffectiveSCEVType(LHS->getType()) == 3035 getEffectiveSCEVType(RHS->getType()) && 3036 "SCEVUDivExpr operand types don't match!"); 3037 3038 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3039 if (RHSC->getValue()->isOne()) 3040 return LHS; // X udiv 1 --> x 3041 // If the denominator is zero, the result of the udiv is undefined. Don't 3042 // try to analyze it, because the resolution chosen here may differ from 3043 // the resolution chosen in other parts of the compiler. 3044 if (!RHSC->getValue()->isZero()) { 3045 // Determine if the division can be folded into the operands of 3046 // its operands. 3047 // TODO: Generalize this to non-constants by using known-bits information. 3048 Type *Ty = LHS->getType(); 3049 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3050 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3051 // For non-power-of-two values, effectively round the value up to the 3052 // nearest power of two. 3053 if (!RHSC->getAPInt().isPowerOf2()) 3054 ++MaxShiftAmt; 3055 IntegerType *ExtTy = 3056 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3057 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3058 if (const SCEVConstant *Step = 3059 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3060 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3061 const APInt &StepInt = Step->getAPInt(); 3062 const APInt &DivInt = RHSC->getAPInt(); 3063 if (!StepInt.urem(DivInt) && 3064 getZeroExtendExpr(AR, ExtTy) == 3065 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3066 getZeroExtendExpr(Step, ExtTy), 3067 AR->getLoop(), SCEV::FlagAnyWrap)) { 3068 SmallVector<const SCEV *, 4> Operands; 3069 for (const SCEV *Op : AR->operands()) 3070 Operands.push_back(getUDivExpr(Op, RHS)); 3071 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3072 } 3073 /// Get a canonical UDivExpr for a recurrence. 3074 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3075 // We can currently only fold X%N if X is constant. 3076 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3077 if (StartC && !DivInt.urem(StepInt) && 3078 getZeroExtendExpr(AR, ExtTy) == 3079 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3080 getZeroExtendExpr(Step, ExtTy), 3081 AR->getLoop(), SCEV::FlagAnyWrap)) { 3082 const APInt &StartInt = StartC->getAPInt(); 3083 const APInt &StartRem = StartInt.urem(StepInt); 3084 if (StartRem != 0) 3085 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3086 AR->getLoop(), SCEV::FlagNW); 3087 } 3088 } 3089 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3090 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3091 SmallVector<const SCEV *, 4> Operands; 3092 for (const SCEV *Op : M->operands()) 3093 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3094 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3095 // Find an operand that's safely divisible. 3096 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3097 const SCEV *Op = M->getOperand(i); 3098 const SCEV *Div = getUDivExpr(Op, RHSC); 3099 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3100 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3101 M->op_end()); 3102 Operands[i] = Div; 3103 return getMulExpr(Operands); 3104 } 3105 } 3106 } 3107 3108 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3109 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3110 if (auto *DivisorConstant = 3111 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3112 bool Overflow = false; 3113 APInt NewRHS = 3114 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3115 if (Overflow) { 3116 return getConstant(RHSC->getType(), 0, false); 3117 } 3118 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3119 } 3120 } 3121 3122 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3123 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3124 SmallVector<const SCEV *, 4> Operands; 3125 for (const SCEV *Op : A->operands()) 3126 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3127 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3128 Operands.clear(); 3129 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3130 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3131 if (isa<SCEVUDivExpr>(Op) || 3132 getMulExpr(Op, RHS) != A->getOperand(i)) 3133 break; 3134 Operands.push_back(Op); 3135 } 3136 if (Operands.size() == A->getNumOperands()) 3137 return getAddExpr(Operands); 3138 } 3139 } 3140 3141 // Fold if both operands are constant. 3142 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3143 Constant *LHSCV = LHSC->getValue(); 3144 Constant *RHSCV = RHSC->getValue(); 3145 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3146 RHSCV))); 3147 } 3148 } 3149 } 3150 3151 FoldingSetNodeID ID; 3152 ID.AddInteger(scUDivExpr); 3153 ID.AddPointer(LHS); 3154 ID.AddPointer(RHS); 3155 void *IP = nullptr; 3156 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3157 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3158 LHS, RHS); 3159 UniqueSCEVs.InsertNode(S, IP); 3160 addToLoopUseLists(S); 3161 return S; 3162 } 3163 3164 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3165 APInt A = C1->getAPInt().abs(); 3166 APInt B = C2->getAPInt().abs(); 3167 uint32_t ABW = A.getBitWidth(); 3168 uint32_t BBW = B.getBitWidth(); 3169 3170 if (ABW > BBW) 3171 B = B.zext(ABW); 3172 else if (ABW < BBW) 3173 A = A.zext(BBW); 3174 3175 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3176 } 3177 3178 /// Get a canonical unsigned division expression, or something simpler if 3179 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3180 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3181 /// it's not exact because the udiv may be clearing bits. 3182 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3183 const SCEV *RHS) { 3184 // TODO: we could try to find factors in all sorts of things, but for now we 3185 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3186 // end of this file for inspiration. 3187 3188 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3189 if (!Mul || !Mul->hasNoUnsignedWrap()) 3190 return getUDivExpr(LHS, RHS); 3191 3192 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3193 // If the mulexpr multiplies by a constant, then that constant must be the 3194 // first element of the mulexpr. 3195 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3196 if (LHSCst == RHSCst) { 3197 SmallVector<const SCEV *, 2> Operands; 3198 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3199 return getMulExpr(Operands); 3200 } 3201 3202 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3203 // that there's a factor provided by one of the other terms. We need to 3204 // check. 3205 APInt Factor = gcd(LHSCst, RHSCst); 3206 if (!Factor.isIntN(1)) { 3207 LHSCst = 3208 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3209 RHSCst = 3210 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3211 SmallVector<const SCEV *, 2> Operands; 3212 Operands.push_back(LHSCst); 3213 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3214 LHS = getMulExpr(Operands); 3215 RHS = RHSCst; 3216 Mul = dyn_cast<SCEVMulExpr>(LHS); 3217 if (!Mul) 3218 return getUDivExactExpr(LHS, RHS); 3219 } 3220 } 3221 } 3222 3223 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3224 if (Mul->getOperand(i) == RHS) { 3225 SmallVector<const SCEV *, 2> Operands; 3226 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3227 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3228 return getMulExpr(Operands); 3229 } 3230 } 3231 3232 return getUDivExpr(LHS, RHS); 3233 } 3234 3235 /// Get an add recurrence expression for the specified loop. Simplify the 3236 /// expression as much as possible. 3237 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3238 const Loop *L, 3239 SCEV::NoWrapFlags Flags) { 3240 SmallVector<const SCEV *, 4> Operands; 3241 Operands.push_back(Start); 3242 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3243 if (StepChrec->getLoop() == L) { 3244 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3245 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3246 } 3247 3248 Operands.push_back(Step); 3249 return getAddRecExpr(Operands, L, Flags); 3250 } 3251 3252 /// Get an add recurrence expression for the specified loop. Simplify the 3253 /// expression as much as possible. 3254 const SCEV * 3255 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3256 const Loop *L, SCEV::NoWrapFlags Flags) { 3257 if (Operands.size() == 1) return Operands[0]; 3258 #ifndef NDEBUG 3259 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3260 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3261 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3262 "SCEVAddRecExpr operand types don't match!"); 3263 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3264 assert(isLoopInvariant(Operands[i], L) && 3265 "SCEVAddRecExpr operand is not loop-invariant!"); 3266 #endif 3267 3268 if (Operands.back()->isZero()) { 3269 Operands.pop_back(); 3270 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3271 } 3272 3273 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3274 // use that information to infer NUW and NSW flags. However, computing a 3275 // BE count requires calling getAddRecExpr, so we may not yet have a 3276 // meaningful BE count at this point (and if we don't, we'd be stuck 3277 // with a SCEVCouldNotCompute as the cached BE count). 3278 3279 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3280 3281 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3282 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3283 const Loop *NestedLoop = NestedAR->getLoop(); 3284 if (L->contains(NestedLoop) 3285 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3286 : (!NestedLoop->contains(L) && 3287 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3288 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3289 NestedAR->op_end()); 3290 Operands[0] = NestedAR->getStart(); 3291 // AddRecs require their operands be loop-invariant with respect to their 3292 // loops. Don't perform this transformation if it would break this 3293 // requirement. 3294 bool AllInvariant = all_of( 3295 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3296 3297 if (AllInvariant) { 3298 // Create a recurrence for the outer loop with the same step size. 3299 // 3300 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3301 // inner recurrence has the same property. 3302 SCEV::NoWrapFlags OuterFlags = 3303 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3304 3305 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3306 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3307 return isLoopInvariant(Op, NestedLoop); 3308 }); 3309 3310 if (AllInvariant) { 3311 // Ok, both add recurrences are valid after the transformation. 3312 // 3313 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3314 // the outer recurrence has the same property. 3315 SCEV::NoWrapFlags InnerFlags = 3316 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3317 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3318 } 3319 } 3320 // Reset Operands to its original state. 3321 Operands[0] = NestedAR; 3322 } 3323 } 3324 3325 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3326 // already have one, otherwise create a new one. 3327 FoldingSetNodeID ID; 3328 ID.AddInteger(scAddRecExpr); 3329 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3330 ID.AddPointer(Operands[i]); 3331 ID.AddPointer(L); 3332 void *IP = nullptr; 3333 SCEVAddRecExpr *S = 3334 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3335 if (!S) { 3336 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3337 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3338 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3339 O, Operands.size(), L); 3340 UniqueSCEVs.InsertNode(S, IP); 3341 addToLoopUseLists(S); 3342 } 3343 S->setNoWrapFlags(Flags); 3344 return S; 3345 } 3346 3347 const SCEV * 3348 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3349 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3350 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3351 // getSCEV(Base)->getType() has the same address space as Base->getType() 3352 // because SCEV::getType() preserves the address space. 3353 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3354 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3355 // instruction to its SCEV, because the Instruction may be guarded by control 3356 // flow and the no-overflow bits may not be valid for the expression in any 3357 // context. This can be fixed similarly to how these flags are handled for 3358 // adds. 3359 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3360 : SCEV::FlagAnyWrap; 3361 3362 const SCEV *TotalOffset = getZero(IntPtrTy); 3363 // The array size is unimportant. The first thing we do on CurTy is getting 3364 // its element type. 3365 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3366 for (const SCEV *IndexExpr : IndexExprs) { 3367 // Compute the (potentially symbolic) offset in bytes for this index. 3368 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3369 // For a struct, add the member offset. 3370 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3371 unsigned FieldNo = Index->getZExtValue(); 3372 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3373 3374 // Add the field offset to the running total offset. 3375 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3376 3377 // Update CurTy to the type of the field at Index. 3378 CurTy = STy->getTypeAtIndex(Index); 3379 } else { 3380 // Update CurTy to its element type. 3381 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3382 // For an array, add the element offset, explicitly scaled. 3383 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3384 // Getelementptr indices are signed. 3385 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3386 3387 // Multiply the index by the element size to compute the element offset. 3388 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3389 3390 // Add the element offset to the running total offset. 3391 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3392 } 3393 } 3394 3395 // Add the total offset from all the GEP indices to the base. 3396 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3397 } 3398 3399 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3400 const SCEV *RHS) { 3401 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3402 return getSMaxExpr(Ops); 3403 } 3404 3405 const SCEV * 3406 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3407 assert(!Ops.empty() && "Cannot get empty smax!"); 3408 if (Ops.size() == 1) return Ops[0]; 3409 #ifndef NDEBUG 3410 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3411 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3412 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3413 "SCEVSMaxExpr operand types don't match!"); 3414 #endif 3415 3416 // Sort by complexity, this groups all similar expression types together. 3417 GroupByComplexity(Ops, &LI, DT); 3418 3419 // If there are any constants, fold them together. 3420 unsigned Idx = 0; 3421 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3422 ++Idx; 3423 assert(Idx < Ops.size()); 3424 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3425 // We found two constants, fold them together! 3426 ConstantInt *Fold = ConstantInt::get( 3427 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3428 Ops[0] = getConstant(Fold); 3429 Ops.erase(Ops.begin()+1); // Erase the folded element 3430 if (Ops.size() == 1) return Ops[0]; 3431 LHSC = cast<SCEVConstant>(Ops[0]); 3432 } 3433 3434 // If we are left with a constant minimum-int, strip it off. 3435 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3436 Ops.erase(Ops.begin()); 3437 --Idx; 3438 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3439 // If we have an smax with a constant maximum-int, it will always be 3440 // maximum-int. 3441 return Ops[0]; 3442 } 3443 3444 if (Ops.size() == 1) return Ops[0]; 3445 } 3446 3447 // Find the first SMax 3448 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3449 ++Idx; 3450 3451 // Check to see if one of the operands is an SMax. If so, expand its operands 3452 // onto our operand list, and recurse to simplify. 3453 if (Idx < Ops.size()) { 3454 bool DeletedSMax = false; 3455 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3456 Ops.erase(Ops.begin()+Idx); 3457 Ops.append(SMax->op_begin(), SMax->op_end()); 3458 DeletedSMax = true; 3459 } 3460 3461 if (DeletedSMax) 3462 return getSMaxExpr(Ops); 3463 } 3464 3465 // Okay, check to see if the same value occurs in the operand list twice. If 3466 // so, delete one. Since we sorted the list, these values are required to 3467 // be adjacent. 3468 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3469 // X smax Y smax Y --> X smax Y 3470 // X smax Y --> X, if X is always greater than Y 3471 if (Ops[i] == Ops[i+1] || 3472 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3473 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3474 --i; --e; 3475 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3476 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3477 --i; --e; 3478 } 3479 3480 if (Ops.size() == 1) return Ops[0]; 3481 3482 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3483 3484 // Okay, it looks like we really DO need an smax expr. Check to see if we 3485 // already have one, otherwise create a new one. 3486 FoldingSetNodeID ID; 3487 ID.AddInteger(scSMaxExpr); 3488 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3489 ID.AddPointer(Ops[i]); 3490 void *IP = nullptr; 3491 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3492 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3493 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3494 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3495 O, Ops.size()); 3496 UniqueSCEVs.InsertNode(S, IP); 3497 addToLoopUseLists(S); 3498 return S; 3499 } 3500 3501 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3502 const SCEV *RHS) { 3503 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3504 return getUMaxExpr(Ops); 3505 } 3506 3507 const SCEV * 3508 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3509 assert(!Ops.empty() && "Cannot get empty umax!"); 3510 if (Ops.size() == 1) return Ops[0]; 3511 #ifndef NDEBUG 3512 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3513 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3514 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3515 "SCEVUMaxExpr operand types don't match!"); 3516 #endif 3517 3518 // Sort by complexity, this groups all similar expression types together. 3519 GroupByComplexity(Ops, &LI, DT); 3520 3521 // If there are any constants, fold them together. 3522 unsigned Idx = 0; 3523 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3524 ++Idx; 3525 assert(Idx < Ops.size()); 3526 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3527 // We found two constants, fold them together! 3528 ConstantInt *Fold = ConstantInt::get( 3529 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3530 Ops[0] = getConstant(Fold); 3531 Ops.erase(Ops.begin()+1); // Erase the folded element 3532 if (Ops.size() == 1) return Ops[0]; 3533 LHSC = cast<SCEVConstant>(Ops[0]); 3534 } 3535 3536 // If we are left with a constant minimum-int, strip it off. 3537 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3538 Ops.erase(Ops.begin()); 3539 --Idx; 3540 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3541 // If we have an umax with a constant maximum-int, it will always be 3542 // maximum-int. 3543 return Ops[0]; 3544 } 3545 3546 if (Ops.size() == 1) return Ops[0]; 3547 } 3548 3549 // Find the first UMax 3550 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3551 ++Idx; 3552 3553 // Check to see if one of the operands is a UMax. If so, expand its operands 3554 // onto our operand list, and recurse to simplify. 3555 if (Idx < Ops.size()) { 3556 bool DeletedUMax = false; 3557 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3558 Ops.erase(Ops.begin()+Idx); 3559 Ops.append(UMax->op_begin(), UMax->op_end()); 3560 DeletedUMax = true; 3561 } 3562 3563 if (DeletedUMax) 3564 return getUMaxExpr(Ops); 3565 } 3566 3567 // Okay, check to see if the same value occurs in the operand list twice. If 3568 // so, delete one. Since we sorted the list, these values are required to 3569 // be adjacent. 3570 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3571 // X umax Y umax Y --> X umax Y 3572 // X umax Y --> X, if X is always greater than Y 3573 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3574 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3575 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3576 --i; --e; 3577 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3578 Ops[i + 1])) { 3579 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3580 --i; --e; 3581 } 3582 3583 if (Ops.size() == 1) return Ops[0]; 3584 3585 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3586 3587 // Okay, it looks like we really DO need a umax expr. Check to see if we 3588 // already have one, otherwise create a new one. 3589 FoldingSetNodeID ID; 3590 ID.AddInteger(scUMaxExpr); 3591 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3592 ID.AddPointer(Ops[i]); 3593 void *IP = nullptr; 3594 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3595 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3596 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3597 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3598 O, Ops.size()); 3599 UniqueSCEVs.InsertNode(S, IP); 3600 addToLoopUseLists(S); 3601 return S; 3602 } 3603 3604 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3605 const SCEV *RHS) { 3606 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3607 return getSMinExpr(Ops); 3608 } 3609 3610 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3611 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3612 SmallVector<const SCEV *, 2> NotOps; 3613 for (auto *S : Ops) 3614 NotOps.push_back(getNotSCEV(S)); 3615 return getNotSCEV(getSMaxExpr(NotOps)); 3616 } 3617 3618 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3619 const SCEV *RHS) { 3620 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3621 return getUMinExpr(Ops); 3622 } 3623 3624 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3625 assert(!Ops.empty() && "At least one operand must be!"); 3626 // Trivial case. 3627 if (Ops.size() == 1) 3628 return Ops[0]; 3629 3630 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3631 SmallVector<const SCEV *, 2> NotOps; 3632 for (auto *S : Ops) 3633 NotOps.push_back(getNotSCEV(S)); 3634 return getNotSCEV(getUMaxExpr(NotOps)); 3635 } 3636 3637 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3638 // We can bypass creating a target-independent 3639 // constant expression and then folding it back into a ConstantInt. 3640 // This is just a compile-time optimization. 3641 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3642 } 3643 3644 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3645 StructType *STy, 3646 unsigned FieldNo) { 3647 // We can bypass creating a target-independent 3648 // constant expression and then folding it back into a ConstantInt. 3649 // This is just a compile-time optimization. 3650 return getConstant( 3651 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3652 } 3653 3654 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3655 // Don't attempt to do anything other than create a SCEVUnknown object 3656 // here. createSCEV only calls getUnknown after checking for all other 3657 // interesting possibilities, and any other code that calls getUnknown 3658 // is doing so in order to hide a value from SCEV canonicalization. 3659 3660 FoldingSetNodeID ID; 3661 ID.AddInteger(scUnknown); 3662 ID.AddPointer(V); 3663 void *IP = nullptr; 3664 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3665 assert(cast<SCEVUnknown>(S)->getValue() == V && 3666 "Stale SCEVUnknown in uniquing map!"); 3667 return S; 3668 } 3669 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3670 FirstUnknown); 3671 FirstUnknown = cast<SCEVUnknown>(S); 3672 UniqueSCEVs.InsertNode(S, IP); 3673 return S; 3674 } 3675 3676 //===----------------------------------------------------------------------===// 3677 // Basic SCEV Analysis and PHI Idiom Recognition Code 3678 // 3679 3680 /// Test if values of the given type are analyzable within the SCEV 3681 /// framework. This primarily includes integer types, and it can optionally 3682 /// include pointer types if the ScalarEvolution class has access to 3683 /// target-specific information. 3684 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3685 // Integers and pointers are always SCEVable. 3686 return Ty->isIntOrPtrTy(); 3687 } 3688 3689 /// Return the size in bits of the specified type, for which isSCEVable must 3690 /// return true. 3691 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3692 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3693 if (Ty->isPointerTy()) 3694 return getDataLayout().getIndexTypeSizeInBits(Ty); 3695 return getDataLayout().getTypeSizeInBits(Ty); 3696 } 3697 3698 /// Return a type with the same bitwidth as the given type and which represents 3699 /// how SCEV will treat the given type, for which isSCEVable must return 3700 /// true. For pointer types, this is the pointer-sized integer type. 3701 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3702 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3703 3704 if (Ty->isIntegerTy()) 3705 return Ty; 3706 3707 // The only other support type is pointer. 3708 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3709 return getDataLayout().getIntPtrType(Ty); 3710 } 3711 3712 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3713 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3714 } 3715 3716 const SCEV *ScalarEvolution::getCouldNotCompute() { 3717 return CouldNotCompute.get(); 3718 } 3719 3720 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3721 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3722 auto *SU = dyn_cast<SCEVUnknown>(S); 3723 return SU && SU->getValue() == nullptr; 3724 }); 3725 3726 return !ContainsNulls; 3727 } 3728 3729 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3730 HasRecMapType::iterator I = HasRecMap.find(S); 3731 if (I != HasRecMap.end()) 3732 return I->second; 3733 3734 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3735 HasRecMap.insert({S, FoundAddRec}); 3736 return FoundAddRec; 3737 } 3738 3739 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3740 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3741 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3742 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3743 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3744 if (!Add) 3745 return {S, nullptr}; 3746 3747 if (Add->getNumOperands() != 2) 3748 return {S, nullptr}; 3749 3750 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3751 if (!ConstOp) 3752 return {S, nullptr}; 3753 3754 return {Add->getOperand(1), ConstOp->getValue()}; 3755 } 3756 3757 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3758 /// by the value and offset from any ValueOffsetPair in the set. 3759 SetVector<ScalarEvolution::ValueOffsetPair> * 3760 ScalarEvolution::getSCEVValues(const SCEV *S) { 3761 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3762 if (SI == ExprValueMap.end()) 3763 return nullptr; 3764 #ifndef NDEBUG 3765 if (VerifySCEVMap) { 3766 // Check there is no dangling Value in the set returned. 3767 for (const auto &VE : SI->second) 3768 assert(ValueExprMap.count(VE.first)); 3769 } 3770 #endif 3771 return &SI->second; 3772 } 3773 3774 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3775 /// cannot be used separately. eraseValueFromMap should be used to remove 3776 /// V from ValueExprMap and ExprValueMap at the same time. 3777 void ScalarEvolution::eraseValueFromMap(Value *V) { 3778 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3779 if (I != ValueExprMap.end()) { 3780 const SCEV *S = I->second; 3781 // Remove {V, 0} from the set of ExprValueMap[S] 3782 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3783 SV->remove({V, nullptr}); 3784 3785 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3786 const SCEV *Stripped; 3787 ConstantInt *Offset; 3788 std::tie(Stripped, Offset) = splitAddExpr(S); 3789 if (Offset != nullptr) { 3790 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3791 SV->remove({V, Offset}); 3792 } 3793 ValueExprMap.erase(V); 3794 } 3795 } 3796 3797 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3798 /// TODO: In reality it is better to check the poison recursevely 3799 /// but this is better than nothing. 3800 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3801 if (auto *I = dyn_cast<Instruction>(V)) { 3802 if (isa<OverflowingBinaryOperator>(I)) { 3803 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3804 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3805 return true; 3806 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3807 return true; 3808 } 3809 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3810 return true; 3811 } 3812 return false; 3813 } 3814 3815 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3816 /// create a new one. 3817 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3818 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3819 3820 const SCEV *S = getExistingSCEV(V); 3821 if (S == nullptr) { 3822 S = createSCEV(V); 3823 // During PHI resolution, it is possible to create two SCEVs for the same 3824 // V, so it is needed to double check whether V->S is inserted into 3825 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3826 std::pair<ValueExprMapType::iterator, bool> Pair = 3827 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3828 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3829 ExprValueMap[S].insert({V, nullptr}); 3830 3831 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3832 // ExprValueMap. 3833 const SCEV *Stripped = S; 3834 ConstantInt *Offset = nullptr; 3835 std::tie(Stripped, Offset) = splitAddExpr(S); 3836 // If stripped is SCEVUnknown, don't bother to save 3837 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3838 // increase the complexity of the expansion code. 3839 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3840 // because it may generate add/sub instead of GEP in SCEV expansion. 3841 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3842 !isa<GetElementPtrInst>(V)) 3843 ExprValueMap[Stripped].insert({V, Offset}); 3844 } 3845 } 3846 return S; 3847 } 3848 3849 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3850 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3851 3852 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3853 if (I != ValueExprMap.end()) { 3854 const SCEV *S = I->second; 3855 if (checkValidity(S)) 3856 return S; 3857 eraseValueFromMap(V); 3858 forgetMemoizedResults(S); 3859 } 3860 return nullptr; 3861 } 3862 3863 /// Return a SCEV corresponding to -V = -1*V 3864 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3865 SCEV::NoWrapFlags Flags) { 3866 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3867 return getConstant( 3868 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3869 3870 Type *Ty = V->getType(); 3871 Ty = getEffectiveSCEVType(Ty); 3872 return getMulExpr( 3873 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3874 } 3875 3876 /// Return a SCEV corresponding to ~V = -1-V 3877 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3878 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3879 return getConstant( 3880 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3881 3882 Type *Ty = V->getType(); 3883 Ty = getEffectiveSCEVType(Ty); 3884 const SCEV *AllOnes = 3885 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3886 return getMinusSCEV(AllOnes, V); 3887 } 3888 3889 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3890 SCEV::NoWrapFlags Flags, 3891 unsigned Depth) { 3892 // Fast path: X - X --> 0. 3893 if (LHS == RHS) 3894 return getZero(LHS->getType()); 3895 3896 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3897 // makes it so that we cannot make much use of NUW. 3898 auto AddFlags = SCEV::FlagAnyWrap; 3899 const bool RHSIsNotMinSigned = 3900 !getSignedRangeMin(RHS).isMinSignedValue(); 3901 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3902 // Let M be the minimum representable signed value. Then (-1)*RHS 3903 // signed-wraps if and only if RHS is M. That can happen even for 3904 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3905 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3906 // (-1)*RHS, we need to prove that RHS != M. 3907 // 3908 // If LHS is non-negative and we know that LHS - RHS does not 3909 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3910 // either by proving that RHS > M or that LHS >= 0. 3911 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3912 AddFlags = SCEV::FlagNSW; 3913 } 3914 } 3915 3916 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3917 // RHS is NSW and LHS >= 0. 3918 // 3919 // The difficulty here is that the NSW flag may have been proven 3920 // relative to a loop that is to be found in a recurrence in LHS and 3921 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3922 // larger scope than intended. 3923 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3924 3925 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3926 } 3927 3928 const SCEV * 3929 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3930 Type *SrcTy = V->getType(); 3931 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3932 "Cannot truncate or zero extend with non-integer arguments!"); 3933 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3934 return V; // No conversion 3935 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3936 return getTruncateExpr(V, Ty); 3937 return getZeroExtendExpr(V, Ty); 3938 } 3939 3940 const SCEV * 3941 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3942 Type *Ty) { 3943 Type *SrcTy = V->getType(); 3944 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3945 "Cannot truncate or zero extend with non-integer arguments!"); 3946 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3947 return V; // No conversion 3948 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3949 return getTruncateExpr(V, Ty); 3950 return getSignExtendExpr(V, Ty); 3951 } 3952 3953 const SCEV * 3954 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3955 Type *SrcTy = V->getType(); 3956 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3957 "Cannot noop or zero extend with non-integer arguments!"); 3958 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3959 "getNoopOrZeroExtend cannot truncate!"); 3960 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3961 return V; // No conversion 3962 return getZeroExtendExpr(V, Ty); 3963 } 3964 3965 const SCEV * 3966 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3967 Type *SrcTy = V->getType(); 3968 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3969 "Cannot noop or sign extend with non-integer arguments!"); 3970 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3971 "getNoopOrSignExtend cannot truncate!"); 3972 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3973 return V; // No conversion 3974 return getSignExtendExpr(V, Ty); 3975 } 3976 3977 const SCEV * 3978 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3979 Type *SrcTy = V->getType(); 3980 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3981 "Cannot noop or any extend with non-integer arguments!"); 3982 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3983 "getNoopOrAnyExtend cannot truncate!"); 3984 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3985 return V; // No conversion 3986 return getAnyExtendExpr(V, Ty); 3987 } 3988 3989 const SCEV * 3990 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3991 Type *SrcTy = V->getType(); 3992 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3993 "Cannot truncate or noop with non-integer arguments!"); 3994 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3995 "getTruncateOrNoop cannot extend!"); 3996 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3997 return V; // No conversion 3998 return getTruncateExpr(V, Ty); 3999 } 4000 4001 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4002 const SCEV *RHS) { 4003 const SCEV *PromotedLHS = LHS; 4004 const SCEV *PromotedRHS = RHS; 4005 4006 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4007 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4008 else 4009 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4010 4011 return getUMaxExpr(PromotedLHS, PromotedRHS); 4012 } 4013 4014 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4015 const SCEV *RHS) { 4016 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4017 return getUMinFromMismatchedTypes(Ops); 4018 } 4019 4020 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4021 SmallVectorImpl<const SCEV *> &Ops) { 4022 assert(!Ops.empty() && "At least one operand must be!"); 4023 // Trivial case. 4024 if (Ops.size() == 1) 4025 return Ops[0]; 4026 4027 // Find the max type first. 4028 Type *MaxType = nullptr; 4029 for (auto *S : Ops) 4030 if (MaxType) 4031 MaxType = getWiderType(MaxType, S->getType()); 4032 else 4033 MaxType = S->getType(); 4034 4035 // Extend all ops to max type. 4036 SmallVector<const SCEV *, 2> PromotedOps; 4037 for (auto *S : Ops) 4038 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4039 4040 // Generate umin. 4041 return getUMinExpr(PromotedOps); 4042 } 4043 4044 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4045 // A pointer operand may evaluate to a nonpointer expression, such as null. 4046 if (!V->getType()->isPointerTy()) 4047 return V; 4048 4049 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4050 return getPointerBase(Cast->getOperand()); 4051 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4052 const SCEV *PtrOp = nullptr; 4053 for (const SCEV *NAryOp : NAry->operands()) { 4054 if (NAryOp->getType()->isPointerTy()) { 4055 // Cannot find the base of an expression with multiple pointer operands. 4056 if (PtrOp) 4057 return V; 4058 PtrOp = NAryOp; 4059 } 4060 } 4061 if (!PtrOp) 4062 return V; 4063 return getPointerBase(PtrOp); 4064 } 4065 return V; 4066 } 4067 4068 /// Push users of the given Instruction onto the given Worklist. 4069 static void 4070 PushDefUseChildren(Instruction *I, 4071 SmallVectorImpl<Instruction *> &Worklist) { 4072 // Push the def-use children onto the Worklist stack. 4073 for (User *U : I->users()) 4074 Worklist.push_back(cast<Instruction>(U)); 4075 } 4076 4077 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4078 SmallVector<Instruction *, 16> Worklist; 4079 PushDefUseChildren(PN, Worklist); 4080 4081 SmallPtrSet<Instruction *, 8> Visited; 4082 Visited.insert(PN); 4083 while (!Worklist.empty()) { 4084 Instruction *I = Worklist.pop_back_val(); 4085 if (!Visited.insert(I).second) 4086 continue; 4087 4088 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4089 if (It != ValueExprMap.end()) { 4090 const SCEV *Old = It->second; 4091 4092 // Short-circuit the def-use traversal if the symbolic name 4093 // ceases to appear in expressions. 4094 if (Old != SymName && !hasOperand(Old, SymName)) 4095 continue; 4096 4097 // SCEVUnknown for a PHI either means that it has an unrecognized 4098 // structure, it's a PHI that's in the progress of being computed 4099 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4100 // additional loop trip count information isn't going to change anything. 4101 // In the second case, createNodeForPHI will perform the necessary 4102 // updates on its own when it gets to that point. In the third, we do 4103 // want to forget the SCEVUnknown. 4104 if (!isa<PHINode>(I) || 4105 !isa<SCEVUnknown>(Old) || 4106 (I != PN && Old == SymName)) { 4107 eraseValueFromMap(It->first); 4108 forgetMemoizedResults(Old); 4109 } 4110 } 4111 4112 PushDefUseChildren(I, Worklist); 4113 } 4114 } 4115 4116 namespace { 4117 4118 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4119 /// expression in case its Loop is L. If it is not L then 4120 /// if IgnoreOtherLoops is true then use AddRec itself 4121 /// otherwise rewrite cannot be done. 4122 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4123 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4124 public: 4125 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4126 bool IgnoreOtherLoops = true) { 4127 SCEVInitRewriter Rewriter(L, SE); 4128 const SCEV *Result = Rewriter.visit(S); 4129 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4130 return SE.getCouldNotCompute(); 4131 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4132 ? SE.getCouldNotCompute() 4133 : Result; 4134 } 4135 4136 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4137 if (!SE.isLoopInvariant(Expr, L)) 4138 SeenLoopVariantSCEVUnknown = true; 4139 return Expr; 4140 } 4141 4142 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4143 // Only re-write AddRecExprs for this loop. 4144 if (Expr->getLoop() == L) 4145 return Expr->getStart(); 4146 SeenOtherLoops = true; 4147 return Expr; 4148 } 4149 4150 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4151 4152 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4153 4154 private: 4155 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4156 : SCEVRewriteVisitor(SE), L(L) {} 4157 4158 const Loop *L; 4159 bool SeenLoopVariantSCEVUnknown = false; 4160 bool SeenOtherLoops = false; 4161 }; 4162 4163 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4164 /// increment expression in case its Loop is L. If it is not L then 4165 /// use AddRec itself. 4166 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4167 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4168 public: 4169 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4170 SCEVPostIncRewriter Rewriter(L, SE); 4171 const SCEV *Result = Rewriter.visit(S); 4172 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4173 ? SE.getCouldNotCompute() 4174 : Result; 4175 } 4176 4177 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4178 if (!SE.isLoopInvariant(Expr, L)) 4179 SeenLoopVariantSCEVUnknown = true; 4180 return Expr; 4181 } 4182 4183 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4184 // Only re-write AddRecExprs for this loop. 4185 if (Expr->getLoop() == L) 4186 return Expr->getPostIncExpr(SE); 4187 SeenOtherLoops = true; 4188 return Expr; 4189 } 4190 4191 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4192 4193 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4194 4195 private: 4196 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4197 : SCEVRewriteVisitor(SE), L(L) {} 4198 4199 const Loop *L; 4200 bool SeenLoopVariantSCEVUnknown = false; 4201 bool SeenOtherLoops = false; 4202 }; 4203 4204 /// This class evaluates the compare condition by matching it against the 4205 /// condition of loop latch. If there is a match we assume a true value 4206 /// for the condition while building SCEV nodes. 4207 class SCEVBackedgeConditionFolder 4208 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4209 public: 4210 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4211 ScalarEvolution &SE) { 4212 bool IsPosBECond = false; 4213 Value *BECond = nullptr; 4214 if (BasicBlock *Latch = L->getLoopLatch()) { 4215 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4216 if (BI && BI->isConditional()) { 4217 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4218 "Both outgoing branches should not target same header!"); 4219 BECond = BI->getCondition(); 4220 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4221 } else { 4222 return S; 4223 } 4224 } 4225 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4226 return Rewriter.visit(S); 4227 } 4228 4229 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4230 const SCEV *Result = Expr; 4231 bool InvariantF = SE.isLoopInvariant(Expr, L); 4232 4233 if (!InvariantF) { 4234 Instruction *I = cast<Instruction>(Expr->getValue()); 4235 switch (I->getOpcode()) { 4236 case Instruction::Select: { 4237 SelectInst *SI = cast<SelectInst>(I); 4238 Optional<const SCEV *> Res = 4239 compareWithBackedgeCondition(SI->getCondition()); 4240 if (Res.hasValue()) { 4241 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4242 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4243 } 4244 break; 4245 } 4246 default: { 4247 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4248 if (Res.hasValue()) 4249 Result = Res.getValue(); 4250 break; 4251 } 4252 } 4253 } 4254 return Result; 4255 } 4256 4257 private: 4258 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4259 bool IsPosBECond, ScalarEvolution &SE) 4260 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4261 IsPositiveBECond(IsPosBECond) {} 4262 4263 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4264 4265 const Loop *L; 4266 /// Loop back condition. 4267 Value *BackedgeCond = nullptr; 4268 /// Set to true if loop back is on positive branch condition. 4269 bool IsPositiveBECond; 4270 }; 4271 4272 Optional<const SCEV *> 4273 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4274 4275 // If value matches the backedge condition for loop latch, 4276 // then return a constant evolution node based on loopback 4277 // branch taken. 4278 if (BackedgeCond == IC) 4279 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4280 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4281 return None; 4282 } 4283 4284 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4285 public: 4286 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4287 ScalarEvolution &SE) { 4288 SCEVShiftRewriter Rewriter(L, SE); 4289 const SCEV *Result = Rewriter.visit(S); 4290 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4291 } 4292 4293 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4294 // Only allow AddRecExprs for this loop. 4295 if (!SE.isLoopInvariant(Expr, L)) 4296 Valid = false; 4297 return Expr; 4298 } 4299 4300 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4301 if (Expr->getLoop() == L && Expr->isAffine()) 4302 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4303 Valid = false; 4304 return Expr; 4305 } 4306 4307 bool isValid() { return Valid; } 4308 4309 private: 4310 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4311 : SCEVRewriteVisitor(SE), L(L) {} 4312 4313 const Loop *L; 4314 bool Valid = true; 4315 }; 4316 4317 } // end anonymous namespace 4318 4319 SCEV::NoWrapFlags 4320 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4321 if (!AR->isAffine()) 4322 return SCEV::FlagAnyWrap; 4323 4324 using OBO = OverflowingBinaryOperator; 4325 4326 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4327 4328 if (!AR->hasNoSignedWrap()) { 4329 ConstantRange AddRecRange = getSignedRange(AR); 4330 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4331 4332 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4333 Instruction::Add, IncRange, OBO::NoSignedWrap); 4334 if (NSWRegion.contains(AddRecRange)) 4335 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4336 } 4337 4338 if (!AR->hasNoUnsignedWrap()) { 4339 ConstantRange AddRecRange = getUnsignedRange(AR); 4340 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4341 4342 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4343 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4344 if (NUWRegion.contains(AddRecRange)) 4345 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4346 } 4347 4348 return Result; 4349 } 4350 4351 namespace { 4352 4353 /// Represents an abstract binary operation. This may exist as a 4354 /// normal instruction or constant expression, or may have been 4355 /// derived from an expression tree. 4356 struct BinaryOp { 4357 unsigned Opcode; 4358 Value *LHS; 4359 Value *RHS; 4360 bool IsNSW = false; 4361 bool IsNUW = false; 4362 4363 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4364 /// constant expression. 4365 Operator *Op = nullptr; 4366 4367 explicit BinaryOp(Operator *Op) 4368 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4369 Op(Op) { 4370 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4371 IsNSW = OBO->hasNoSignedWrap(); 4372 IsNUW = OBO->hasNoUnsignedWrap(); 4373 } 4374 } 4375 4376 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4377 bool IsNUW = false) 4378 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4379 }; 4380 4381 } // end anonymous namespace 4382 4383 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4384 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4385 auto *Op = dyn_cast<Operator>(V); 4386 if (!Op) 4387 return None; 4388 4389 // Implementation detail: all the cleverness here should happen without 4390 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4391 // SCEV expressions when possible, and we should not break that. 4392 4393 switch (Op->getOpcode()) { 4394 case Instruction::Add: 4395 case Instruction::Sub: 4396 case Instruction::Mul: 4397 case Instruction::UDiv: 4398 case Instruction::URem: 4399 case Instruction::And: 4400 case Instruction::Or: 4401 case Instruction::AShr: 4402 case Instruction::Shl: 4403 return BinaryOp(Op); 4404 4405 case Instruction::Xor: 4406 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4407 // If the RHS of the xor is a signmask, then this is just an add. 4408 // Instcombine turns add of signmask into xor as a strength reduction step. 4409 if (RHSC->getValue().isSignMask()) 4410 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4411 return BinaryOp(Op); 4412 4413 case Instruction::LShr: 4414 // Turn logical shift right of a constant into a unsigned divide. 4415 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4416 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4417 4418 // If the shift count is not less than the bitwidth, the result of 4419 // the shift is undefined. Don't try to analyze it, because the 4420 // resolution chosen here may differ from the resolution chosen in 4421 // other parts of the compiler. 4422 if (SA->getValue().ult(BitWidth)) { 4423 Constant *X = 4424 ConstantInt::get(SA->getContext(), 4425 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4426 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4427 } 4428 } 4429 return BinaryOp(Op); 4430 4431 case Instruction::ExtractValue: { 4432 auto *EVI = cast<ExtractValueInst>(Op); 4433 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4434 break; 4435 4436 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4437 if (!CI) 4438 break; 4439 4440 if (auto *F = CI->getCalledFunction()) 4441 switch (F->getIntrinsicID()) { 4442 case Intrinsic::sadd_with_overflow: 4443 case Intrinsic::uadd_with_overflow: 4444 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4445 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4446 CI->getArgOperand(1)); 4447 4448 // Now that we know that all uses of the arithmetic-result component of 4449 // CI are guarded by the overflow check, we can go ahead and pretend 4450 // that the arithmetic is non-overflowing. 4451 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4452 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4453 CI->getArgOperand(1), /* IsNSW = */ true, 4454 /* IsNUW = */ false); 4455 else 4456 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4457 CI->getArgOperand(1), /* IsNSW = */ false, 4458 /* IsNUW*/ true); 4459 case Intrinsic::ssub_with_overflow: 4460 case Intrinsic::usub_with_overflow: 4461 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4462 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4463 CI->getArgOperand(1)); 4464 4465 // The same reasoning as sadd/uadd above. 4466 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4467 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4468 CI->getArgOperand(1), /* IsNSW = */ true, 4469 /* IsNUW = */ false); 4470 else 4471 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4472 CI->getArgOperand(1), /* IsNSW = */ false, 4473 /* IsNUW = */ true); 4474 case Intrinsic::smul_with_overflow: 4475 case Intrinsic::umul_with_overflow: 4476 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4477 CI->getArgOperand(1)); 4478 default: 4479 break; 4480 } 4481 break; 4482 } 4483 4484 default: 4485 break; 4486 } 4487 4488 return None; 4489 } 4490 4491 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4492 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4493 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4494 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4495 /// follows one of the following patterns: 4496 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4497 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4498 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4499 /// we return the type of the truncation operation, and indicate whether the 4500 /// truncated type should be treated as signed/unsigned by setting 4501 /// \p Signed to true/false, respectively. 4502 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4503 bool &Signed, ScalarEvolution &SE) { 4504 // The case where Op == SymbolicPHI (that is, with no type conversions on 4505 // the way) is handled by the regular add recurrence creating logic and 4506 // would have already been triggered in createAddRecForPHI. Reaching it here 4507 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4508 // because one of the other operands of the SCEVAddExpr updating this PHI is 4509 // not invariant). 4510 // 4511 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4512 // this case predicates that allow us to prove that Op == SymbolicPHI will 4513 // be added. 4514 if (Op == SymbolicPHI) 4515 return nullptr; 4516 4517 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4518 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4519 if (SourceBits != NewBits) 4520 return nullptr; 4521 4522 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4523 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4524 if (!SExt && !ZExt) 4525 return nullptr; 4526 const SCEVTruncateExpr *Trunc = 4527 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4528 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4529 if (!Trunc) 4530 return nullptr; 4531 const SCEV *X = Trunc->getOperand(); 4532 if (X != SymbolicPHI) 4533 return nullptr; 4534 Signed = SExt != nullptr; 4535 return Trunc->getType(); 4536 } 4537 4538 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4539 if (!PN->getType()->isIntegerTy()) 4540 return nullptr; 4541 const Loop *L = LI.getLoopFor(PN->getParent()); 4542 if (!L || L->getHeader() != PN->getParent()) 4543 return nullptr; 4544 return L; 4545 } 4546 4547 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4548 // computation that updates the phi follows the following pattern: 4549 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4550 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4551 // If so, try to see if it can be rewritten as an AddRecExpr under some 4552 // Predicates. If successful, return them as a pair. Also cache the results 4553 // of the analysis. 4554 // 4555 // Example usage scenario: 4556 // Say the Rewriter is called for the following SCEV: 4557 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4558 // where: 4559 // %X = phi i64 (%Start, %BEValue) 4560 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4561 // and call this function with %SymbolicPHI = %X. 4562 // 4563 // The analysis will find that the value coming around the backedge has 4564 // the following SCEV: 4565 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4566 // Upon concluding that this matches the desired pattern, the function 4567 // will return the pair {NewAddRec, SmallPredsVec} where: 4568 // NewAddRec = {%Start,+,%Step} 4569 // SmallPredsVec = {P1, P2, P3} as follows: 4570 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4571 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4572 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4573 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4574 // under the predicates {P1,P2,P3}. 4575 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4576 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4577 // 4578 // TODO's: 4579 // 4580 // 1) Extend the Induction descriptor to also support inductions that involve 4581 // casts: When needed (namely, when we are called in the context of the 4582 // vectorizer induction analysis), a Set of cast instructions will be 4583 // populated by this method, and provided back to isInductionPHI. This is 4584 // needed to allow the vectorizer to properly record them to be ignored by 4585 // the cost model and to avoid vectorizing them (otherwise these casts, 4586 // which are redundant under the runtime overflow checks, will be 4587 // vectorized, which can be costly). 4588 // 4589 // 2) Support additional induction/PHISCEV patterns: We also want to support 4590 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4591 // after the induction update operation (the induction increment): 4592 // 4593 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4594 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4595 // 4596 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4597 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4598 // 4599 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4600 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4601 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4602 SmallVector<const SCEVPredicate *, 3> Predicates; 4603 4604 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4605 // return an AddRec expression under some predicate. 4606 4607 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4608 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4609 assert(L && "Expecting an integer loop header phi"); 4610 4611 // The loop may have multiple entrances or multiple exits; we can analyze 4612 // this phi as an addrec if it has a unique entry value and a unique 4613 // backedge value. 4614 Value *BEValueV = nullptr, *StartValueV = nullptr; 4615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4616 Value *V = PN->getIncomingValue(i); 4617 if (L->contains(PN->getIncomingBlock(i))) { 4618 if (!BEValueV) { 4619 BEValueV = V; 4620 } else if (BEValueV != V) { 4621 BEValueV = nullptr; 4622 break; 4623 } 4624 } else if (!StartValueV) { 4625 StartValueV = V; 4626 } else if (StartValueV != V) { 4627 StartValueV = nullptr; 4628 break; 4629 } 4630 } 4631 if (!BEValueV || !StartValueV) 4632 return None; 4633 4634 const SCEV *BEValue = getSCEV(BEValueV); 4635 4636 // If the value coming around the backedge is an add with the symbolic 4637 // value we just inserted, possibly with casts that we can ignore under 4638 // an appropriate runtime guard, then we found a simple induction variable! 4639 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4640 if (!Add) 4641 return None; 4642 4643 // If there is a single occurrence of the symbolic value, possibly 4644 // casted, replace it with a recurrence. 4645 unsigned FoundIndex = Add->getNumOperands(); 4646 Type *TruncTy = nullptr; 4647 bool Signed; 4648 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4649 if ((TruncTy = 4650 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4651 if (FoundIndex == e) { 4652 FoundIndex = i; 4653 break; 4654 } 4655 4656 if (FoundIndex == Add->getNumOperands()) 4657 return None; 4658 4659 // Create an add with everything but the specified operand. 4660 SmallVector<const SCEV *, 8> Ops; 4661 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4662 if (i != FoundIndex) 4663 Ops.push_back(Add->getOperand(i)); 4664 const SCEV *Accum = getAddExpr(Ops); 4665 4666 // The runtime checks will not be valid if the step amount is 4667 // varying inside the loop. 4668 if (!isLoopInvariant(Accum, L)) 4669 return None; 4670 4671 // *** Part2: Create the predicates 4672 4673 // Analysis was successful: we have a phi-with-cast pattern for which we 4674 // can return an AddRec expression under the following predicates: 4675 // 4676 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4677 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4678 // P2: An Equal predicate that guarantees that 4679 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4680 // P3: An Equal predicate that guarantees that 4681 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4682 // 4683 // As we next prove, the above predicates guarantee that: 4684 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4685 // 4686 // 4687 // More formally, we want to prove that: 4688 // Expr(i+1) = Start + (i+1) * Accum 4689 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4690 // 4691 // Given that: 4692 // 1) Expr(0) = Start 4693 // 2) Expr(1) = Start + Accum 4694 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4695 // 3) Induction hypothesis (step i): 4696 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4697 // 4698 // Proof: 4699 // Expr(i+1) = 4700 // = Start + (i+1)*Accum 4701 // = (Start + i*Accum) + Accum 4702 // = Expr(i) + Accum 4703 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4704 // :: from step i 4705 // 4706 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4707 // 4708 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4709 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4710 // + Accum :: from P3 4711 // 4712 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4713 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4714 // 4715 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4716 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4717 // 4718 // By induction, the same applies to all iterations 1<=i<n: 4719 // 4720 4721 // Create a truncated addrec for which we will add a no overflow check (P1). 4722 const SCEV *StartVal = getSCEV(StartValueV); 4723 const SCEV *PHISCEV = 4724 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4725 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4726 4727 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4728 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4729 // will be constant. 4730 // 4731 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4732 // add P1. 4733 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4734 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4735 Signed ? SCEVWrapPredicate::IncrementNSSW 4736 : SCEVWrapPredicate::IncrementNUSW; 4737 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4738 Predicates.push_back(AddRecPred); 4739 } 4740 4741 // Create the Equal Predicates P2,P3: 4742 4743 // It is possible that the predicates P2 and/or P3 are computable at 4744 // compile time due to StartVal and/or Accum being constants. 4745 // If either one is, then we can check that now and escape if either P2 4746 // or P3 is false. 4747 4748 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4749 // for each of StartVal and Accum 4750 auto getExtendedExpr = [&](const SCEV *Expr, 4751 bool CreateSignExtend) -> const SCEV * { 4752 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4753 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4754 const SCEV *ExtendedExpr = 4755 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4756 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4757 return ExtendedExpr; 4758 }; 4759 4760 // Given: 4761 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4762 // = getExtendedExpr(Expr) 4763 // Determine whether the predicate P: Expr == ExtendedExpr 4764 // is known to be false at compile time 4765 auto PredIsKnownFalse = [&](const SCEV *Expr, 4766 const SCEV *ExtendedExpr) -> bool { 4767 return Expr != ExtendedExpr && 4768 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4769 }; 4770 4771 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4772 if (PredIsKnownFalse(StartVal, StartExtended)) { 4773 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4774 return None; 4775 } 4776 4777 // The Step is always Signed (because the overflow checks are either 4778 // NSSW or NUSW) 4779 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4780 if (PredIsKnownFalse(Accum, AccumExtended)) { 4781 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4782 return None; 4783 } 4784 4785 auto AppendPredicate = [&](const SCEV *Expr, 4786 const SCEV *ExtendedExpr) -> void { 4787 if (Expr != ExtendedExpr && 4788 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4789 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4790 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4791 Predicates.push_back(Pred); 4792 } 4793 }; 4794 4795 AppendPredicate(StartVal, StartExtended); 4796 AppendPredicate(Accum, AccumExtended); 4797 4798 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4799 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4800 // into NewAR if it will also add the runtime overflow checks specified in 4801 // Predicates. 4802 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4803 4804 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4805 std::make_pair(NewAR, Predicates); 4806 // Remember the result of the analysis for this SCEV at this locayyytion. 4807 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4808 return PredRewrite; 4809 } 4810 4811 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4812 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4813 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4814 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4815 if (!L) 4816 return None; 4817 4818 // Check to see if we already analyzed this PHI. 4819 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4820 if (I != PredicatedSCEVRewrites.end()) { 4821 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4822 I->second; 4823 // Analysis was done before and failed to create an AddRec: 4824 if (Rewrite.first == SymbolicPHI) 4825 return None; 4826 // Analysis was done before and succeeded to create an AddRec under 4827 // a predicate: 4828 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4829 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4830 return Rewrite; 4831 } 4832 4833 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4834 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4835 4836 // Record in the cache that the analysis failed 4837 if (!Rewrite) { 4838 SmallVector<const SCEVPredicate *, 3> Predicates; 4839 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4840 return None; 4841 } 4842 4843 return Rewrite; 4844 } 4845 4846 // FIXME: This utility is currently required because the Rewriter currently 4847 // does not rewrite this expression: 4848 // {0, +, (sext ix (trunc iy to ix) to iy)} 4849 // into {0, +, %step}, 4850 // even when the following Equal predicate exists: 4851 // "%step == (sext ix (trunc iy to ix) to iy)". 4852 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4853 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4854 if (AR1 == AR2) 4855 return true; 4856 4857 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4858 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4859 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4860 return false; 4861 return true; 4862 }; 4863 4864 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4865 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4866 return false; 4867 return true; 4868 } 4869 4870 /// A helper function for createAddRecFromPHI to handle simple cases. 4871 /// 4872 /// This function tries to find an AddRec expression for the simplest (yet most 4873 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4874 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4875 /// technique for finding the AddRec expression. 4876 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4877 Value *BEValueV, 4878 Value *StartValueV) { 4879 const Loop *L = LI.getLoopFor(PN->getParent()); 4880 assert(L && L->getHeader() == PN->getParent()); 4881 assert(BEValueV && StartValueV); 4882 4883 auto BO = MatchBinaryOp(BEValueV, DT); 4884 if (!BO) 4885 return nullptr; 4886 4887 if (BO->Opcode != Instruction::Add) 4888 return nullptr; 4889 4890 const SCEV *Accum = nullptr; 4891 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4892 Accum = getSCEV(BO->RHS); 4893 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4894 Accum = getSCEV(BO->LHS); 4895 4896 if (!Accum) 4897 return nullptr; 4898 4899 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4900 if (BO->IsNUW) 4901 Flags = setFlags(Flags, SCEV::FlagNUW); 4902 if (BO->IsNSW) 4903 Flags = setFlags(Flags, SCEV::FlagNSW); 4904 4905 const SCEV *StartVal = getSCEV(StartValueV); 4906 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4907 4908 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4909 4910 // We can add Flags to the post-inc expression only if we 4911 // know that it is *undefined behavior* for BEValueV to 4912 // overflow. 4913 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4914 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4915 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4916 4917 return PHISCEV; 4918 } 4919 4920 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4921 const Loop *L = LI.getLoopFor(PN->getParent()); 4922 if (!L || L->getHeader() != PN->getParent()) 4923 return nullptr; 4924 4925 // The loop may have multiple entrances or multiple exits; we can analyze 4926 // this phi as an addrec if it has a unique entry value and a unique 4927 // backedge value. 4928 Value *BEValueV = nullptr, *StartValueV = nullptr; 4929 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4930 Value *V = PN->getIncomingValue(i); 4931 if (L->contains(PN->getIncomingBlock(i))) { 4932 if (!BEValueV) { 4933 BEValueV = V; 4934 } else if (BEValueV != V) { 4935 BEValueV = nullptr; 4936 break; 4937 } 4938 } else if (!StartValueV) { 4939 StartValueV = V; 4940 } else if (StartValueV != V) { 4941 StartValueV = nullptr; 4942 break; 4943 } 4944 } 4945 if (!BEValueV || !StartValueV) 4946 return nullptr; 4947 4948 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4949 "PHI node already processed?"); 4950 4951 // First, try to find AddRec expression without creating a fictituos symbolic 4952 // value for PN. 4953 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4954 return S; 4955 4956 // Handle PHI node value symbolically. 4957 const SCEV *SymbolicName = getUnknown(PN); 4958 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4959 4960 // Using this symbolic name for the PHI, analyze the value coming around 4961 // the back-edge. 4962 const SCEV *BEValue = getSCEV(BEValueV); 4963 4964 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4965 // has a special value for the first iteration of the loop. 4966 4967 // If the value coming around the backedge is an add with the symbolic 4968 // value we just inserted, then we found a simple induction variable! 4969 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4970 // If there is a single occurrence of the symbolic value, replace it 4971 // with a recurrence. 4972 unsigned FoundIndex = Add->getNumOperands(); 4973 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4974 if (Add->getOperand(i) == SymbolicName) 4975 if (FoundIndex == e) { 4976 FoundIndex = i; 4977 break; 4978 } 4979 4980 if (FoundIndex != Add->getNumOperands()) { 4981 // Create an add with everything but the specified operand. 4982 SmallVector<const SCEV *, 8> Ops; 4983 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4984 if (i != FoundIndex) 4985 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4986 L, *this)); 4987 const SCEV *Accum = getAddExpr(Ops); 4988 4989 // This is not a valid addrec if the step amount is varying each 4990 // loop iteration, but is not itself an addrec in this loop. 4991 if (isLoopInvariant(Accum, L) || 4992 (isa<SCEVAddRecExpr>(Accum) && 4993 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4994 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4995 4996 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4997 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4998 if (BO->IsNUW) 4999 Flags = setFlags(Flags, SCEV::FlagNUW); 5000 if (BO->IsNSW) 5001 Flags = setFlags(Flags, SCEV::FlagNSW); 5002 } 5003 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5004 // If the increment is an inbounds GEP, then we know the address 5005 // space cannot be wrapped around. We cannot make any guarantee 5006 // about signed or unsigned overflow because pointers are 5007 // unsigned but we may have a negative index from the base 5008 // pointer. We can guarantee that no unsigned wrap occurs if the 5009 // indices form a positive value. 5010 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5011 Flags = setFlags(Flags, SCEV::FlagNW); 5012 5013 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5014 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5015 Flags = setFlags(Flags, SCEV::FlagNUW); 5016 } 5017 5018 // We cannot transfer nuw and nsw flags from subtraction 5019 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5020 // for instance. 5021 } 5022 5023 const SCEV *StartVal = getSCEV(StartValueV); 5024 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5025 5026 // Okay, for the entire analysis of this edge we assumed the PHI 5027 // to be symbolic. We now need to go back and purge all of the 5028 // entries for the scalars that use the symbolic expression. 5029 forgetSymbolicName(PN, SymbolicName); 5030 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5031 5032 // We can add Flags to the post-inc expression only if we 5033 // know that it is *undefined behavior* for BEValueV to 5034 // overflow. 5035 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5036 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5037 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5038 5039 return PHISCEV; 5040 } 5041 } 5042 } else { 5043 // Otherwise, this could be a loop like this: 5044 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5045 // In this case, j = {1,+,1} and BEValue is j. 5046 // Because the other in-value of i (0) fits the evolution of BEValue 5047 // i really is an addrec evolution. 5048 // 5049 // We can generalize this saying that i is the shifted value of BEValue 5050 // by one iteration: 5051 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5052 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5053 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5054 if (Shifted != getCouldNotCompute() && 5055 Start != getCouldNotCompute()) { 5056 const SCEV *StartVal = getSCEV(StartValueV); 5057 if (Start == StartVal) { 5058 // Okay, for the entire analysis of this edge we assumed the PHI 5059 // to be symbolic. We now need to go back and purge all of the 5060 // entries for the scalars that use the symbolic expression. 5061 forgetSymbolicName(PN, SymbolicName); 5062 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5063 return Shifted; 5064 } 5065 } 5066 } 5067 5068 // Remove the temporary PHI node SCEV that has been inserted while intending 5069 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5070 // as it will prevent later (possibly simpler) SCEV expressions to be added 5071 // to the ValueExprMap. 5072 eraseValueFromMap(PN); 5073 5074 return nullptr; 5075 } 5076 5077 // Checks if the SCEV S is available at BB. S is considered available at BB 5078 // if S can be materialized at BB without introducing a fault. 5079 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5080 BasicBlock *BB) { 5081 struct CheckAvailable { 5082 bool TraversalDone = false; 5083 bool Available = true; 5084 5085 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5086 BasicBlock *BB = nullptr; 5087 DominatorTree &DT; 5088 5089 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5090 : L(L), BB(BB), DT(DT) {} 5091 5092 bool setUnavailable() { 5093 TraversalDone = true; 5094 Available = false; 5095 return false; 5096 } 5097 5098 bool follow(const SCEV *S) { 5099 switch (S->getSCEVType()) { 5100 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5101 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5102 // These expressions are available if their operand(s) is/are. 5103 return true; 5104 5105 case scAddRecExpr: { 5106 // We allow add recurrences that are on the loop BB is in, or some 5107 // outer loop. This guarantees availability because the value of the 5108 // add recurrence at BB is simply the "current" value of the induction 5109 // variable. We can relax this in the future; for instance an add 5110 // recurrence on a sibling dominating loop is also available at BB. 5111 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5112 if (L && (ARLoop == L || ARLoop->contains(L))) 5113 return true; 5114 5115 return setUnavailable(); 5116 } 5117 5118 case scUnknown: { 5119 // For SCEVUnknown, we check for simple dominance. 5120 const auto *SU = cast<SCEVUnknown>(S); 5121 Value *V = SU->getValue(); 5122 5123 if (isa<Argument>(V)) 5124 return false; 5125 5126 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5127 return false; 5128 5129 return setUnavailable(); 5130 } 5131 5132 case scUDivExpr: 5133 case scCouldNotCompute: 5134 // We do not try to smart about these at all. 5135 return setUnavailable(); 5136 } 5137 llvm_unreachable("switch should be fully covered!"); 5138 } 5139 5140 bool isDone() { return TraversalDone; } 5141 }; 5142 5143 CheckAvailable CA(L, BB, DT); 5144 SCEVTraversal<CheckAvailable> ST(CA); 5145 5146 ST.visitAll(S); 5147 return CA.Available; 5148 } 5149 5150 // Try to match a control flow sequence that branches out at BI and merges back 5151 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5152 // match. 5153 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5154 Value *&C, Value *&LHS, Value *&RHS) { 5155 C = BI->getCondition(); 5156 5157 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5158 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5159 5160 if (!LeftEdge.isSingleEdge()) 5161 return false; 5162 5163 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5164 5165 Use &LeftUse = Merge->getOperandUse(0); 5166 Use &RightUse = Merge->getOperandUse(1); 5167 5168 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5169 LHS = LeftUse; 5170 RHS = RightUse; 5171 return true; 5172 } 5173 5174 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5175 LHS = RightUse; 5176 RHS = LeftUse; 5177 return true; 5178 } 5179 5180 return false; 5181 } 5182 5183 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5184 auto IsReachable = 5185 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5186 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5187 const Loop *L = LI.getLoopFor(PN->getParent()); 5188 5189 // We don't want to break LCSSA, even in a SCEV expression tree. 5190 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5191 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5192 return nullptr; 5193 5194 // Try to match 5195 // 5196 // br %cond, label %left, label %right 5197 // left: 5198 // br label %merge 5199 // right: 5200 // br label %merge 5201 // merge: 5202 // V = phi [ %x, %left ], [ %y, %right ] 5203 // 5204 // as "select %cond, %x, %y" 5205 5206 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5207 assert(IDom && "At least the entry block should dominate PN"); 5208 5209 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5210 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5211 5212 if (BI && BI->isConditional() && 5213 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5214 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5215 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5216 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5217 } 5218 5219 return nullptr; 5220 } 5221 5222 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5223 if (const SCEV *S = createAddRecFromPHI(PN)) 5224 return S; 5225 5226 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5227 return S; 5228 5229 // If the PHI has a single incoming value, follow that value, unless the 5230 // PHI's incoming blocks are in a different loop, in which case doing so 5231 // risks breaking LCSSA form. Instcombine would normally zap these, but 5232 // it doesn't have DominatorTree information, so it may miss cases. 5233 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5234 if (LI.replacementPreservesLCSSAForm(PN, V)) 5235 return getSCEV(V); 5236 5237 // If it's not a loop phi, we can't handle it yet. 5238 return getUnknown(PN); 5239 } 5240 5241 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5242 Value *Cond, 5243 Value *TrueVal, 5244 Value *FalseVal) { 5245 // Handle "constant" branch or select. This can occur for instance when a 5246 // loop pass transforms an inner loop and moves on to process the outer loop. 5247 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5248 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5249 5250 // Try to match some simple smax or umax patterns. 5251 auto *ICI = dyn_cast<ICmpInst>(Cond); 5252 if (!ICI) 5253 return getUnknown(I); 5254 5255 Value *LHS = ICI->getOperand(0); 5256 Value *RHS = ICI->getOperand(1); 5257 5258 switch (ICI->getPredicate()) { 5259 case ICmpInst::ICMP_SLT: 5260 case ICmpInst::ICMP_SLE: 5261 std::swap(LHS, RHS); 5262 LLVM_FALLTHROUGH; 5263 case ICmpInst::ICMP_SGT: 5264 case ICmpInst::ICMP_SGE: 5265 // a >s b ? a+x : b+x -> smax(a, b)+x 5266 // a >s b ? b+x : a+x -> smin(a, b)+x 5267 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5268 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5269 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5270 const SCEV *LA = getSCEV(TrueVal); 5271 const SCEV *RA = getSCEV(FalseVal); 5272 const SCEV *LDiff = getMinusSCEV(LA, LS); 5273 const SCEV *RDiff = getMinusSCEV(RA, RS); 5274 if (LDiff == RDiff) 5275 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5276 LDiff = getMinusSCEV(LA, RS); 5277 RDiff = getMinusSCEV(RA, LS); 5278 if (LDiff == RDiff) 5279 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5280 } 5281 break; 5282 case ICmpInst::ICMP_ULT: 5283 case ICmpInst::ICMP_ULE: 5284 std::swap(LHS, RHS); 5285 LLVM_FALLTHROUGH; 5286 case ICmpInst::ICMP_UGT: 5287 case ICmpInst::ICMP_UGE: 5288 // a >u b ? a+x : b+x -> umax(a, b)+x 5289 // a >u b ? b+x : a+x -> umin(a, b)+x 5290 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5291 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5292 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5293 const SCEV *LA = getSCEV(TrueVal); 5294 const SCEV *RA = getSCEV(FalseVal); 5295 const SCEV *LDiff = getMinusSCEV(LA, LS); 5296 const SCEV *RDiff = getMinusSCEV(RA, RS); 5297 if (LDiff == RDiff) 5298 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5299 LDiff = getMinusSCEV(LA, RS); 5300 RDiff = getMinusSCEV(RA, LS); 5301 if (LDiff == RDiff) 5302 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5303 } 5304 break; 5305 case ICmpInst::ICMP_NE: 5306 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5307 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5308 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5309 const SCEV *One = getOne(I->getType()); 5310 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5311 const SCEV *LA = getSCEV(TrueVal); 5312 const SCEV *RA = getSCEV(FalseVal); 5313 const SCEV *LDiff = getMinusSCEV(LA, LS); 5314 const SCEV *RDiff = getMinusSCEV(RA, One); 5315 if (LDiff == RDiff) 5316 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5317 } 5318 break; 5319 case ICmpInst::ICMP_EQ: 5320 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5321 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5322 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5323 const SCEV *One = getOne(I->getType()); 5324 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5325 const SCEV *LA = getSCEV(TrueVal); 5326 const SCEV *RA = getSCEV(FalseVal); 5327 const SCEV *LDiff = getMinusSCEV(LA, One); 5328 const SCEV *RDiff = getMinusSCEV(RA, LS); 5329 if (LDiff == RDiff) 5330 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5331 } 5332 break; 5333 default: 5334 break; 5335 } 5336 5337 return getUnknown(I); 5338 } 5339 5340 /// Expand GEP instructions into add and multiply operations. This allows them 5341 /// to be analyzed by regular SCEV code. 5342 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5343 // Don't attempt to analyze GEPs over unsized objects. 5344 if (!GEP->getSourceElementType()->isSized()) 5345 return getUnknown(GEP); 5346 5347 SmallVector<const SCEV *, 4> IndexExprs; 5348 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5349 IndexExprs.push_back(getSCEV(*Index)); 5350 return getGEPExpr(GEP, IndexExprs); 5351 } 5352 5353 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5354 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5355 return C->getAPInt().countTrailingZeros(); 5356 5357 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5358 return std::min(GetMinTrailingZeros(T->getOperand()), 5359 (uint32_t)getTypeSizeInBits(T->getType())); 5360 5361 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5362 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5363 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5364 ? getTypeSizeInBits(E->getType()) 5365 : OpRes; 5366 } 5367 5368 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5369 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5370 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5371 ? getTypeSizeInBits(E->getType()) 5372 : OpRes; 5373 } 5374 5375 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5376 // The result is the min of all operands results. 5377 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5378 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5379 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5380 return MinOpRes; 5381 } 5382 5383 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5384 // The result is the sum of all operands results. 5385 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5386 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5387 for (unsigned i = 1, e = M->getNumOperands(); 5388 SumOpRes != BitWidth && i != e; ++i) 5389 SumOpRes = 5390 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5391 return SumOpRes; 5392 } 5393 5394 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5395 // The result is the min of all operands results. 5396 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5397 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5398 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5399 return MinOpRes; 5400 } 5401 5402 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5403 // The result is the min of all operands results. 5404 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5405 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5406 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5407 return MinOpRes; 5408 } 5409 5410 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5411 // The result is the min of all operands results. 5412 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5413 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5414 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5415 return MinOpRes; 5416 } 5417 5418 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5419 // For a SCEVUnknown, ask ValueTracking. 5420 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5421 return Known.countMinTrailingZeros(); 5422 } 5423 5424 // SCEVUDivExpr 5425 return 0; 5426 } 5427 5428 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5429 auto I = MinTrailingZerosCache.find(S); 5430 if (I != MinTrailingZerosCache.end()) 5431 return I->second; 5432 5433 uint32_t Result = GetMinTrailingZerosImpl(S); 5434 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5435 assert(InsertPair.second && "Should insert a new key"); 5436 return InsertPair.first->second; 5437 } 5438 5439 /// Helper method to assign a range to V from metadata present in the IR. 5440 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5441 if (Instruction *I = dyn_cast<Instruction>(V)) 5442 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5443 return getConstantRangeFromMetadata(*MD); 5444 5445 return None; 5446 } 5447 5448 /// Determine the range for a particular SCEV. If SignHint is 5449 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5450 /// with a "cleaner" unsigned (resp. signed) representation. 5451 const ConstantRange & 5452 ScalarEvolution::getRangeRef(const SCEV *S, 5453 ScalarEvolution::RangeSignHint SignHint) { 5454 DenseMap<const SCEV *, ConstantRange> &Cache = 5455 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5456 : SignedRanges; 5457 5458 // See if we've computed this range already. 5459 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5460 if (I != Cache.end()) 5461 return I->second; 5462 5463 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5464 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5465 5466 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5467 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5468 5469 // If the value has known zeros, the maximum value will have those known zeros 5470 // as well. 5471 uint32_t TZ = GetMinTrailingZeros(S); 5472 if (TZ != 0) { 5473 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5474 ConservativeResult = 5475 ConstantRange(APInt::getMinValue(BitWidth), 5476 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5477 else 5478 ConservativeResult = ConstantRange( 5479 APInt::getSignedMinValue(BitWidth), 5480 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5481 } 5482 5483 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5484 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5485 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5486 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5487 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5488 } 5489 5490 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5491 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5492 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5493 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5494 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5495 } 5496 5497 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5498 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5499 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5500 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5501 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5502 } 5503 5504 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5505 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5506 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5507 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5508 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5509 } 5510 5511 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5512 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5513 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5514 return setRange(UDiv, SignHint, 5515 ConservativeResult.intersectWith(X.udiv(Y))); 5516 } 5517 5518 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5519 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5520 return setRange(ZExt, SignHint, 5521 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5522 } 5523 5524 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5525 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5526 return setRange(SExt, SignHint, 5527 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5528 } 5529 5530 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5531 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5532 return setRange(Trunc, SignHint, 5533 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5534 } 5535 5536 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5537 // If there's no unsigned wrap, the value will never be less than its 5538 // initial value. 5539 if (AddRec->hasNoUnsignedWrap()) 5540 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5541 if (!C->getValue()->isZero()) 5542 ConservativeResult = ConservativeResult.intersectWith( 5543 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5544 5545 // If there's no signed wrap, and all the operands have the same sign or 5546 // zero, the value won't ever change sign. 5547 if (AddRec->hasNoSignedWrap()) { 5548 bool AllNonNeg = true; 5549 bool AllNonPos = true; 5550 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5551 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5552 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5553 } 5554 if (AllNonNeg) 5555 ConservativeResult = ConservativeResult.intersectWith( 5556 ConstantRange(APInt(BitWidth, 0), 5557 APInt::getSignedMinValue(BitWidth))); 5558 else if (AllNonPos) 5559 ConservativeResult = ConservativeResult.intersectWith( 5560 ConstantRange(APInt::getSignedMinValue(BitWidth), 5561 APInt(BitWidth, 1))); 5562 } 5563 5564 // TODO: non-affine addrec 5565 if (AddRec->isAffine()) { 5566 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5567 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5568 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5569 auto RangeFromAffine = getRangeForAffineAR( 5570 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5571 BitWidth); 5572 if (!RangeFromAffine.isFullSet()) 5573 ConservativeResult = 5574 ConservativeResult.intersectWith(RangeFromAffine); 5575 5576 auto RangeFromFactoring = getRangeViaFactoring( 5577 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5578 BitWidth); 5579 if (!RangeFromFactoring.isFullSet()) 5580 ConservativeResult = 5581 ConservativeResult.intersectWith(RangeFromFactoring); 5582 } 5583 } 5584 5585 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5586 } 5587 5588 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5589 // Check if the IR explicitly contains !range metadata. 5590 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5591 if (MDRange.hasValue()) 5592 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5593 5594 // Split here to avoid paying the compile-time cost of calling both 5595 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5596 // if needed. 5597 const DataLayout &DL = getDataLayout(); 5598 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5599 // For a SCEVUnknown, ask ValueTracking. 5600 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5601 if (Known.One != ~Known.Zero + 1) 5602 ConservativeResult = 5603 ConservativeResult.intersectWith(ConstantRange(Known.One, 5604 ~Known.Zero + 1)); 5605 } else { 5606 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5607 "generalize as needed!"); 5608 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5609 if (NS > 1) 5610 ConservativeResult = ConservativeResult.intersectWith( 5611 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5612 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5613 } 5614 5615 // A range of Phi is a subset of union of all ranges of its input. 5616 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5617 // Make sure that we do not run over cycled Phis. 5618 if (PendingPhiRanges.insert(Phi).second) { 5619 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5620 for (auto &Op : Phi->operands()) { 5621 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5622 RangeFromOps = RangeFromOps.unionWith(OpRange); 5623 // No point to continue if we already have a full set. 5624 if (RangeFromOps.isFullSet()) 5625 break; 5626 } 5627 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5628 bool Erased = PendingPhiRanges.erase(Phi); 5629 assert(Erased && "Failed to erase Phi properly?"); 5630 (void) Erased; 5631 } 5632 } 5633 5634 return setRange(U, SignHint, std::move(ConservativeResult)); 5635 } 5636 5637 return setRange(S, SignHint, std::move(ConservativeResult)); 5638 } 5639 5640 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5641 // values that the expression can take. Initially, the expression has a value 5642 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5643 // argument defines if we treat Step as signed or unsigned. 5644 static ConstantRange getRangeForAffineARHelper(APInt Step, 5645 const ConstantRange &StartRange, 5646 const APInt &MaxBECount, 5647 unsigned BitWidth, bool Signed) { 5648 // If either Step or MaxBECount is 0, then the expression won't change, and we 5649 // just need to return the initial range. 5650 if (Step == 0 || MaxBECount == 0) 5651 return StartRange; 5652 5653 // If we don't know anything about the initial value (i.e. StartRange is 5654 // FullRange), then we don't know anything about the final range either. 5655 // Return FullRange. 5656 if (StartRange.isFullSet()) 5657 return ConstantRange(BitWidth, /* isFullSet = */ true); 5658 5659 // If Step is signed and negative, then we use its absolute value, but we also 5660 // note that we're moving in the opposite direction. 5661 bool Descending = Signed && Step.isNegative(); 5662 5663 if (Signed) 5664 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5665 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5666 // This equations hold true due to the well-defined wrap-around behavior of 5667 // APInt. 5668 Step = Step.abs(); 5669 5670 // Check if Offset is more than full span of BitWidth. If it is, the 5671 // expression is guaranteed to overflow. 5672 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5673 return ConstantRange(BitWidth, /* isFullSet = */ true); 5674 5675 // Offset is by how much the expression can change. Checks above guarantee no 5676 // overflow here. 5677 APInt Offset = Step * MaxBECount; 5678 5679 // Minimum value of the final range will match the minimal value of StartRange 5680 // if the expression is increasing and will be decreased by Offset otherwise. 5681 // Maximum value of the final range will match the maximal value of StartRange 5682 // if the expression is decreasing and will be increased by Offset otherwise. 5683 APInt StartLower = StartRange.getLower(); 5684 APInt StartUpper = StartRange.getUpper() - 1; 5685 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5686 : (StartUpper + std::move(Offset)); 5687 5688 // It's possible that the new minimum/maximum value will fall into the initial 5689 // range (due to wrap around). This means that the expression can take any 5690 // value in this bitwidth, and we have to return full range. 5691 if (StartRange.contains(MovedBoundary)) 5692 return ConstantRange(BitWidth, /* isFullSet = */ true); 5693 5694 APInt NewLower = 5695 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5696 APInt NewUpper = 5697 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5698 NewUpper += 1; 5699 5700 // If we end up with full range, return a proper full range. 5701 if (NewLower == NewUpper) 5702 return ConstantRange(BitWidth, /* isFullSet = */ true); 5703 5704 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5705 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5706 } 5707 5708 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5709 const SCEV *Step, 5710 const SCEV *MaxBECount, 5711 unsigned BitWidth) { 5712 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5713 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5714 "Precondition!"); 5715 5716 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5717 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5718 5719 // First, consider step signed. 5720 ConstantRange StartSRange = getSignedRange(Start); 5721 ConstantRange StepSRange = getSignedRange(Step); 5722 5723 // If Step can be both positive and negative, we need to find ranges for the 5724 // maximum absolute step values in both directions and union them. 5725 ConstantRange SR = 5726 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5727 MaxBECountValue, BitWidth, /* Signed = */ true); 5728 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5729 StartSRange, MaxBECountValue, 5730 BitWidth, /* Signed = */ true)); 5731 5732 // Next, consider step unsigned. 5733 ConstantRange UR = getRangeForAffineARHelper( 5734 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5735 MaxBECountValue, BitWidth, /* Signed = */ false); 5736 5737 // Finally, intersect signed and unsigned ranges. 5738 return SR.intersectWith(UR); 5739 } 5740 5741 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5742 const SCEV *Step, 5743 const SCEV *MaxBECount, 5744 unsigned BitWidth) { 5745 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5746 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5747 5748 struct SelectPattern { 5749 Value *Condition = nullptr; 5750 APInt TrueValue; 5751 APInt FalseValue; 5752 5753 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5754 const SCEV *S) { 5755 Optional<unsigned> CastOp; 5756 APInt Offset(BitWidth, 0); 5757 5758 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5759 "Should be!"); 5760 5761 // Peel off a constant offset: 5762 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5763 // In the future we could consider being smarter here and handle 5764 // {Start+Step,+,Step} too. 5765 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5766 return; 5767 5768 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5769 S = SA->getOperand(1); 5770 } 5771 5772 // Peel off a cast operation 5773 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5774 CastOp = SCast->getSCEVType(); 5775 S = SCast->getOperand(); 5776 } 5777 5778 using namespace llvm::PatternMatch; 5779 5780 auto *SU = dyn_cast<SCEVUnknown>(S); 5781 const APInt *TrueVal, *FalseVal; 5782 if (!SU || 5783 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5784 m_APInt(FalseVal)))) { 5785 Condition = nullptr; 5786 return; 5787 } 5788 5789 TrueValue = *TrueVal; 5790 FalseValue = *FalseVal; 5791 5792 // Re-apply the cast we peeled off earlier 5793 if (CastOp.hasValue()) 5794 switch (*CastOp) { 5795 default: 5796 llvm_unreachable("Unknown SCEV cast type!"); 5797 5798 case scTruncate: 5799 TrueValue = TrueValue.trunc(BitWidth); 5800 FalseValue = FalseValue.trunc(BitWidth); 5801 break; 5802 case scZeroExtend: 5803 TrueValue = TrueValue.zext(BitWidth); 5804 FalseValue = FalseValue.zext(BitWidth); 5805 break; 5806 case scSignExtend: 5807 TrueValue = TrueValue.sext(BitWidth); 5808 FalseValue = FalseValue.sext(BitWidth); 5809 break; 5810 } 5811 5812 // Re-apply the constant offset we peeled off earlier 5813 TrueValue += Offset; 5814 FalseValue += Offset; 5815 } 5816 5817 bool isRecognized() { return Condition != nullptr; } 5818 }; 5819 5820 SelectPattern StartPattern(*this, BitWidth, Start); 5821 if (!StartPattern.isRecognized()) 5822 return ConstantRange(BitWidth, /* isFullSet = */ true); 5823 5824 SelectPattern StepPattern(*this, BitWidth, Step); 5825 if (!StepPattern.isRecognized()) 5826 return ConstantRange(BitWidth, /* isFullSet = */ true); 5827 5828 if (StartPattern.Condition != StepPattern.Condition) { 5829 // We don't handle this case today; but we could, by considering four 5830 // possibilities below instead of two. I'm not sure if there are cases where 5831 // that will help over what getRange already does, though. 5832 return ConstantRange(BitWidth, /* isFullSet = */ true); 5833 } 5834 5835 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5836 // construct arbitrary general SCEV expressions here. This function is called 5837 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5838 // say) can end up caching a suboptimal value. 5839 5840 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5841 // C2352 and C2512 (otherwise it isn't needed). 5842 5843 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5844 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5845 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5846 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5847 5848 ConstantRange TrueRange = 5849 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5850 ConstantRange FalseRange = 5851 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5852 5853 return TrueRange.unionWith(FalseRange); 5854 } 5855 5856 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5857 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5858 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5859 5860 // Return early if there are no flags to propagate to the SCEV. 5861 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5862 if (BinOp->hasNoUnsignedWrap()) 5863 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5864 if (BinOp->hasNoSignedWrap()) 5865 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5866 if (Flags == SCEV::FlagAnyWrap) 5867 return SCEV::FlagAnyWrap; 5868 5869 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5870 } 5871 5872 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5873 // Here we check that I is in the header of the innermost loop containing I, 5874 // since we only deal with instructions in the loop header. The actual loop we 5875 // need to check later will come from an add recurrence, but getting that 5876 // requires computing the SCEV of the operands, which can be expensive. This 5877 // check we can do cheaply to rule out some cases early. 5878 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5879 if (InnermostContainingLoop == nullptr || 5880 InnermostContainingLoop->getHeader() != I->getParent()) 5881 return false; 5882 5883 // Only proceed if we can prove that I does not yield poison. 5884 if (!programUndefinedIfFullPoison(I)) 5885 return false; 5886 5887 // At this point we know that if I is executed, then it does not wrap 5888 // according to at least one of NSW or NUW. If I is not executed, then we do 5889 // not know if the calculation that I represents would wrap. Multiple 5890 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5891 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5892 // derived from other instructions that map to the same SCEV. We cannot make 5893 // that guarantee for cases where I is not executed. So we need to find the 5894 // loop that I is considered in relation to and prove that I is executed for 5895 // every iteration of that loop. That implies that the value that I 5896 // calculates does not wrap anywhere in the loop, so then we can apply the 5897 // flags to the SCEV. 5898 // 5899 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5900 // from different loops, so that we know which loop to prove that I is 5901 // executed in. 5902 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5903 // I could be an extractvalue from a call to an overflow intrinsic. 5904 // TODO: We can do better here in some cases. 5905 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5906 return false; 5907 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5908 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5909 bool AllOtherOpsLoopInvariant = true; 5910 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5911 ++OtherOpIndex) { 5912 if (OtherOpIndex != OpIndex) { 5913 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5914 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5915 AllOtherOpsLoopInvariant = false; 5916 break; 5917 } 5918 } 5919 } 5920 if (AllOtherOpsLoopInvariant && 5921 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5922 return true; 5923 } 5924 } 5925 return false; 5926 } 5927 5928 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5929 // If we know that \c I can never be poison period, then that's enough. 5930 if (isSCEVExprNeverPoison(I)) 5931 return true; 5932 5933 // For an add recurrence specifically, we assume that infinite loops without 5934 // side effects are undefined behavior, and then reason as follows: 5935 // 5936 // If the add recurrence is poison in any iteration, it is poison on all 5937 // future iterations (since incrementing poison yields poison). If the result 5938 // of the add recurrence is fed into the loop latch condition and the loop 5939 // does not contain any throws or exiting blocks other than the latch, we now 5940 // have the ability to "choose" whether the backedge is taken or not (by 5941 // choosing a sufficiently evil value for the poison feeding into the branch) 5942 // for every iteration including and after the one in which \p I first became 5943 // poison. There are two possibilities (let's call the iteration in which \p 5944 // I first became poison as K): 5945 // 5946 // 1. In the set of iterations including and after K, the loop body executes 5947 // no side effects. In this case executing the backege an infinte number 5948 // of times will yield undefined behavior. 5949 // 5950 // 2. In the set of iterations including and after K, the loop body executes 5951 // at least one side effect. In this case, that specific instance of side 5952 // effect is control dependent on poison, which also yields undefined 5953 // behavior. 5954 5955 auto *ExitingBB = L->getExitingBlock(); 5956 auto *LatchBB = L->getLoopLatch(); 5957 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5958 return false; 5959 5960 SmallPtrSet<const Instruction *, 16> Pushed; 5961 SmallVector<const Instruction *, 8> PoisonStack; 5962 5963 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5964 // things that are known to be fully poison under that assumption go on the 5965 // PoisonStack. 5966 Pushed.insert(I); 5967 PoisonStack.push_back(I); 5968 5969 bool LatchControlDependentOnPoison = false; 5970 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5971 const Instruction *Poison = PoisonStack.pop_back_val(); 5972 5973 for (auto *PoisonUser : Poison->users()) { 5974 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5975 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5976 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5977 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5978 assert(BI->isConditional() && "Only possibility!"); 5979 if (BI->getParent() == LatchBB) { 5980 LatchControlDependentOnPoison = true; 5981 break; 5982 } 5983 } 5984 } 5985 } 5986 5987 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5988 } 5989 5990 ScalarEvolution::LoopProperties 5991 ScalarEvolution::getLoopProperties(const Loop *L) { 5992 using LoopProperties = ScalarEvolution::LoopProperties; 5993 5994 auto Itr = LoopPropertiesCache.find(L); 5995 if (Itr == LoopPropertiesCache.end()) { 5996 auto HasSideEffects = [](Instruction *I) { 5997 if (auto *SI = dyn_cast<StoreInst>(I)) 5998 return !SI->isSimple(); 5999 6000 return I->mayHaveSideEffects(); 6001 }; 6002 6003 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6004 /*HasNoSideEffects*/ true}; 6005 6006 for (auto *BB : L->getBlocks()) 6007 for (auto &I : *BB) { 6008 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6009 LP.HasNoAbnormalExits = false; 6010 if (HasSideEffects(&I)) 6011 LP.HasNoSideEffects = false; 6012 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6013 break; // We're already as pessimistic as we can get. 6014 } 6015 6016 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6017 assert(InsertPair.second && "We just checked!"); 6018 Itr = InsertPair.first; 6019 } 6020 6021 return Itr->second; 6022 } 6023 6024 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6025 if (!isSCEVable(V->getType())) 6026 return getUnknown(V); 6027 6028 if (Instruction *I = dyn_cast<Instruction>(V)) { 6029 // Don't attempt to analyze instructions in blocks that aren't 6030 // reachable. Such instructions don't matter, and they aren't required 6031 // to obey basic rules for definitions dominating uses which this 6032 // analysis depends on. 6033 if (!DT.isReachableFromEntry(I->getParent())) 6034 return getUnknown(V); 6035 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6036 return getConstant(CI); 6037 else if (isa<ConstantPointerNull>(V)) 6038 return getZero(V->getType()); 6039 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6040 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6041 else if (!isa<ConstantExpr>(V)) 6042 return getUnknown(V); 6043 6044 Operator *U = cast<Operator>(V); 6045 if (auto BO = MatchBinaryOp(U, DT)) { 6046 switch (BO->Opcode) { 6047 case Instruction::Add: { 6048 // The simple thing to do would be to just call getSCEV on both operands 6049 // and call getAddExpr with the result. However if we're looking at a 6050 // bunch of things all added together, this can be quite inefficient, 6051 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6052 // Instead, gather up all the operands and make a single getAddExpr call. 6053 // LLVM IR canonical form means we need only traverse the left operands. 6054 SmallVector<const SCEV *, 4> AddOps; 6055 do { 6056 if (BO->Op) { 6057 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6058 AddOps.push_back(OpSCEV); 6059 break; 6060 } 6061 6062 // If a NUW or NSW flag can be applied to the SCEV for this 6063 // addition, then compute the SCEV for this addition by itself 6064 // with a separate call to getAddExpr. We need to do that 6065 // instead of pushing the operands of the addition onto AddOps, 6066 // since the flags are only known to apply to this particular 6067 // addition - they may not apply to other additions that can be 6068 // formed with operands from AddOps. 6069 const SCEV *RHS = getSCEV(BO->RHS); 6070 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6071 if (Flags != SCEV::FlagAnyWrap) { 6072 const SCEV *LHS = getSCEV(BO->LHS); 6073 if (BO->Opcode == Instruction::Sub) 6074 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6075 else 6076 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6077 break; 6078 } 6079 } 6080 6081 if (BO->Opcode == Instruction::Sub) 6082 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6083 else 6084 AddOps.push_back(getSCEV(BO->RHS)); 6085 6086 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6087 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6088 NewBO->Opcode != Instruction::Sub)) { 6089 AddOps.push_back(getSCEV(BO->LHS)); 6090 break; 6091 } 6092 BO = NewBO; 6093 } while (true); 6094 6095 return getAddExpr(AddOps); 6096 } 6097 6098 case Instruction::Mul: { 6099 SmallVector<const SCEV *, 4> MulOps; 6100 do { 6101 if (BO->Op) { 6102 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6103 MulOps.push_back(OpSCEV); 6104 break; 6105 } 6106 6107 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6108 if (Flags != SCEV::FlagAnyWrap) { 6109 MulOps.push_back( 6110 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6111 break; 6112 } 6113 } 6114 6115 MulOps.push_back(getSCEV(BO->RHS)); 6116 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6117 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6118 MulOps.push_back(getSCEV(BO->LHS)); 6119 break; 6120 } 6121 BO = NewBO; 6122 } while (true); 6123 6124 return getMulExpr(MulOps); 6125 } 6126 case Instruction::UDiv: 6127 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6128 case Instruction::URem: 6129 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6130 case Instruction::Sub: { 6131 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6132 if (BO->Op) 6133 Flags = getNoWrapFlagsFromUB(BO->Op); 6134 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6135 } 6136 case Instruction::And: 6137 // For an expression like x&255 that merely masks off the high bits, 6138 // use zext(trunc(x)) as the SCEV expression. 6139 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6140 if (CI->isZero()) 6141 return getSCEV(BO->RHS); 6142 if (CI->isMinusOne()) 6143 return getSCEV(BO->LHS); 6144 const APInt &A = CI->getValue(); 6145 6146 // Instcombine's ShrinkDemandedConstant may strip bits out of 6147 // constants, obscuring what would otherwise be a low-bits mask. 6148 // Use computeKnownBits to compute what ShrinkDemandedConstant 6149 // knew about to reconstruct a low-bits mask value. 6150 unsigned LZ = A.countLeadingZeros(); 6151 unsigned TZ = A.countTrailingZeros(); 6152 unsigned BitWidth = A.getBitWidth(); 6153 KnownBits Known(BitWidth); 6154 computeKnownBits(BO->LHS, Known, getDataLayout(), 6155 0, &AC, nullptr, &DT); 6156 6157 APInt EffectiveMask = 6158 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6159 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6160 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6161 const SCEV *LHS = getSCEV(BO->LHS); 6162 const SCEV *ShiftedLHS = nullptr; 6163 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6164 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6165 // For an expression like (x * 8) & 8, simplify the multiply. 6166 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6167 unsigned GCD = std::min(MulZeros, TZ); 6168 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6169 SmallVector<const SCEV*, 4> MulOps; 6170 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6171 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6172 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6173 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6174 } 6175 } 6176 if (!ShiftedLHS) 6177 ShiftedLHS = getUDivExpr(LHS, MulCount); 6178 return getMulExpr( 6179 getZeroExtendExpr( 6180 getTruncateExpr(ShiftedLHS, 6181 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6182 BO->LHS->getType()), 6183 MulCount); 6184 } 6185 } 6186 break; 6187 6188 case Instruction::Or: 6189 // If the RHS of the Or is a constant, we may have something like: 6190 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6191 // optimizations will transparently handle this case. 6192 // 6193 // In order for this transformation to be safe, the LHS must be of the 6194 // form X*(2^n) and the Or constant must be less than 2^n. 6195 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6196 const SCEV *LHS = getSCEV(BO->LHS); 6197 const APInt &CIVal = CI->getValue(); 6198 if (GetMinTrailingZeros(LHS) >= 6199 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6200 // Build a plain add SCEV. 6201 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6202 // If the LHS of the add was an addrec and it has no-wrap flags, 6203 // transfer the no-wrap flags, since an or won't introduce a wrap. 6204 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6205 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6206 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6207 OldAR->getNoWrapFlags()); 6208 } 6209 return S; 6210 } 6211 } 6212 break; 6213 6214 case Instruction::Xor: 6215 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6216 // If the RHS of xor is -1, then this is a not operation. 6217 if (CI->isMinusOne()) 6218 return getNotSCEV(getSCEV(BO->LHS)); 6219 6220 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6221 // This is a variant of the check for xor with -1, and it handles 6222 // the case where instcombine has trimmed non-demanded bits out 6223 // of an xor with -1. 6224 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6225 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6226 if (LBO->getOpcode() == Instruction::And && 6227 LCI->getValue() == CI->getValue()) 6228 if (const SCEVZeroExtendExpr *Z = 6229 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6230 Type *UTy = BO->LHS->getType(); 6231 const SCEV *Z0 = Z->getOperand(); 6232 Type *Z0Ty = Z0->getType(); 6233 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6234 6235 // If C is a low-bits mask, the zero extend is serving to 6236 // mask off the high bits. Complement the operand and 6237 // re-apply the zext. 6238 if (CI->getValue().isMask(Z0TySize)) 6239 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6240 6241 // If C is a single bit, it may be in the sign-bit position 6242 // before the zero-extend. In this case, represent the xor 6243 // using an add, which is equivalent, and re-apply the zext. 6244 APInt Trunc = CI->getValue().trunc(Z0TySize); 6245 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6246 Trunc.isSignMask()) 6247 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6248 UTy); 6249 } 6250 } 6251 break; 6252 6253 case Instruction::Shl: 6254 // Turn shift left of a constant amount into a multiply. 6255 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6256 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6257 6258 // If the shift count is not less than the bitwidth, the result of 6259 // the shift is undefined. Don't try to analyze it, because the 6260 // resolution chosen here may differ from the resolution chosen in 6261 // other parts of the compiler. 6262 if (SA->getValue().uge(BitWidth)) 6263 break; 6264 6265 // It is currently not resolved how to interpret NSW for left 6266 // shift by BitWidth - 1, so we avoid applying flags in that 6267 // case. Remove this check (or this comment) once the situation 6268 // is resolved. See 6269 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6270 // and http://reviews.llvm.org/D8890 . 6271 auto Flags = SCEV::FlagAnyWrap; 6272 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6273 Flags = getNoWrapFlagsFromUB(BO->Op); 6274 6275 Constant *X = ConstantInt::get( 6276 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6277 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6278 } 6279 break; 6280 6281 case Instruction::AShr: { 6282 // AShr X, C, where C is a constant. 6283 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6284 if (!CI) 6285 break; 6286 6287 Type *OuterTy = BO->LHS->getType(); 6288 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6289 // If the shift count is not less than the bitwidth, the result of 6290 // the shift is undefined. Don't try to analyze it, because the 6291 // resolution chosen here may differ from the resolution chosen in 6292 // other parts of the compiler. 6293 if (CI->getValue().uge(BitWidth)) 6294 break; 6295 6296 if (CI->isZero()) 6297 return getSCEV(BO->LHS); // shift by zero --> noop 6298 6299 uint64_t AShrAmt = CI->getZExtValue(); 6300 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6301 6302 Operator *L = dyn_cast<Operator>(BO->LHS); 6303 if (L && L->getOpcode() == Instruction::Shl) { 6304 // X = Shl A, n 6305 // Y = AShr X, m 6306 // Both n and m are constant. 6307 6308 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6309 if (L->getOperand(1) == BO->RHS) 6310 // For a two-shift sext-inreg, i.e. n = m, 6311 // use sext(trunc(x)) as the SCEV expression. 6312 return getSignExtendExpr( 6313 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6314 6315 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6316 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6317 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6318 if (ShlAmt > AShrAmt) { 6319 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6320 // expression. We already checked that ShlAmt < BitWidth, so 6321 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6322 // ShlAmt - AShrAmt < Amt. 6323 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6324 ShlAmt - AShrAmt); 6325 return getSignExtendExpr( 6326 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6327 getConstant(Mul)), OuterTy); 6328 } 6329 } 6330 } 6331 break; 6332 } 6333 } 6334 } 6335 6336 switch (U->getOpcode()) { 6337 case Instruction::Trunc: 6338 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6339 6340 case Instruction::ZExt: 6341 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6342 6343 case Instruction::SExt: 6344 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6345 // The NSW flag of a subtract does not always survive the conversion to 6346 // A + (-1)*B. By pushing sign extension onto its operands we are much 6347 // more likely to preserve NSW and allow later AddRec optimisations. 6348 // 6349 // NOTE: This is effectively duplicating this logic from getSignExtend: 6350 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6351 // but by that point the NSW information has potentially been lost. 6352 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6353 Type *Ty = U->getType(); 6354 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6355 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6356 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6357 } 6358 } 6359 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6360 6361 case Instruction::BitCast: 6362 // BitCasts are no-op casts so we just eliminate the cast. 6363 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6364 return getSCEV(U->getOperand(0)); 6365 break; 6366 6367 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6368 // lead to pointer expressions which cannot safely be expanded to GEPs, 6369 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6370 // simplifying integer expressions. 6371 6372 case Instruction::GetElementPtr: 6373 return createNodeForGEP(cast<GEPOperator>(U)); 6374 6375 case Instruction::PHI: 6376 return createNodeForPHI(cast<PHINode>(U)); 6377 6378 case Instruction::Select: 6379 // U can also be a select constant expr, which let fall through. Since 6380 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6381 // constant expressions cannot have instructions as operands, we'd have 6382 // returned getUnknown for a select constant expressions anyway. 6383 if (isa<Instruction>(U)) 6384 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6385 U->getOperand(1), U->getOperand(2)); 6386 break; 6387 6388 case Instruction::Call: 6389 case Instruction::Invoke: 6390 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6391 return getSCEV(RV); 6392 break; 6393 } 6394 6395 return getUnknown(V); 6396 } 6397 6398 //===----------------------------------------------------------------------===// 6399 // Iteration Count Computation Code 6400 // 6401 6402 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6403 if (!ExitCount) 6404 return 0; 6405 6406 ConstantInt *ExitConst = ExitCount->getValue(); 6407 6408 // Guard against huge trip counts. 6409 if (ExitConst->getValue().getActiveBits() > 32) 6410 return 0; 6411 6412 // In case of integer overflow, this returns 0, which is correct. 6413 return ((unsigned)ExitConst->getZExtValue()) + 1; 6414 } 6415 6416 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6417 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6418 return getSmallConstantTripCount(L, ExitingBB); 6419 6420 // No trip count information for multiple exits. 6421 return 0; 6422 } 6423 6424 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6425 BasicBlock *ExitingBlock) { 6426 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6427 assert(L->isLoopExiting(ExitingBlock) && 6428 "Exiting block must actually branch out of the loop!"); 6429 const SCEVConstant *ExitCount = 6430 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6431 return getConstantTripCount(ExitCount); 6432 } 6433 6434 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6435 const auto *MaxExitCount = 6436 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6437 return getConstantTripCount(MaxExitCount); 6438 } 6439 6440 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6441 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6442 return getSmallConstantTripMultiple(L, ExitingBB); 6443 6444 // No trip multiple information for multiple exits. 6445 return 0; 6446 } 6447 6448 /// Returns the largest constant divisor of the trip count of this loop as a 6449 /// normal unsigned value, if possible. This means that the actual trip count is 6450 /// always a multiple of the returned value (don't forget the trip count could 6451 /// very well be zero as well!). 6452 /// 6453 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6454 /// multiple of a constant (which is also the case if the trip count is simply 6455 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6456 /// if the trip count is very large (>= 2^32). 6457 /// 6458 /// As explained in the comments for getSmallConstantTripCount, this assumes 6459 /// that control exits the loop via ExitingBlock. 6460 unsigned 6461 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6462 BasicBlock *ExitingBlock) { 6463 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6464 assert(L->isLoopExiting(ExitingBlock) && 6465 "Exiting block must actually branch out of the loop!"); 6466 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6467 if (ExitCount == getCouldNotCompute()) 6468 return 1; 6469 6470 // Get the trip count from the BE count by adding 1. 6471 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6472 6473 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6474 if (!TC) 6475 // Attempt to factor more general cases. Returns the greatest power of 6476 // two divisor. If overflow happens, the trip count expression is still 6477 // divisible by the greatest power of 2 divisor returned. 6478 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6479 6480 ConstantInt *Result = TC->getValue(); 6481 6482 // Guard against huge trip counts (this requires checking 6483 // for zero to handle the case where the trip count == -1 and the 6484 // addition wraps). 6485 if (!Result || Result->getValue().getActiveBits() > 32 || 6486 Result->getValue().getActiveBits() == 0) 6487 return 1; 6488 6489 return (unsigned)Result->getZExtValue(); 6490 } 6491 6492 /// Get the expression for the number of loop iterations for which this loop is 6493 /// guaranteed not to exit via ExitingBlock. Otherwise return 6494 /// SCEVCouldNotCompute. 6495 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6496 BasicBlock *ExitingBlock) { 6497 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6498 } 6499 6500 const SCEV * 6501 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6502 SCEVUnionPredicate &Preds) { 6503 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6504 } 6505 6506 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6507 return getBackedgeTakenInfo(L).getExact(L, this); 6508 } 6509 6510 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6511 /// known never to be less than the actual backedge taken count. 6512 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6513 return getBackedgeTakenInfo(L).getMax(this); 6514 } 6515 6516 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6517 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6518 } 6519 6520 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6521 static void 6522 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6523 BasicBlock *Header = L->getHeader(); 6524 6525 // Push all Loop-header PHIs onto the Worklist stack. 6526 for (PHINode &PN : Header->phis()) 6527 Worklist.push_back(&PN); 6528 } 6529 6530 const ScalarEvolution::BackedgeTakenInfo & 6531 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6532 auto &BTI = getBackedgeTakenInfo(L); 6533 if (BTI.hasFullInfo()) 6534 return BTI; 6535 6536 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6537 6538 if (!Pair.second) 6539 return Pair.first->second; 6540 6541 BackedgeTakenInfo Result = 6542 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6543 6544 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6545 } 6546 6547 const ScalarEvolution::BackedgeTakenInfo & 6548 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6549 // Initially insert an invalid entry for this loop. If the insertion 6550 // succeeds, proceed to actually compute a backedge-taken count and 6551 // update the value. The temporary CouldNotCompute value tells SCEV 6552 // code elsewhere that it shouldn't attempt to request a new 6553 // backedge-taken count, which could result in infinite recursion. 6554 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6555 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6556 if (!Pair.second) 6557 return Pair.first->second; 6558 6559 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6560 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6561 // must be cleared in this scope. 6562 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6563 6564 // In product build, there are no usage of statistic. 6565 (void)NumTripCountsComputed; 6566 (void)NumTripCountsNotComputed; 6567 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6568 const SCEV *BEExact = Result.getExact(L, this); 6569 if (BEExact != getCouldNotCompute()) { 6570 assert(isLoopInvariant(BEExact, L) && 6571 isLoopInvariant(Result.getMax(this), L) && 6572 "Computed backedge-taken count isn't loop invariant for loop!"); 6573 ++NumTripCountsComputed; 6574 } 6575 else if (Result.getMax(this) == getCouldNotCompute() && 6576 isa<PHINode>(L->getHeader()->begin())) { 6577 // Only count loops that have phi nodes as not being computable. 6578 ++NumTripCountsNotComputed; 6579 } 6580 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6581 6582 // Now that we know more about the trip count for this loop, forget any 6583 // existing SCEV values for PHI nodes in this loop since they are only 6584 // conservative estimates made without the benefit of trip count 6585 // information. This is similar to the code in forgetLoop, except that 6586 // it handles SCEVUnknown PHI nodes specially. 6587 if (Result.hasAnyInfo()) { 6588 SmallVector<Instruction *, 16> Worklist; 6589 PushLoopPHIs(L, Worklist); 6590 6591 SmallPtrSet<Instruction *, 8> Discovered; 6592 while (!Worklist.empty()) { 6593 Instruction *I = Worklist.pop_back_val(); 6594 6595 ValueExprMapType::iterator It = 6596 ValueExprMap.find_as(static_cast<Value *>(I)); 6597 if (It != ValueExprMap.end()) { 6598 const SCEV *Old = It->second; 6599 6600 // SCEVUnknown for a PHI either means that it has an unrecognized 6601 // structure, or it's a PHI that's in the progress of being computed 6602 // by createNodeForPHI. In the former case, additional loop trip 6603 // count information isn't going to change anything. In the later 6604 // case, createNodeForPHI will perform the necessary updates on its 6605 // own when it gets to that point. 6606 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6607 eraseValueFromMap(It->first); 6608 forgetMemoizedResults(Old); 6609 } 6610 if (PHINode *PN = dyn_cast<PHINode>(I)) 6611 ConstantEvolutionLoopExitValue.erase(PN); 6612 } 6613 6614 // Since we don't need to invalidate anything for correctness and we're 6615 // only invalidating to make SCEV's results more precise, we get to stop 6616 // early to avoid invalidating too much. This is especially important in 6617 // cases like: 6618 // 6619 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6620 // loop0: 6621 // %pn0 = phi 6622 // ... 6623 // loop1: 6624 // %pn1 = phi 6625 // ... 6626 // 6627 // where both loop0 and loop1's backedge taken count uses the SCEV 6628 // expression for %v. If we don't have the early stop below then in cases 6629 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6630 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6631 // count for loop1, effectively nullifying SCEV's trip count cache. 6632 for (auto *U : I->users()) 6633 if (auto *I = dyn_cast<Instruction>(U)) { 6634 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6635 if (LoopForUser && L->contains(LoopForUser) && 6636 Discovered.insert(I).second) 6637 Worklist.push_back(I); 6638 } 6639 } 6640 } 6641 6642 // Re-lookup the insert position, since the call to 6643 // computeBackedgeTakenCount above could result in a 6644 // recusive call to getBackedgeTakenInfo (on a different 6645 // loop), which would invalidate the iterator computed 6646 // earlier. 6647 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6648 } 6649 6650 void ScalarEvolution::forgetLoop(const Loop *L) { 6651 // Drop any stored trip count value. 6652 auto RemoveLoopFromBackedgeMap = 6653 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6654 auto BTCPos = Map.find(L); 6655 if (BTCPos != Map.end()) { 6656 BTCPos->second.clear(); 6657 Map.erase(BTCPos); 6658 } 6659 }; 6660 6661 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6662 SmallVector<Instruction *, 32> Worklist; 6663 SmallPtrSet<Instruction *, 16> Visited; 6664 6665 // Iterate over all the loops and sub-loops to drop SCEV information. 6666 while (!LoopWorklist.empty()) { 6667 auto *CurrL = LoopWorklist.pop_back_val(); 6668 6669 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6670 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6671 6672 // Drop information about predicated SCEV rewrites for this loop. 6673 for (auto I = PredicatedSCEVRewrites.begin(); 6674 I != PredicatedSCEVRewrites.end();) { 6675 std::pair<const SCEV *, const Loop *> Entry = I->first; 6676 if (Entry.second == CurrL) 6677 PredicatedSCEVRewrites.erase(I++); 6678 else 6679 ++I; 6680 } 6681 6682 auto LoopUsersItr = LoopUsers.find(CurrL); 6683 if (LoopUsersItr != LoopUsers.end()) { 6684 for (auto *S : LoopUsersItr->second) 6685 forgetMemoizedResults(S); 6686 LoopUsers.erase(LoopUsersItr); 6687 } 6688 6689 // Drop information about expressions based on loop-header PHIs. 6690 PushLoopPHIs(CurrL, Worklist); 6691 6692 while (!Worklist.empty()) { 6693 Instruction *I = Worklist.pop_back_val(); 6694 if (!Visited.insert(I).second) 6695 continue; 6696 6697 ValueExprMapType::iterator It = 6698 ValueExprMap.find_as(static_cast<Value *>(I)); 6699 if (It != ValueExprMap.end()) { 6700 eraseValueFromMap(It->first); 6701 forgetMemoizedResults(It->second); 6702 if (PHINode *PN = dyn_cast<PHINode>(I)) 6703 ConstantEvolutionLoopExitValue.erase(PN); 6704 } 6705 6706 PushDefUseChildren(I, Worklist); 6707 } 6708 6709 LoopPropertiesCache.erase(CurrL); 6710 // Forget all contained loops too, to avoid dangling entries in the 6711 // ValuesAtScopes map. 6712 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6713 } 6714 } 6715 6716 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6717 while (Loop *Parent = L->getParentLoop()) 6718 L = Parent; 6719 forgetLoop(L); 6720 } 6721 6722 void ScalarEvolution::forgetValue(Value *V) { 6723 Instruction *I = dyn_cast<Instruction>(V); 6724 if (!I) return; 6725 6726 // Drop information about expressions based on loop-header PHIs. 6727 SmallVector<Instruction *, 16> Worklist; 6728 Worklist.push_back(I); 6729 6730 SmallPtrSet<Instruction *, 8> Visited; 6731 while (!Worklist.empty()) { 6732 I = Worklist.pop_back_val(); 6733 if (!Visited.insert(I).second) 6734 continue; 6735 6736 ValueExprMapType::iterator It = 6737 ValueExprMap.find_as(static_cast<Value *>(I)); 6738 if (It != ValueExprMap.end()) { 6739 eraseValueFromMap(It->first); 6740 forgetMemoizedResults(It->second); 6741 if (PHINode *PN = dyn_cast<PHINode>(I)) 6742 ConstantEvolutionLoopExitValue.erase(PN); 6743 } 6744 6745 PushDefUseChildren(I, Worklist); 6746 } 6747 } 6748 6749 /// Get the exact loop backedge taken count considering all loop exits. A 6750 /// computable result can only be returned for loops with all exiting blocks 6751 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6752 /// is never skipped. This is a valid assumption as long as the loop exits via 6753 /// that test. For precise results, it is the caller's responsibility to specify 6754 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6755 const SCEV * 6756 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6757 SCEVUnionPredicate *Preds) const { 6758 // If any exits were not computable, the loop is not computable. 6759 if (!isComplete() || ExitNotTaken.empty()) 6760 return SE->getCouldNotCompute(); 6761 6762 const BasicBlock *Latch = L->getLoopLatch(); 6763 // All exiting blocks we have collected must dominate the only backedge. 6764 if (!Latch) 6765 return SE->getCouldNotCompute(); 6766 6767 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6768 // count is simply a minimum out of all these calculated exit counts. 6769 SmallVector<const SCEV *, 2> Ops; 6770 for (auto &ENT : ExitNotTaken) { 6771 const SCEV *BECount = ENT.ExactNotTaken; 6772 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6773 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6774 "We should only have known counts for exiting blocks that dominate " 6775 "latch!"); 6776 6777 Ops.push_back(BECount); 6778 6779 if (Preds && !ENT.hasAlwaysTruePredicate()) 6780 Preds->add(ENT.Predicate.get()); 6781 6782 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6783 "Predicate should be always true!"); 6784 } 6785 6786 return SE->getUMinFromMismatchedTypes(Ops); 6787 } 6788 6789 /// Get the exact not taken count for this loop exit. 6790 const SCEV * 6791 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6792 ScalarEvolution *SE) const { 6793 for (auto &ENT : ExitNotTaken) 6794 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6795 return ENT.ExactNotTaken; 6796 6797 return SE->getCouldNotCompute(); 6798 } 6799 6800 /// getMax - Get the max backedge taken count for the loop. 6801 const SCEV * 6802 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6803 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6804 return !ENT.hasAlwaysTruePredicate(); 6805 }; 6806 6807 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6808 return SE->getCouldNotCompute(); 6809 6810 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6811 "No point in having a non-constant max backedge taken count!"); 6812 return getMax(); 6813 } 6814 6815 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6816 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6817 return !ENT.hasAlwaysTruePredicate(); 6818 }; 6819 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6820 } 6821 6822 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6823 ScalarEvolution *SE) const { 6824 if (getMax() && getMax() != SE->getCouldNotCompute() && 6825 SE->hasOperand(getMax(), S)) 6826 return true; 6827 6828 for (auto &ENT : ExitNotTaken) 6829 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6830 SE->hasOperand(ENT.ExactNotTaken, S)) 6831 return true; 6832 6833 return false; 6834 } 6835 6836 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6837 : ExactNotTaken(E), MaxNotTaken(E) { 6838 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6839 isa<SCEVConstant>(MaxNotTaken)) && 6840 "No point in having a non-constant max backedge taken count!"); 6841 } 6842 6843 ScalarEvolution::ExitLimit::ExitLimit( 6844 const SCEV *E, const SCEV *M, bool MaxOrZero, 6845 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6846 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6847 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6848 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6849 "Exact is not allowed to be less precise than Max"); 6850 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6851 isa<SCEVConstant>(MaxNotTaken)) && 6852 "No point in having a non-constant max backedge taken count!"); 6853 for (auto *PredSet : PredSetList) 6854 for (auto *P : *PredSet) 6855 addPredicate(P); 6856 } 6857 6858 ScalarEvolution::ExitLimit::ExitLimit( 6859 const SCEV *E, const SCEV *M, bool MaxOrZero, 6860 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6861 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6862 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6863 isa<SCEVConstant>(MaxNotTaken)) && 6864 "No point in having a non-constant max backedge taken count!"); 6865 } 6866 6867 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6868 bool MaxOrZero) 6869 : ExitLimit(E, M, MaxOrZero, None) { 6870 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6871 isa<SCEVConstant>(MaxNotTaken)) && 6872 "No point in having a non-constant max backedge taken count!"); 6873 } 6874 6875 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6876 /// computable exit into a persistent ExitNotTakenInfo array. 6877 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6878 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6879 &&ExitCounts, 6880 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6881 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6882 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6883 6884 ExitNotTaken.reserve(ExitCounts.size()); 6885 std::transform( 6886 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6887 [&](const EdgeExitInfo &EEI) { 6888 BasicBlock *ExitBB = EEI.first; 6889 const ExitLimit &EL = EEI.second; 6890 if (EL.Predicates.empty()) 6891 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6892 6893 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6894 for (auto *Pred : EL.Predicates) 6895 Predicate->add(Pred); 6896 6897 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6898 }); 6899 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6900 "No point in having a non-constant max backedge taken count!"); 6901 } 6902 6903 /// Invalidate this result and free the ExitNotTakenInfo array. 6904 void ScalarEvolution::BackedgeTakenInfo::clear() { 6905 ExitNotTaken.clear(); 6906 } 6907 6908 /// Compute the number of times the backedge of the specified loop will execute. 6909 ScalarEvolution::BackedgeTakenInfo 6910 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6911 bool AllowPredicates) { 6912 SmallVector<BasicBlock *, 8> ExitingBlocks; 6913 L->getExitingBlocks(ExitingBlocks); 6914 6915 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6916 6917 SmallVector<EdgeExitInfo, 4> ExitCounts; 6918 bool CouldComputeBECount = true; 6919 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6920 const SCEV *MustExitMaxBECount = nullptr; 6921 const SCEV *MayExitMaxBECount = nullptr; 6922 bool MustExitMaxOrZero = false; 6923 6924 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6925 // and compute maxBECount. 6926 // Do a union of all the predicates here. 6927 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6928 BasicBlock *ExitBB = ExitingBlocks[i]; 6929 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6930 6931 assert((AllowPredicates || EL.Predicates.empty()) && 6932 "Predicated exit limit when predicates are not allowed!"); 6933 6934 // 1. For each exit that can be computed, add an entry to ExitCounts. 6935 // CouldComputeBECount is true only if all exits can be computed. 6936 if (EL.ExactNotTaken == getCouldNotCompute()) 6937 // We couldn't compute an exact value for this exit, so 6938 // we won't be able to compute an exact value for the loop. 6939 CouldComputeBECount = false; 6940 else 6941 ExitCounts.emplace_back(ExitBB, EL); 6942 6943 // 2. Derive the loop's MaxBECount from each exit's max number of 6944 // non-exiting iterations. Partition the loop exits into two kinds: 6945 // LoopMustExits and LoopMayExits. 6946 // 6947 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6948 // is a LoopMayExit. If any computable LoopMustExit is found, then 6949 // MaxBECount is the minimum EL.MaxNotTaken of computable 6950 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6951 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6952 // computable EL.MaxNotTaken. 6953 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6954 DT.dominates(ExitBB, Latch)) { 6955 if (!MustExitMaxBECount) { 6956 MustExitMaxBECount = EL.MaxNotTaken; 6957 MustExitMaxOrZero = EL.MaxOrZero; 6958 } else { 6959 MustExitMaxBECount = 6960 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6961 } 6962 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6963 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6964 MayExitMaxBECount = EL.MaxNotTaken; 6965 else { 6966 MayExitMaxBECount = 6967 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6968 } 6969 } 6970 } 6971 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6972 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6973 // The loop backedge will be taken the maximum or zero times if there's 6974 // a single exit that must be taken the maximum or zero times. 6975 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6976 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6977 MaxBECount, MaxOrZero); 6978 } 6979 6980 ScalarEvolution::ExitLimit 6981 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6982 bool AllowPredicates) { 6983 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 6984 // If our exiting block does not dominate the latch, then its connection with 6985 // loop's exit limit may be far from trivial. 6986 const BasicBlock *Latch = L->getLoopLatch(); 6987 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 6988 return getCouldNotCompute(); 6989 6990 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6991 TerminatorInst *Term = ExitingBlock->getTerminator(); 6992 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6993 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6994 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6995 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 6996 "It should have one successor in loop and one exit block!"); 6997 // Proceed to the next level to examine the exit condition expression. 6998 return computeExitLimitFromCond( 6999 L, BI->getCondition(), ExitIfTrue, 7000 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7001 } 7002 7003 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7004 // For switch, make sure that there is a single exit from the loop. 7005 BasicBlock *Exit = nullptr; 7006 for (auto *SBB : successors(ExitingBlock)) 7007 if (!L->contains(SBB)) { 7008 if (Exit) // Multiple exit successors. 7009 return getCouldNotCompute(); 7010 Exit = SBB; 7011 } 7012 assert(Exit && "Exiting block must have at least one exit"); 7013 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7014 /*ControlsExit=*/IsOnlyExit); 7015 } 7016 7017 return getCouldNotCompute(); 7018 } 7019 7020 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7021 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7022 bool ControlsExit, bool AllowPredicates) { 7023 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7024 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7025 ControlsExit, AllowPredicates); 7026 } 7027 7028 Optional<ScalarEvolution::ExitLimit> 7029 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7030 bool ExitIfTrue, bool ControlsExit, 7031 bool AllowPredicates) { 7032 (void)this->L; 7033 (void)this->ExitIfTrue; 7034 (void)this->AllowPredicates; 7035 7036 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7037 this->AllowPredicates == AllowPredicates && 7038 "Variance in assumed invariant key components!"); 7039 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7040 if (Itr == TripCountMap.end()) 7041 return None; 7042 return Itr->second; 7043 } 7044 7045 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7046 bool ExitIfTrue, 7047 bool ControlsExit, 7048 bool AllowPredicates, 7049 const ExitLimit &EL) { 7050 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7051 this->AllowPredicates == AllowPredicates && 7052 "Variance in assumed invariant key components!"); 7053 7054 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7055 assert(InsertResult.second && "Expected successful insertion!"); 7056 (void)InsertResult; 7057 (void)ExitIfTrue; 7058 } 7059 7060 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7061 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7062 bool ControlsExit, bool AllowPredicates) { 7063 7064 if (auto MaybeEL = 7065 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7066 return *MaybeEL; 7067 7068 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7069 ControlsExit, AllowPredicates); 7070 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7071 return EL; 7072 } 7073 7074 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7075 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7076 bool ControlsExit, bool AllowPredicates) { 7077 // Check if the controlling expression for this loop is an And or Or. 7078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7079 if (BO->getOpcode() == Instruction::And) { 7080 // Recurse on the operands of the and. 7081 bool EitherMayExit = !ExitIfTrue; 7082 ExitLimit EL0 = computeExitLimitFromCondCached( 7083 Cache, L, BO->getOperand(0), ExitIfTrue, 7084 ControlsExit && !EitherMayExit, AllowPredicates); 7085 ExitLimit EL1 = computeExitLimitFromCondCached( 7086 Cache, L, BO->getOperand(1), ExitIfTrue, 7087 ControlsExit && !EitherMayExit, AllowPredicates); 7088 const SCEV *BECount = getCouldNotCompute(); 7089 const SCEV *MaxBECount = getCouldNotCompute(); 7090 if (EitherMayExit) { 7091 // Both conditions must be true for the loop to continue executing. 7092 // Choose the less conservative count. 7093 if (EL0.ExactNotTaken == getCouldNotCompute() || 7094 EL1.ExactNotTaken == getCouldNotCompute()) 7095 BECount = getCouldNotCompute(); 7096 else 7097 BECount = 7098 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7099 if (EL0.MaxNotTaken == getCouldNotCompute()) 7100 MaxBECount = EL1.MaxNotTaken; 7101 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7102 MaxBECount = EL0.MaxNotTaken; 7103 else 7104 MaxBECount = 7105 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7106 } else { 7107 // Both conditions must be true at the same time for the loop to exit. 7108 // For now, be conservative. 7109 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7110 MaxBECount = EL0.MaxNotTaken; 7111 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7112 BECount = EL0.ExactNotTaken; 7113 } 7114 7115 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7116 // to be more aggressive when computing BECount than when computing 7117 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7118 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7119 // to not. 7120 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7121 !isa<SCEVCouldNotCompute>(BECount)) 7122 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7123 7124 return ExitLimit(BECount, MaxBECount, false, 7125 {&EL0.Predicates, &EL1.Predicates}); 7126 } 7127 if (BO->getOpcode() == Instruction::Or) { 7128 // Recurse on the operands of the or. 7129 bool EitherMayExit = ExitIfTrue; 7130 ExitLimit EL0 = computeExitLimitFromCondCached( 7131 Cache, L, BO->getOperand(0), ExitIfTrue, 7132 ControlsExit && !EitherMayExit, AllowPredicates); 7133 ExitLimit EL1 = computeExitLimitFromCondCached( 7134 Cache, L, BO->getOperand(1), ExitIfTrue, 7135 ControlsExit && !EitherMayExit, AllowPredicates); 7136 const SCEV *BECount = getCouldNotCompute(); 7137 const SCEV *MaxBECount = getCouldNotCompute(); 7138 if (EitherMayExit) { 7139 // Both conditions must be false for the loop to continue executing. 7140 // Choose the less conservative count. 7141 if (EL0.ExactNotTaken == getCouldNotCompute() || 7142 EL1.ExactNotTaken == getCouldNotCompute()) 7143 BECount = getCouldNotCompute(); 7144 else 7145 BECount = 7146 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7147 if (EL0.MaxNotTaken == getCouldNotCompute()) 7148 MaxBECount = EL1.MaxNotTaken; 7149 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7150 MaxBECount = EL0.MaxNotTaken; 7151 else 7152 MaxBECount = 7153 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7154 } else { 7155 // Both conditions must be false at the same time for the loop to exit. 7156 // For now, be conservative. 7157 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7158 MaxBECount = EL0.MaxNotTaken; 7159 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7160 BECount = EL0.ExactNotTaken; 7161 } 7162 7163 return ExitLimit(BECount, MaxBECount, false, 7164 {&EL0.Predicates, &EL1.Predicates}); 7165 } 7166 } 7167 7168 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7169 // Proceed to the next level to examine the icmp. 7170 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7171 ExitLimit EL = 7172 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7173 if (EL.hasFullInfo() || !AllowPredicates) 7174 return EL; 7175 7176 // Try again, but use SCEV predicates this time. 7177 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7178 /*AllowPredicates=*/true); 7179 } 7180 7181 // Check for a constant condition. These are normally stripped out by 7182 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7183 // preserve the CFG and is temporarily leaving constant conditions 7184 // in place. 7185 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7186 if (ExitIfTrue == !CI->getZExtValue()) 7187 // The backedge is always taken. 7188 return getCouldNotCompute(); 7189 else 7190 // The backedge is never taken. 7191 return getZero(CI->getType()); 7192 } 7193 7194 // If it's not an integer or pointer comparison then compute it the hard way. 7195 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7196 } 7197 7198 ScalarEvolution::ExitLimit 7199 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7200 ICmpInst *ExitCond, 7201 bool ExitIfTrue, 7202 bool ControlsExit, 7203 bool AllowPredicates) { 7204 // If the condition was exit on true, convert the condition to exit on false 7205 ICmpInst::Predicate Pred; 7206 if (!ExitIfTrue) 7207 Pred = ExitCond->getPredicate(); 7208 else 7209 Pred = ExitCond->getInversePredicate(); 7210 const ICmpInst::Predicate OriginalPred = Pred; 7211 7212 // Handle common loops like: for (X = "string"; *X; ++X) 7213 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7214 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7215 ExitLimit ItCnt = 7216 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7217 if (ItCnt.hasAnyInfo()) 7218 return ItCnt; 7219 } 7220 7221 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7222 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7223 7224 // Try to evaluate any dependencies out of the loop. 7225 LHS = getSCEVAtScope(LHS, L); 7226 RHS = getSCEVAtScope(RHS, L); 7227 7228 // At this point, we would like to compute how many iterations of the 7229 // loop the predicate will return true for these inputs. 7230 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7231 // If there is a loop-invariant, force it into the RHS. 7232 std::swap(LHS, RHS); 7233 Pred = ICmpInst::getSwappedPredicate(Pred); 7234 } 7235 7236 // Simplify the operands before analyzing them. 7237 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7238 7239 // If we have a comparison of a chrec against a constant, try to use value 7240 // ranges to answer this query. 7241 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7242 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7243 if (AddRec->getLoop() == L) { 7244 // Form the constant range. 7245 ConstantRange CompRange = 7246 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7247 7248 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7249 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7250 } 7251 7252 switch (Pred) { 7253 case ICmpInst::ICMP_NE: { // while (X != Y) 7254 // Convert to: while (X-Y != 0) 7255 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7256 AllowPredicates); 7257 if (EL.hasAnyInfo()) return EL; 7258 break; 7259 } 7260 case ICmpInst::ICMP_EQ: { // while (X == Y) 7261 // Convert to: while (X-Y == 0) 7262 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7263 if (EL.hasAnyInfo()) return EL; 7264 break; 7265 } 7266 case ICmpInst::ICMP_SLT: 7267 case ICmpInst::ICMP_ULT: { // while (X < Y) 7268 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7269 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7270 AllowPredicates); 7271 if (EL.hasAnyInfo()) return EL; 7272 break; 7273 } 7274 case ICmpInst::ICMP_SGT: 7275 case ICmpInst::ICMP_UGT: { // while (X > Y) 7276 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7277 ExitLimit EL = 7278 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7279 AllowPredicates); 7280 if (EL.hasAnyInfo()) return EL; 7281 break; 7282 } 7283 default: 7284 break; 7285 } 7286 7287 auto *ExhaustiveCount = 7288 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7289 7290 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7291 return ExhaustiveCount; 7292 7293 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7294 ExitCond->getOperand(1), L, OriginalPred); 7295 } 7296 7297 ScalarEvolution::ExitLimit 7298 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7299 SwitchInst *Switch, 7300 BasicBlock *ExitingBlock, 7301 bool ControlsExit) { 7302 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7303 7304 // Give up if the exit is the default dest of a switch. 7305 if (Switch->getDefaultDest() == ExitingBlock) 7306 return getCouldNotCompute(); 7307 7308 assert(L->contains(Switch->getDefaultDest()) && 7309 "Default case must not exit the loop!"); 7310 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7311 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7312 7313 // while (X != Y) --> while (X-Y != 0) 7314 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7315 if (EL.hasAnyInfo()) 7316 return EL; 7317 7318 return getCouldNotCompute(); 7319 } 7320 7321 static ConstantInt * 7322 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7323 ScalarEvolution &SE) { 7324 const SCEV *InVal = SE.getConstant(C); 7325 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7326 assert(isa<SCEVConstant>(Val) && 7327 "Evaluation of SCEV at constant didn't fold correctly?"); 7328 return cast<SCEVConstant>(Val)->getValue(); 7329 } 7330 7331 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7332 /// compute the backedge execution count. 7333 ScalarEvolution::ExitLimit 7334 ScalarEvolution::computeLoadConstantCompareExitLimit( 7335 LoadInst *LI, 7336 Constant *RHS, 7337 const Loop *L, 7338 ICmpInst::Predicate predicate) { 7339 if (LI->isVolatile()) return getCouldNotCompute(); 7340 7341 // Check to see if the loaded pointer is a getelementptr of a global. 7342 // TODO: Use SCEV instead of manually grubbing with GEPs. 7343 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7344 if (!GEP) return getCouldNotCompute(); 7345 7346 // Make sure that it is really a constant global we are gepping, with an 7347 // initializer, and make sure the first IDX is really 0. 7348 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7349 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7350 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7351 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7352 return getCouldNotCompute(); 7353 7354 // Okay, we allow one non-constant index into the GEP instruction. 7355 Value *VarIdx = nullptr; 7356 std::vector<Constant*> Indexes; 7357 unsigned VarIdxNum = 0; 7358 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7359 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7360 Indexes.push_back(CI); 7361 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7362 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7363 VarIdx = GEP->getOperand(i); 7364 VarIdxNum = i-2; 7365 Indexes.push_back(nullptr); 7366 } 7367 7368 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7369 if (!VarIdx) 7370 return getCouldNotCompute(); 7371 7372 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7373 // Check to see if X is a loop variant variable value now. 7374 const SCEV *Idx = getSCEV(VarIdx); 7375 Idx = getSCEVAtScope(Idx, L); 7376 7377 // We can only recognize very limited forms of loop index expressions, in 7378 // particular, only affine AddRec's like {C1,+,C2}. 7379 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7380 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7381 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7382 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7383 return getCouldNotCompute(); 7384 7385 unsigned MaxSteps = MaxBruteForceIterations; 7386 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7387 ConstantInt *ItCst = ConstantInt::get( 7388 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7389 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7390 7391 // Form the GEP offset. 7392 Indexes[VarIdxNum] = Val; 7393 7394 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7395 Indexes); 7396 if (!Result) break; // Cannot compute! 7397 7398 // Evaluate the condition for this iteration. 7399 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7400 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7401 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7402 ++NumArrayLenItCounts; 7403 return getConstant(ItCst); // Found terminating iteration! 7404 } 7405 } 7406 return getCouldNotCompute(); 7407 } 7408 7409 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7410 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7411 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7412 if (!RHS) 7413 return getCouldNotCompute(); 7414 7415 const BasicBlock *Latch = L->getLoopLatch(); 7416 if (!Latch) 7417 return getCouldNotCompute(); 7418 7419 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7420 if (!Predecessor) 7421 return getCouldNotCompute(); 7422 7423 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7424 // Return LHS in OutLHS and shift_opt in OutOpCode. 7425 auto MatchPositiveShift = 7426 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7427 7428 using namespace PatternMatch; 7429 7430 ConstantInt *ShiftAmt; 7431 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7432 OutOpCode = Instruction::LShr; 7433 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7434 OutOpCode = Instruction::AShr; 7435 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7436 OutOpCode = Instruction::Shl; 7437 else 7438 return false; 7439 7440 return ShiftAmt->getValue().isStrictlyPositive(); 7441 }; 7442 7443 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7444 // 7445 // loop: 7446 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7447 // %iv.shifted = lshr i32 %iv, <positive constant> 7448 // 7449 // Return true on a successful match. Return the corresponding PHI node (%iv 7450 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7451 auto MatchShiftRecurrence = 7452 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7453 Optional<Instruction::BinaryOps> PostShiftOpCode; 7454 7455 { 7456 Instruction::BinaryOps OpC; 7457 Value *V; 7458 7459 // If we encounter a shift instruction, "peel off" the shift operation, 7460 // and remember that we did so. Later when we inspect %iv's backedge 7461 // value, we will make sure that the backedge value uses the same 7462 // operation. 7463 // 7464 // Note: the peeled shift operation does not have to be the same 7465 // instruction as the one feeding into the PHI's backedge value. We only 7466 // really care about it being the same *kind* of shift instruction -- 7467 // that's all that is required for our later inferences to hold. 7468 if (MatchPositiveShift(LHS, V, OpC)) { 7469 PostShiftOpCode = OpC; 7470 LHS = V; 7471 } 7472 } 7473 7474 PNOut = dyn_cast<PHINode>(LHS); 7475 if (!PNOut || PNOut->getParent() != L->getHeader()) 7476 return false; 7477 7478 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7479 Value *OpLHS; 7480 7481 return 7482 // The backedge value for the PHI node must be a shift by a positive 7483 // amount 7484 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7485 7486 // of the PHI node itself 7487 OpLHS == PNOut && 7488 7489 // and the kind of shift should be match the kind of shift we peeled 7490 // off, if any. 7491 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7492 }; 7493 7494 PHINode *PN; 7495 Instruction::BinaryOps OpCode; 7496 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7497 return getCouldNotCompute(); 7498 7499 const DataLayout &DL = getDataLayout(); 7500 7501 // The key rationale for this optimization is that for some kinds of shift 7502 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7503 // within a finite number of iterations. If the condition guarding the 7504 // backedge (in the sense that the backedge is taken if the condition is true) 7505 // is false for the value the shift recurrence stabilizes to, then we know 7506 // that the backedge is taken only a finite number of times. 7507 7508 ConstantInt *StableValue = nullptr; 7509 switch (OpCode) { 7510 default: 7511 llvm_unreachable("Impossible case!"); 7512 7513 case Instruction::AShr: { 7514 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7515 // bitwidth(K) iterations. 7516 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7517 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7518 Predecessor->getTerminator(), &DT); 7519 auto *Ty = cast<IntegerType>(RHS->getType()); 7520 if (Known.isNonNegative()) 7521 StableValue = ConstantInt::get(Ty, 0); 7522 else if (Known.isNegative()) 7523 StableValue = ConstantInt::get(Ty, -1, true); 7524 else 7525 return getCouldNotCompute(); 7526 7527 break; 7528 } 7529 case Instruction::LShr: 7530 case Instruction::Shl: 7531 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7532 // stabilize to 0 in at most bitwidth(K) iterations. 7533 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7534 break; 7535 } 7536 7537 auto *Result = 7538 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7539 assert(Result->getType()->isIntegerTy(1) && 7540 "Otherwise cannot be an operand to a branch instruction"); 7541 7542 if (Result->isZeroValue()) { 7543 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7544 const SCEV *UpperBound = 7545 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7546 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7547 } 7548 7549 return getCouldNotCompute(); 7550 } 7551 7552 /// Return true if we can constant fold an instruction of the specified type, 7553 /// assuming that all operands were constants. 7554 static bool CanConstantFold(const Instruction *I) { 7555 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7556 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7557 isa<LoadInst>(I)) 7558 return true; 7559 7560 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7561 if (const Function *F = CI->getCalledFunction()) 7562 return canConstantFoldCallTo(CI, F); 7563 return false; 7564 } 7565 7566 /// Determine whether this instruction can constant evolve within this loop 7567 /// assuming its operands can all constant evolve. 7568 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7569 // An instruction outside of the loop can't be derived from a loop PHI. 7570 if (!L->contains(I)) return false; 7571 7572 if (isa<PHINode>(I)) { 7573 // We don't currently keep track of the control flow needed to evaluate 7574 // PHIs, so we cannot handle PHIs inside of loops. 7575 return L->getHeader() == I->getParent(); 7576 } 7577 7578 // If we won't be able to constant fold this expression even if the operands 7579 // are constants, bail early. 7580 return CanConstantFold(I); 7581 } 7582 7583 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7584 /// recursing through each instruction operand until reaching a loop header phi. 7585 static PHINode * 7586 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7587 DenseMap<Instruction *, PHINode *> &PHIMap, 7588 unsigned Depth) { 7589 if (Depth > MaxConstantEvolvingDepth) 7590 return nullptr; 7591 7592 // Otherwise, we can evaluate this instruction if all of its operands are 7593 // constant or derived from a PHI node themselves. 7594 PHINode *PHI = nullptr; 7595 for (Value *Op : UseInst->operands()) { 7596 if (isa<Constant>(Op)) continue; 7597 7598 Instruction *OpInst = dyn_cast<Instruction>(Op); 7599 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7600 7601 PHINode *P = dyn_cast<PHINode>(OpInst); 7602 if (!P) 7603 // If this operand is already visited, reuse the prior result. 7604 // We may have P != PHI if this is the deepest point at which the 7605 // inconsistent paths meet. 7606 P = PHIMap.lookup(OpInst); 7607 if (!P) { 7608 // Recurse and memoize the results, whether a phi is found or not. 7609 // This recursive call invalidates pointers into PHIMap. 7610 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7611 PHIMap[OpInst] = P; 7612 } 7613 if (!P) 7614 return nullptr; // Not evolving from PHI 7615 if (PHI && PHI != P) 7616 return nullptr; // Evolving from multiple different PHIs. 7617 PHI = P; 7618 } 7619 // This is a expression evolving from a constant PHI! 7620 return PHI; 7621 } 7622 7623 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7624 /// in the loop that V is derived from. We allow arbitrary operations along the 7625 /// way, but the operands of an operation must either be constants or a value 7626 /// derived from a constant PHI. If this expression does not fit with these 7627 /// constraints, return null. 7628 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7629 Instruction *I = dyn_cast<Instruction>(V); 7630 if (!I || !canConstantEvolve(I, L)) return nullptr; 7631 7632 if (PHINode *PN = dyn_cast<PHINode>(I)) 7633 return PN; 7634 7635 // Record non-constant instructions contained by the loop. 7636 DenseMap<Instruction *, PHINode *> PHIMap; 7637 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7638 } 7639 7640 /// EvaluateExpression - Given an expression that passes the 7641 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7642 /// in the loop has the value PHIVal. If we can't fold this expression for some 7643 /// reason, return null. 7644 static Constant *EvaluateExpression(Value *V, const Loop *L, 7645 DenseMap<Instruction *, Constant *> &Vals, 7646 const DataLayout &DL, 7647 const TargetLibraryInfo *TLI) { 7648 // Convenient constant check, but redundant for recursive calls. 7649 if (Constant *C = dyn_cast<Constant>(V)) return C; 7650 Instruction *I = dyn_cast<Instruction>(V); 7651 if (!I) return nullptr; 7652 7653 if (Constant *C = Vals.lookup(I)) return C; 7654 7655 // An instruction inside the loop depends on a value outside the loop that we 7656 // weren't given a mapping for, or a value such as a call inside the loop. 7657 if (!canConstantEvolve(I, L)) return nullptr; 7658 7659 // An unmapped PHI can be due to a branch or another loop inside this loop, 7660 // or due to this not being the initial iteration through a loop where we 7661 // couldn't compute the evolution of this particular PHI last time. 7662 if (isa<PHINode>(I)) return nullptr; 7663 7664 std::vector<Constant*> Operands(I->getNumOperands()); 7665 7666 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7667 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7668 if (!Operand) { 7669 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7670 if (!Operands[i]) return nullptr; 7671 continue; 7672 } 7673 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7674 Vals[Operand] = C; 7675 if (!C) return nullptr; 7676 Operands[i] = C; 7677 } 7678 7679 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7680 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7681 Operands[1], DL, TLI); 7682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7683 if (!LI->isVolatile()) 7684 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7685 } 7686 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7687 } 7688 7689 7690 // If every incoming value to PN except the one for BB is a specific Constant, 7691 // return that, else return nullptr. 7692 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7693 Constant *IncomingVal = nullptr; 7694 7695 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7696 if (PN->getIncomingBlock(i) == BB) 7697 continue; 7698 7699 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7700 if (!CurrentVal) 7701 return nullptr; 7702 7703 if (IncomingVal != CurrentVal) { 7704 if (IncomingVal) 7705 return nullptr; 7706 IncomingVal = CurrentVal; 7707 } 7708 } 7709 7710 return IncomingVal; 7711 } 7712 7713 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7714 /// in the header of its containing loop, we know the loop executes a 7715 /// constant number of times, and the PHI node is just a recurrence 7716 /// involving constants, fold it. 7717 Constant * 7718 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7719 const APInt &BEs, 7720 const Loop *L) { 7721 auto I = ConstantEvolutionLoopExitValue.find(PN); 7722 if (I != ConstantEvolutionLoopExitValue.end()) 7723 return I->second; 7724 7725 if (BEs.ugt(MaxBruteForceIterations)) 7726 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7727 7728 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7729 7730 DenseMap<Instruction *, Constant *> CurrentIterVals; 7731 BasicBlock *Header = L->getHeader(); 7732 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7733 7734 BasicBlock *Latch = L->getLoopLatch(); 7735 if (!Latch) 7736 return nullptr; 7737 7738 for (PHINode &PHI : Header->phis()) { 7739 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7740 CurrentIterVals[&PHI] = StartCST; 7741 } 7742 if (!CurrentIterVals.count(PN)) 7743 return RetVal = nullptr; 7744 7745 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7746 7747 // Execute the loop symbolically to determine the exit value. 7748 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7749 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7750 7751 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7752 unsigned IterationNum = 0; 7753 const DataLayout &DL = getDataLayout(); 7754 for (; ; ++IterationNum) { 7755 if (IterationNum == NumIterations) 7756 return RetVal = CurrentIterVals[PN]; // Got exit value! 7757 7758 // Compute the value of the PHIs for the next iteration. 7759 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7760 DenseMap<Instruction *, Constant *> NextIterVals; 7761 Constant *NextPHI = 7762 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7763 if (!NextPHI) 7764 return nullptr; // Couldn't evaluate! 7765 NextIterVals[PN] = NextPHI; 7766 7767 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7768 7769 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7770 // cease to be able to evaluate one of them or if they stop evolving, 7771 // because that doesn't necessarily prevent us from computing PN. 7772 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7773 for (const auto &I : CurrentIterVals) { 7774 PHINode *PHI = dyn_cast<PHINode>(I.first); 7775 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7776 PHIsToCompute.emplace_back(PHI, I.second); 7777 } 7778 // We use two distinct loops because EvaluateExpression may invalidate any 7779 // iterators into CurrentIterVals. 7780 for (const auto &I : PHIsToCompute) { 7781 PHINode *PHI = I.first; 7782 Constant *&NextPHI = NextIterVals[PHI]; 7783 if (!NextPHI) { // Not already computed. 7784 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7785 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7786 } 7787 if (NextPHI != I.second) 7788 StoppedEvolving = false; 7789 } 7790 7791 // If all entries in CurrentIterVals == NextIterVals then we can stop 7792 // iterating, the loop can't continue to change. 7793 if (StoppedEvolving) 7794 return RetVal = CurrentIterVals[PN]; 7795 7796 CurrentIterVals.swap(NextIterVals); 7797 } 7798 } 7799 7800 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7801 Value *Cond, 7802 bool ExitWhen) { 7803 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7804 if (!PN) return getCouldNotCompute(); 7805 7806 // If the loop is canonicalized, the PHI will have exactly two entries. 7807 // That's the only form we support here. 7808 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7809 7810 DenseMap<Instruction *, Constant *> CurrentIterVals; 7811 BasicBlock *Header = L->getHeader(); 7812 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7813 7814 BasicBlock *Latch = L->getLoopLatch(); 7815 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7816 7817 for (PHINode &PHI : Header->phis()) { 7818 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7819 CurrentIterVals[&PHI] = StartCST; 7820 } 7821 if (!CurrentIterVals.count(PN)) 7822 return getCouldNotCompute(); 7823 7824 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7825 // the loop symbolically to determine when the condition gets a value of 7826 // "ExitWhen". 7827 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7828 const DataLayout &DL = getDataLayout(); 7829 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7830 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7831 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7832 7833 // Couldn't symbolically evaluate. 7834 if (!CondVal) return getCouldNotCompute(); 7835 7836 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7837 ++NumBruteForceTripCountsComputed; 7838 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7839 } 7840 7841 // Update all the PHI nodes for the next iteration. 7842 DenseMap<Instruction *, Constant *> NextIterVals; 7843 7844 // Create a list of which PHIs we need to compute. We want to do this before 7845 // calling EvaluateExpression on them because that may invalidate iterators 7846 // into CurrentIterVals. 7847 SmallVector<PHINode *, 8> PHIsToCompute; 7848 for (const auto &I : CurrentIterVals) { 7849 PHINode *PHI = dyn_cast<PHINode>(I.first); 7850 if (!PHI || PHI->getParent() != Header) continue; 7851 PHIsToCompute.push_back(PHI); 7852 } 7853 for (PHINode *PHI : PHIsToCompute) { 7854 Constant *&NextPHI = NextIterVals[PHI]; 7855 if (NextPHI) continue; // Already computed! 7856 7857 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7858 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7859 } 7860 CurrentIterVals.swap(NextIterVals); 7861 } 7862 7863 // Too many iterations were needed to evaluate. 7864 return getCouldNotCompute(); 7865 } 7866 7867 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7868 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7869 ValuesAtScopes[V]; 7870 // Check to see if we've folded this expression at this loop before. 7871 for (auto &LS : Values) 7872 if (LS.first == L) 7873 return LS.second ? LS.second : V; 7874 7875 Values.emplace_back(L, nullptr); 7876 7877 // Otherwise compute it. 7878 const SCEV *C = computeSCEVAtScope(V, L); 7879 for (auto &LS : reverse(ValuesAtScopes[V])) 7880 if (LS.first == L) { 7881 LS.second = C; 7882 break; 7883 } 7884 return C; 7885 } 7886 7887 /// This builds up a Constant using the ConstantExpr interface. That way, we 7888 /// will return Constants for objects which aren't represented by a 7889 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7890 /// Returns NULL if the SCEV isn't representable as a Constant. 7891 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7892 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7893 case scCouldNotCompute: 7894 case scAddRecExpr: 7895 break; 7896 case scConstant: 7897 return cast<SCEVConstant>(V)->getValue(); 7898 case scUnknown: 7899 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7900 case scSignExtend: { 7901 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7902 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7903 return ConstantExpr::getSExt(CastOp, SS->getType()); 7904 break; 7905 } 7906 case scZeroExtend: { 7907 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7908 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7909 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7910 break; 7911 } 7912 case scTruncate: { 7913 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7914 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7915 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7916 break; 7917 } 7918 case scAddExpr: { 7919 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7920 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7921 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7922 unsigned AS = PTy->getAddressSpace(); 7923 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7924 C = ConstantExpr::getBitCast(C, DestPtrTy); 7925 } 7926 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7927 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7928 if (!C2) return nullptr; 7929 7930 // First pointer! 7931 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7932 unsigned AS = C2->getType()->getPointerAddressSpace(); 7933 std::swap(C, C2); 7934 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7935 // The offsets have been converted to bytes. We can add bytes to an 7936 // i8* by GEP with the byte count in the first index. 7937 C = ConstantExpr::getBitCast(C, DestPtrTy); 7938 } 7939 7940 // Don't bother trying to sum two pointers. We probably can't 7941 // statically compute a load that results from it anyway. 7942 if (C2->getType()->isPointerTy()) 7943 return nullptr; 7944 7945 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7946 if (PTy->getElementType()->isStructTy()) 7947 C2 = ConstantExpr::getIntegerCast( 7948 C2, Type::getInt32Ty(C->getContext()), true); 7949 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7950 } else 7951 C = ConstantExpr::getAdd(C, C2); 7952 } 7953 return C; 7954 } 7955 break; 7956 } 7957 case scMulExpr: { 7958 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7959 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7960 // Don't bother with pointers at all. 7961 if (C->getType()->isPointerTy()) return nullptr; 7962 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7963 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7964 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7965 C = ConstantExpr::getMul(C, C2); 7966 } 7967 return C; 7968 } 7969 break; 7970 } 7971 case scUDivExpr: { 7972 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7973 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7974 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7975 if (LHS->getType() == RHS->getType()) 7976 return ConstantExpr::getUDiv(LHS, RHS); 7977 break; 7978 } 7979 case scSMaxExpr: 7980 case scUMaxExpr: 7981 break; // TODO: smax, umax. 7982 } 7983 return nullptr; 7984 } 7985 7986 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7987 if (isa<SCEVConstant>(V)) return V; 7988 7989 // If this instruction is evolved from a constant-evolving PHI, compute the 7990 // exit value from the loop without using SCEVs. 7991 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7992 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7993 const Loop *LI = this->LI[I->getParent()]; 7994 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7995 if (PHINode *PN = dyn_cast<PHINode>(I)) 7996 if (PN->getParent() == LI->getHeader()) { 7997 // Okay, there is no closed form solution for the PHI node. Check 7998 // to see if the loop that contains it has a known backedge-taken 7999 // count. If so, we may be able to force computation of the exit 8000 // value. 8001 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8002 if (const SCEVConstant *BTCC = 8003 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8004 8005 // This trivial case can show up in some degenerate cases where 8006 // the incoming IR has not yet been fully simplified. 8007 if (BTCC->getValue()->isZero()) { 8008 Value *InitValue = nullptr; 8009 bool MultipleInitValues = false; 8010 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8011 if (!LI->contains(PN->getIncomingBlock(i))) { 8012 if (!InitValue) 8013 InitValue = PN->getIncomingValue(i); 8014 else if (InitValue != PN->getIncomingValue(i)) { 8015 MultipleInitValues = true; 8016 break; 8017 } 8018 } 8019 if (!MultipleInitValues && InitValue) 8020 return getSCEV(InitValue); 8021 } 8022 } 8023 // Okay, we know how many times the containing loop executes. If 8024 // this is a constant evolving PHI node, get the final value at 8025 // the specified iteration number. 8026 Constant *RV = 8027 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8028 if (RV) return getSCEV(RV); 8029 } 8030 } 8031 8032 // Okay, this is an expression that we cannot symbolically evaluate 8033 // into a SCEV. Check to see if it's possible to symbolically evaluate 8034 // the arguments into constants, and if so, try to constant propagate the 8035 // result. This is particularly useful for computing loop exit values. 8036 if (CanConstantFold(I)) { 8037 SmallVector<Constant *, 4> Operands; 8038 bool MadeImprovement = false; 8039 for (Value *Op : I->operands()) { 8040 if (Constant *C = dyn_cast<Constant>(Op)) { 8041 Operands.push_back(C); 8042 continue; 8043 } 8044 8045 // If any of the operands is non-constant and if they are 8046 // non-integer and non-pointer, don't even try to analyze them 8047 // with scev techniques. 8048 if (!isSCEVable(Op->getType())) 8049 return V; 8050 8051 const SCEV *OrigV = getSCEV(Op); 8052 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8053 MadeImprovement |= OrigV != OpV; 8054 8055 Constant *C = BuildConstantFromSCEV(OpV); 8056 if (!C) return V; 8057 if (C->getType() != Op->getType()) 8058 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8059 Op->getType(), 8060 false), 8061 C, Op->getType()); 8062 Operands.push_back(C); 8063 } 8064 8065 // Check to see if getSCEVAtScope actually made an improvement. 8066 if (MadeImprovement) { 8067 Constant *C = nullptr; 8068 const DataLayout &DL = getDataLayout(); 8069 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8070 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8071 Operands[1], DL, &TLI); 8072 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8073 if (!LI->isVolatile()) 8074 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8075 } else 8076 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8077 if (!C) return V; 8078 return getSCEV(C); 8079 } 8080 } 8081 } 8082 8083 // This is some other type of SCEVUnknown, just return it. 8084 return V; 8085 } 8086 8087 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8088 // Avoid performing the look-up in the common case where the specified 8089 // expression has no loop-variant portions. 8090 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8091 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8092 if (OpAtScope != Comm->getOperand(i)) { 8093 // Okay, at least one of these operands is loop variant but might be 8094 // foldable. Build a new instance of the folded commutative expression. 8095 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8096 Comm->op_begin()+i); 8097 NewOps.push_back(OpAtScope); 8098 8099 for (++i; i != e; ++i) { 8100 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8101 NewOps.push_back(OpAtScope); 8102 } 8103 if (isa<SCEVAddExpr>(Comm)) 8104 return getAddExpr(NewOps); 8105 if (isa<SCEVMulExpr>(Comm)) 8106 return getMulExpr(NewOps); 8107 if (isa<SCEVSMaxExpr>(Comm)) 8108 return getSMaxExpr(NewOps); 8109 if (isa<SCEVUMaxExpr>(Comm)) 8110 return getUMaxExpr(NewOps); 8111 llvm_unreachable("Unknown commutative SCEV type!"); 8112 } 8113 } 8114 // If we got here, all operands are loop invariant. 8115 return Comm; 8116 } 8117 8118 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8119 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8120 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8121 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8122 return Div; // must be loop invariant 8123 return getUDivExpr(LHS, RHS); 8124 } 8125 8126 // If this is a loop recurrence for a loop that does not contain L, then we 8127 // are dealing with the final value computed by the loop. 8128 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8129 // First, attempt to evaluate each operand. 8130 // Avoid performing the look-up in the common case where the specified 8131 // expression has no loop-variant portions. 8132 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8133 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8134 if (OpAtScope == AddRec->getOperand(i)) 8135 continue; 8136 8137 // Okay, at least one of these operands is loop variant but might be 8138 // foldable. Build a new instance of the folded commutative expression. 8139 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8140 AddRec->op_begin()+i); 8141 NewOps.push_back(OpAtScope); 8142 for (++i; i != e; ++i) 8143 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8144 8145 const SCEV *FoldedRec = 8146 getAddRecExpr(NewOps, AddRec->getLoop(), 8147 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8148 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8149 // The addrec may be folded to a nonrecurrence, for example, if the 8150 // induction variable is multiplied by zero after constant folding. Go 8151 // ahead and return the folded value. 8152 if (!AddRec) 8153 return FoldedRec; 8154 break; 8155 } 8156 8157 // If the scope is outside the addrec's loop, evaluate it by using the 8158 // loop exit value of the addrec. 8159 if (!AddRec->getLoop()->contains(L)) { 8160 // To evaluate this recurrence, we need to know how many times the AddRec 8161 // loop iterates. Compute this now. 8162 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8163 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8164 8165 // Then, evaluate the AddRec. 8166 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8167 } 8168 8169 return AddRec; 8170 } 8171 8172 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8173 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8174 if (Op == Cast->getOperand()) 8175 return Cast; // must be loop invariant 8176 return getZeroExtendExpr(Op, Cast->getType()); 8177 } 8178 8179 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8180 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8181 if (Op == Cast->getOperand()) 8182 return Cast; // must be loop invariant 8183 return getSignExtendExpr(Op, Cast->getType()); 8184 } 8185 8186 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8187 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8188 if (Op == Cast->getOperand()) 8189 return Cast; // must be loop invariant 8190 return getTruncateExpr(Op, Cast->getType()); 8191 } 8192 8193 llvm_unreachable("Unknown SCEV type!"); 8194 } 8195 8196 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8197 return getSCEVAtScope(getSCEV(V), L); 8198 } 8199 8200 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8201 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8202 return stripInjectiveFunctions(ZExt->getOperand()); 8203 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8204 return stripInjectiveFunctions(SExt->getOperand()); 8205 return S; 8206 } 8207 8208 /// Finds the minimum unsigned root of the following equation: 8209 /// 8210 /// A * X = B (mod N) 8211 /// 8212 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8213 /// A and B isn't important. 8214 /// 8215 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8216 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8217 ScalarEvolution &SE) { 8218 uint32_t BW = A.getBitWidth(); 8219 assert(BW == SE.getTypeSizeInBits(B->getType())); 8220 assert(A != 0 && "A must be non-zero."); 8221 8222 // 1. D = gcd(A, N) 8223 // 8224 // The gcd of A and N may have only one prime factor: 2. The number of 8225 // trailing zeros in A is its multiplicity 8226 uint32_t Mult2 = A.countTrailingZeros(); 8227 // D = 2^Mult2 8228 8229 // 2. Check if B is divisible by D. 8230 // 8231 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8232 // is not less than multiplicity of this prime factor for D. 8233 if (SE.GetMinTrailingZeros(B) < Mult2) 8234 return SE.getCouldNotCompute(); 8235 8236 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8237 // modulo (N / D). 8238 // 8239 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8240 // (N / D) in general. The inverse itself always fits into BW bits, though, 8241 // so we immediately truncate it. 8242 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8243 APInt Mod(BW + 1, 0); 8244 Mod.setBit(BW - Mult2); // Mod = N / D 8245 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8246 8247 // 4. Compute the minimum unsigned root of the equation: 8248 // I * (B / D) mod (N / D) 8249 // To simplify the computation, we factor out the divide by D: 8250 // (I * B mod N) / D 8251 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8252 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8253 } 8254 8255 /// Find the roots of the quadratic equation for the given quadratic chrec 8256 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8257 /// two SCEVCouldNotCompute objects. 8258 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8259 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8260 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8261 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8262 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8263 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8264 8265 // We currently can only solve this if the coefficients are constants. 8266 if (!LC || !MC || !NC) 8267 return None; 8268 8269 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8270 const APInt &L = LC->getAPInt(); 8271 const APInt &M = MC->getAPInt(); 8272 const APInt &N = NC->getAPInt(); 8273 APInt Two(BitWidth, 2); 8274 8275 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8276 8277 // The A coefficient is N/2 8278 APInt A = N.sdiv(Two); 8279 8280 // The B coefficient is M-N/2 8281 APInt B = M; 8282 B -= A; // A is the same as N/2. 8283 8284 // The C coefficient is L. 8285 const APInt& C = L; 8286 8287 // Compute the B^2-4ac term. 8288 APInt SqrtTerm = B; 8289 SqrtTerm *= B; 8290 SqrtTerm -= 4 * (A * C); 8291 8292 if (SqrtTerm.isNegative()) { 8293 // The loop is provably infinite. 8294 return None; 8295 } 8296 8297 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8298 // integer value or else APInt::sqrt() will assert. 8299 APInt SqrtVal = SqrtTerm.sqrt(); 8300 8301 // Compute the two solutions for the quadratic formula. 8302 // The divisions must be performed as signed divisions. 8303 APInt NegB = -std::move(B); 8304 APInt TwoA = std::move(A); 8305 TwoA <<= 1; 8306 if (TwoA.isNullValue()) 8307 return None; 8308 8309 LLVMContext &Context = SE.getContext(); 8310 8311 ConstantInt *Solution1 = 8312 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8313 ConstantInt *Solution2 = 8314 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8315 8316 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8317 cast<SCEVConstant>(SE.getConstant(Solution2))); 8318 } 8319 8320 ScalarEvolution::ExitLimit 8321 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8322 bool AllowPredicates) { 8323 8324 // This is only used for loops with a "x != y" exit test. The exit condition 8325 // is now expressed as a single expression, V = x-y. So the exit test is 8326 // effectively V != 0. We know and take advantage of the fact that this 8327 // expression only being used in a comparison by zero context. 8328 8329 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8330 // If the value is a constant 8331 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8332 // If the value is already zero, the branch will execute zero times. 8333 if (C->getValue()->isZero()) return C; 8334 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8335 } 8336 8337 const SCEVAddRecExpr *AddRec = 8338 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8339 8340 if (!AddRec && AllowPredicates) 8341 // Try to make this an AddRec using runtime tests, in the first X 8342 // iterations of this loop, where X is the SCEV expression found by the 8343 // algorithm below. 8344 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8345 8346 if (!AddRec || AddRec->getLoop() != L) 8347 return getCouldNotCompute(); 8348 8349 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8350 // the quadratic equation to solve it. 8351 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8352 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8353 const SCEVConstant *R1 = Roots->first; 8354 const SCEVConstant *R2 = Roots->second; 8355 // Pick the smallest positive root value. 8356 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8357 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8358 if (!CB->getZExtValue()) 8359 std::swap(R1, R2); // R1 is the minimum root now. 8360 8361 // We can only use this value if the chrec ends up with an exact zero 8362 // value at this index. When solving for "X*X != 5", for example, we 8363 // should not accept a root of 2. 8364 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8365 if (Val->isZero()) 8366 // We found a quadratic root! 8367 return ExitLimit(R1, R1, false, Predicates); 8368 } 8369 } 8370 return getCouldNotCompute(); 8371 } 8372 8373 // Otherwise we can only handle this if it is affine. 8374 if (!AddRec->isAffine()) 8375 return getCouldNotCompute(); 8376 8377 // If this is an affine expression, the execution count of this branch is 8378 // the minimum unsigned root of the following equation: 8379 // 8380 // Start + Step*N = 0 (mod 2^BW) 8381 // 8382 // equivalent to: 8383 // 8384 // Step*N = -Start (mod 2^BW) 8385 // 8386 // where BW is the common bit width of Start and Step. 8387 8388 // Get the initial value for the loop. 8389 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8390 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8391 8392 // For now we handle only constant steps. 8393 // 8394 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8395 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8396 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8397 // We have not yet seen any such cases. 8398 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8399 if (!StepC || StepC->getValue()->isZero()) 8400 return getCouldNotCompute(); 8401 8402 // For positive steps (counting up until unsigned overflow): 8403 // N = -Start/Step (as unsigned) 8404 // For negative steps (counting down to zero): 8405 // N = Start/-Step 8406 // First compute the unsigned distance from zero in the direction of Step. 8407 bool CountDown = StepC->getAPInt().isNegative(); 8408 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8409 8410 // Handle unitary steps, which cannot wraparound. 8411 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8412 // N = Distance (as unsigned) 8413 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8414 APInt MaxBECount = getUnsignedRangeMax(Distance); 8415 8416 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8417 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8418 // case, and see if we can improve the bound. 8419 // 8420 // Explicitly handling this here is necessary because getUnsignedRange 8421 // isn't context-sensitive; it doesn't know that we only care about the 8422 // range inside the loop. 8423 const SCEV *Zero = getZero(Distance->getType()); 8424 const SCEV *One = getOne(Distance->getType()); 8425 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8426 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8427 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8428 // as "unsigned_max(Distance + 1) - 1". 8429 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8430 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8431 } 8432 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8433 } 8434 8435 // If the condition controls loop exit (the loop exits only if the expression 8436 // is true) and the addition is no-wrap we can use unsigned divide to 8437 // compute the backedge count. In this case, the step may not divide the 8438 // distance, but we don't care because if the condition is "missed" the loop 8439 // will have undefined behavior due to wrapping. 8440 if (ControlsExit && AddRec->hasNoSelfWrap() && 8441 loopHasNoAbnormalExits(AddRec->getLoop())) { 8442 const SCEV *Exact = 8443 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8444 const SCEV *Max = 8445 Exact == getCouldNotCompute() 8446 ? Exact 8447 : getConstant(getUnsignedRangeMax(Exact)); 8448 return ExitLimit(Exact, Max, false, Predicates); 8449 } 8450 8451 // Solve the general equation. 8452 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8453 getNegativeSCEV(Start), *this); 8454 const SCEV *M = E == getCouldNotCompute() 8455 ? E 8456 : getConstant(getUnsignedRangeMax(E)); 8457 return ExitLimit(E, M, false, Predicates); 8458 } 8459 8460 ScalarEvolution::ExitLimit 8461 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8462 // Loops that look like: while (X == 0) are very strange indeed. We don't 8463 // handle them yet except for the trivial case. This could be expanded in the 8464 // future as needed. 8465 8466 // If the value is a constant, check to see if it is known to be non-zero 8467 // already. If so, the backedge will execute zero times. 8468 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8469 if (!C->getValue()->isZero()) 8470 return getZero(C->getType()); 8471 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8472 } 8473 8474 // We could implement others, but I really doubt anyone writes loops like 8475 // this, and if they did, they would already be constant folded. 8476 return getCouldNotCompute(); 8477 } 8478 8479 std::pair<BasicBlock *, BasicBlock *> 8480 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8481 // If the block has a unique predecessor, then there is no path from the 8482 // predecessor to the block that does not go through the direct edge 8483 // from the predecessor to the block. 8484 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8485 return {Pred, BB}; 8486 8487 // A loop's header is defined to be a block that dominates the loop. 8488 // If the header has a unique predecessor outside the loop, it must be 8489 // a block that has exactly one successor that can reach the loop. 8490 if (Loop *L = LI.getLoopFor(BB)) 8491 return {L->getLoopPredecessor(), L->getHeader()}; 8492 8493 return {nullptr, nullptr}; 8494 } 8495 8496 /// SCEV structural equivalence is usually sufficient for testing whether two 8497 /// expressions are equal, however for the purposes of looking for a condition 8498 /// guarding a loop, it can be useful to be a little more general, since a 8499 /// front-end may have replicated the controlling expression. 8500 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8501 // Quick check to see if they are the same SCEV. 8502 if (A == B) return true; 8503 8504 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8505 // Not all instructions that are "identical" compute the same value. For 8506 // instance, two distinct alloca instructions allocating the same type are 8507 // identical and do not read memory; but compute distinct values. 8508 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8509 }; 8510 8511 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8512 // two different instructions with the same value. Check for this case. 8513 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8514 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8515 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8516 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8517 if (ComputesEqualValues(AI, BI)) 8518 return true; 8519 8520 // Otherwise assume they may have a different value. 8521 return false; 8522 } 8523 8524 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8525 const SCEV *&LHS, const SCEV *&RHS, 8526 unsigned Depth) { 8527 bool Changed = false; 8528 8529 // If we hit the max recursion limit bail out. 8530 if (Depth >= 3) 8531 return false; 8532 8533 // Canonicalize a constant to the right side. 8534 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8535 // Check for both operands constant. 8536 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8537 if (ConstantExpr::getICmp(Pred, 8538 LHSC->getValue(), 8539 RHSC->getValue())->isNullValue()) 8540 goto trivially_false; 8541 else 8542 goto trivially_true; 8543 } 8544 // Otherwise swap the operands to put the constant on the right. 8545 std::swap(LHS, RHS); 8546 Pred = ICmpInst::getSwappedPredicate(Pred); 8547 Changed = true; 8548 } 8549 8550 // If we're comparing an addrec with a value which is loop-invariant in the 8551 // addrec's loop, put the addrec on the left. Also make a dominance check, 8552 // as both operands could be addrecs loop-invariant in each other's loop. 8553 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8554 const Loop *L = AR->getLoop(); 8555 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8556 std::swap(LHS, RHS); 8557 Pred = ICmpInst::getSwappedPredicate(Pred); 8558 Changed = true; 8559 } 8560 } 8561 8562 // If there's a constant operand, canonicalize comparisons with boundary 8563 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8564 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8565 const APInt &RA = RC->getAPInt(); 8566 8567 bool SimplifiedByConstantRange = false; 8568 8569 if (!ICmpInst::isEquality(Pred)) { 8570 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8571 if (ExactCR.isFullSet()) 8572 goto trivially_true; 8573 else if (ExactCR.isEmptySet()) 8574 goto trivially_false; 8575 8576 APInt NewRHS; 8577 CmpInst::Predicate NewPred; 8578 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8579 ICmpInst::isEquality(NewPred)) { 8580 // We were able to convert an inequality to an equality. 8581 Pred = NewPred; 8582 RHS = getConstant(NewRHS); 8583 Changed = SimplifiedByConstantRange = true; 8584 } 8585 } 8586 8587 if (!SimplifiedByConstantRange) { 8588 switch (Pred) { 8589 default: 8590 break; 8591 case ICmpInst::ICMP_EQ: 8592 case ICmpInst::ICMP_NE: 8593 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8594 if (!RA) 8595 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8596 if (const SCEVMulExpr *ME = 8597 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8598 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8599 ME->getOperand(0)->isAllOnesValue()) { 8600 RHS = AE->getOperand(1); 8601 LHS = ME->getOperand(1); 8602 Changed = true; 8603 } 8604 break; 8605 8606 8607 // The "Should have been caught earlier!" messages refer to the fact 8608 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8609 // should have fired on the corresponding cases, and canonicalized the 8610 // check to trivially_true or trivially_false. 8611 8612 case ICmpInst::ICMP_UGE: 8613 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8614 Pred = ICmpInst::ICMP_UGT; 8615 RHS = getConstant(RA - 1); 8616 Changed = true; 8617 break; 8618 case ICmpInst::ICMP_ULE: 8619 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8620 Pred = ICmpInst::ICMP_ULT; 8621 RHS = getConstant(RA + 1); 8622 Changed = true; 8623 break; 8624 case ICmpInst::ICMP_SGE: 8625 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8626 Pred = ICmpInst::ICMP_SGT; 8627 RHS = getConstant(RA - 1); 8628 Changed = true; 8629 break; 8630 case ICmpInst::ICMP_SLE: 8631 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8632 Pred = ICmpInst::ICMP_SLT; 8633 RHS = getConstant(RA + 1); 8634 Changed = true; 8635 break; 8636 } 8637 } 8638 } 8639 8640 // Check for obvious equality. 8641 if (HasSameValue(LHS, RHS)) { 8642 if (ICmpInst::isTrueWhenEqual(Pred)) 8643 goto trivially_true; 8644 if (ICmpInst::isFalseWhenEqual(Pred)) 8645 goto trivially_false; 8646 } 8647 8648 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8649 // adding or subtracting 1 from one of the operands. 8650 switch (Pred) { 8651 case ICmpInst::ICMP_SLE: 8652 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8653 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8654 SCEV::FlagNSW); 8655 Pred = ICmpInst::ICMP_SLT; 8656 Changed = true; 8657 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8658 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8659 SCEV::FlagNSW); 8660 Pred = ICmpInst::ICMP_SLT; 8661 Changed = true; 8662 } 8663 break; 8664 case ICmpInst::ICMP_SGE: 8665 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8666 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8667 SCEV::FlagNSW); 8668 Pred = ICmpInst::ICMP_SGT; 8669 Changed = true; 8670 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8671 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8672 SCEV::FlagNSW); 8673 Pred = ICmpInst::ICMP_SGT; 8674 Changed = true; 8675 } 8676 break; 8677 case ICmpInst::ICMP_ULE: 8678 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8679 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8680 SCEV::FlagNUW); 8681 Pred = ICmpInst::ICMP_ULT; 8682 Changed = true; 8683 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8684 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8685 Pred = ICmpInst::ICMP_ULT; 8686 Changed = true; 8687 } 8688 break; 8689 case ICmpInst::ICMP_UGE: 8690 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8691 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8692 Pred = ICmpInst::ICMP_UGT; 8693 Changed = true; 8694 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8695 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8696 SCEV::FlagNUW); 8697 Pred = ICmpInst::ICMP_UGT; 8698 Changed = true; 8699 } 8700 break; 8701 default: 8702 break; 8703 } 8704 8705 // TODO: More simplifications are possible here. 8706 8707 // Recursively simplify until we either hit a recursion limit or nothing 8708 // changes. 8709 if (Changed) 8710 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8711 8712 return Changed; 8713 8714 trivially_true: 8715 // Return 0 == 0. 8716 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8717 Pred = ICmpInst::ICMP_EQ; 8718 return true; 8719 8720 trivially_false: 8721 // Return 0 != 0. 8722 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8723 Pred = ICmpInst::ICMP_NE; 8724 return true; 8725 } 8726 8727 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8728 return getSignedRangeMax(S).isNegative(); 8729 } 8730 8731 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8732 return getSignedRangeMin(S).isStrictlyPositive(); 8733 } 8734 8735 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8736 return !getSignedRangeMin(S).isNegative(); 8737 } 8738 8739 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8740 return !getSignedRangeMax(S).isStrictlyPositive(); 8741 } 8742 8743 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8744 return isKnownNegative(S) || isKnownPositive(S); 8745 } 8746 8747 std::pair<const SCEV *, const SCEV *> 8748 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8749 // Compute SCEV on entry of loop L. 8750 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8751 if (Start == getCouldNotCompute()) 8752 return { Start, Start }; 8753 // Compute post increment SCEV for loop L. 8754 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8755 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8756 return { Start, PostInc }; 8757 } 8758 8759 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8760 const SCEV *LHS, const SCEV *RHS) { 8761 // First collect all loops. 8762 SmallPtrSet<const Loop *, 8> LoopsUsed; 8763 getUsedLoops(LHS, LoopsUsed); 8764 getUsedLoops(RHS, LoopsUsed); 8765 8766 if (LoopsUsed.empty()) 8767 return false; 8768 8769 // Domination relationship must be a linear order on collected loops. 8770 #ifndef NDEBUG 8771 for (auto *L1 : LoopsUsed) 8772 for (auto *L2 : LoopsUsed) 8773 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8774 DT.dominates(L2->getHeader(), L1->getHeader())) && 8775 "Domination relationship is not a linear order"); 8776 #endif 8777 8778 const Loop *MDL = 8779 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8780 [&](const Loop *L1, const Loop *L2) { 8781 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 8782 }); 8783 8784 // Get init and post increment value for LHS. 8785 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 8786 // if LHS contains unknown non-invariant SCEV then bail out. 8787 if (SplitLHS.first == getCouldNotCompute()) 8788 return false; 8789 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 8790 // Get init and post increment value for RHS. 8791 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 8792 // if RHS contains unknown non-invariant SCEV then bail out. 8793 if (SplitRHS.first == getCouldNotCompute()) 8794 return false; 8795 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 8796 // It is possible that init SCEV contains an invariant load but it does 8797 // not dominate MDL and is not available at MDL loop entry, so we should 8798 // check it here. 8799 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 8800 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 8801 return false; 8802 8803 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 8804 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 8805 SplitRHS.second); 8806 } 8807 8808 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8809 const SCEV *LHS, const SCEV *RHS) { 8810 // Canonicalize the inputs first. 8811 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8812 8813 if (isKnownViaInduction(Pred, LHS, RHS)) 8814 return true; 8815 8816 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8817 return true; 8818 8819 // Otherwise see what can be done with some simple reasoning. 8820 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 8821 } 8822 8823 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 8824 const SCEVAddRecExpr *LHS, 8825 const SCEV *RHS) { 8826 const Loop *L = LHS->getLoop(); 8827 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 8828 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 8829 } 8830 8831 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8832 ICmpInst::Predicate Pred, 8833 bool &Increasing) { 8834 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8835 8836 #ifndef NDEBUG 8837 // Verify an invariant: inverting the predicate should turn a monotonically 8838 // increasing change to a monotonically decreasing one, and vice versa. 8839 bool IncreasingSwapped; 8840 bool ResultSwapped = isMonotonicPredicateImpl( 8841 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8842 8843 assert(Result == ResultSwapped && "should be able to analyze both!"); 8844 if (ResultSwapped) 8845 assert(Increasing == !IncreasingSwapped && 8846 "monotonicity should flip as we flip the predicate"); 8847 #endif 8848 8849 return Result; 8850 } 8851 8852 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8853 ICmpInst::Predicate Pred, 8854 bool &Increasing) { 8855 8856 // A zero step value for LHS means the induction variable is essentially a 8857 // loop invariant value. We don't really depend on the predicate actually 8858 // flipping from false to true (for increasing predicates, and the other way 8859 // around for decreasing predicates), all we care about is that *if* the 8860 // predicate changes then it only changes from false to true. 8861 // 8862 // A zero step value in itself is not very useful, but there may be places 8863 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8864 // as general as possible. 8865 8866 switch (Pred) { 8867 default: 8868 return false; // Conservative answer 8869 8870 case ICmpInst::ICMP_UGT: 8871 case ICmpInst::ICMP_UGE: 8872 case ICmpInst::ICMP_ULT: 8873 case ICmpInst::ICMP_ULE: 8874 if (!LHS->hasNoUnsignedWrap()) 8875 return false; 8876 8877 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8878 return true; 8879 8880 case ICmpInst::ICMP_SGT: 8881 case ICmpInst::ICMP_SGE: 8882 case ICmpInst::ICMP_SLT: 8883 case ICmpInst::ICMP_SLE: { 8884 if (!LHS->hasNoSignedWrap()) 8885 return false; 8886 8887 const SCEV *Step = LHS->getStepRecurrence(*this); 8888 8889 if (isKnownNonNegative(Step)) { 8890 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8891 return true; 8892 } 8893 8894 if (isKnownNonPositive(Step)) { 8895 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8896 return true; 8897 } 8898 8899 return false; 8900 } 8901 8902 } 8903 8904 llvm_unreachable("switch has default clause!"); 8905 } 8906 8907 bool ScalarEvolution::isLoopInvariantPredicate( 8908 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8909 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8910 const SCEV *&InvariantRHS) { 8911 8912 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8913 if (!isLoopInvariant(RHS, L)) { 8914 if (!isLoopInvariant(LHS, L)) 8915 return false; 8916 8917 std::swap(LHS, RHS); 8918 Pred = ICmpInst::getSwappedPredicate(Pred); 8919 } 8920 8921 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8922 if (!ArLHS || ArLHS->getLoop() != L) 8923 return false; 8924 8925 bool Increasing; 8926 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8927 return false; 8928 8929 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8930 // true as the loop iterates, and the backedge is control dependent on 8931 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8932 // 8933 // * if the predicate was false in the first iteration then the predicate 8934 // is never evaluated again, since the loop exits without taking the 8935 // backedge. 8936 // * if the predicate was true in the first iteration then it will 8937 // continue to be true for all future iterations since it is 8938 // monotonically increasing. 8939 // 8940 // For both the above possibilities, we can replace the loop varying 8941 // predicate with its value on the first iteration of the loop (which is 8942 // loop invariant). 8943 // 8944 // A similar reasoning applies for a monotonically decreasing predicate, by 8945 // replacing true with false and false with true in the above two bullets. 8946 8947 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8948 8949 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8950 return false; 8951 8952 InvariantPred = Pred; 8953 InvariantLHS = ArLHS->getStart(); 8954 InvariantRHS = RHS; 8955 return true; 8956 } 8957 8958 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8959 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8960 if (HasSameValue(LHS, RHS)) 8961 return ICmpInst::isTrueWhenEqual(Pred); 8962 8963 // This code is split out from isKnownPredicate because it is called from 8964 // within isLoopEntryGuardedByCond. 8965 8966 auto CheckRanges = 8967 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8968 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8969 .contains(RangeLHS); 8970 }; 8971 8972 // The check at the top of the function catches the case where the values are 8973 // known to be equal. 8974 if (Pred == CmpInst::ICMP_EQ) 8975 return false; 8976 8977 if (Pred == CmpInst::ICMP_NE) 8978 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8979 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8980 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8981 8982 if (CmpInst::isSigned(Pred)) 8983 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8984 8985 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8986 } 8987 8988 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8989 const SCEV *LHS, 8990 const SCEV *RHS) { 8991 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8992 // Return Y via OutY. 8993 auto MatchBinaryAddToConst = 8994 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8995 SCEV::NoWrapFlags ExpectedFlags) { 8996 const SCEV *NonConstOp, *ConstOp; 8997 SCEV::NoWrapFlags FlagsPresent; 8998 8999 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9000 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9001 return false; 9002 9003 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9004 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9005 }; 9006 9007 APInt C; 9008 9009 switch (Pred) { 9010 default: 9011 break; 9012 9013 case ICmpInst::ICMP_SGE: 9014 std::swap(LHS, RHS); 9015 LLVM_FALLTHROUGH; 9016 case ICmpInst::ICMP_SLE: 9017 // X s<= (X + C)<nsw> if C >= 0 9018 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9019 return true; 9020 9021 // (X + C)<nsw> s<= X if C <= 0 9022 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9023 !C.isStrictlyPositive()) 9024 return true; 9025 break; 9026 9027 case ICmpInst::ICMP_SGT: 9028 std::swap(LHS, RHS); 9029 LLVM_FALLTHROUGH; 9030 case ICmpInst::ICMP_SLT: 9031 // X s< (X + C)<nsw> if C > 0 9032 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9033 C.isStrictlyPositive()) 9034 return true; 9035 9036 // (X + C)<nsw> s< X if C < 0 9037 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9038 return true; 9039 break; 9040 } 9041 9042 return false; 9043 } 9044 9045 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9046 const SCEV *LHS, 9047 const SCEV *RHS) { 9048 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9049 return false; 9050 9051 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9052 // the stack can result in exponential time complexity. 9053 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9054 9055 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9056 // 9057 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9058 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9059 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9060 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9061 // use isKnownPredicate later if needed. 9062 return isKnownNonNegative(RHS) && 9063 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9064 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9065 } 9066 9067 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9068 ICmpInst::Predicate Pred, 9069 const SCEV *LHS, const SCEV *RHS) { 9070 // No need to even try if we know the module has no guards. 9071 if (!HasGuards) 9072 return false; 9073 9074 return any_of(*BB, [&](Instruction &I) { 9075 using namespace llvm::PatternMatch; 9076 9077 Value *Condition; 9078 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9079 m_Value(Condition))) && 9080 isImpliedCond(Pred, LHS, RHS, Condition, false); 9081 }); 9082 } 9083 9084 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9085 /// protected by a conditional between LHS and RHS. This is used to 9086 /// to eliminate casts. 9087 bool 9088 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9089 ICmpInst::Predicate Pred, 9090 const SCEV *LHS, const SCEV *RHS) { 9091 // Interpret a null as meaning no loop, where there is obviously no guard 9092 // (interprocedural conditions notwithstanding). 9093 if (!L) return true; 9094 9095 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9096 return true; 9097 9098 BasicBlock *Latch = L->getLoopLatch(); 9099 if (!Latch) 9100 return false; 9101 9102 BranchInst *LoopContinuePredicate = 9103 dyn_cast<BranchInst>(Latch->getTerminator()); 9104 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9105 isImpliedCond(Pred, LHS, RHS, 9106 LoopContinuePredicate->getCondition(), 9107 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9108 return true; 9109 9110 // We don't want more than one activation of the following loops on the stack 9111 // -- that can lead to O(n!) time complexity. 9112 if (WalkingBEDominatingConds) 9113 return false; 9114 9115 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9116 9117 // See if we can exploit a trip count to prove the predicate. 9118 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9119 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9120 if (LatchBECount != getCouldNotCompute()) { 9121 // We know that Latch branches back to the loop header exactly 9122 // LatchBECount times. This means the backdege condition at Latch is 9123 // equivalent to "{0,+,1} u< LatchBECount". 9124 Type *Ty = LatchBECount->getType(); 9125 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9126 const SCEV *LoopCounter = 9127 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9128 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9129 LatchBECount)) 9130 return true; 9131 } 9132 9133 // Check conditions due to any @llvm.assume intrinsics. 9134 for (auto &AssumeVH : AC.assumptions()) { 9135 if (!AssumeVH) 9136 continue; 9137 auto *CI = cast<CallInst>(AssumeVH); 9138 if (!DT.dominates(CI, Latch->getTerminator())) 9139 continue; 9140 9141 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9142 return true; 9143 } 9144 9145 // If the loop is not reachable from the entry block, we risk running into an 9146 // infinite loop as we walk up into the dom tree. These loops do not matter 9147 // anyway, so we just return a conservative answer when we see them. 9148 if (!DT.isReachableFromEntry(L->getHeader())) 9149 return false; 9150 9151 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9152 return true; 9153 9154 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9155 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9156 assert(DTN && "should reach the loop header before reaching the root!"); 9157 9158 BasicBlock *BB = DTN->getBlock(); 9159 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9160 return true; 9161 9162 BasicBlock *PBB = BB->getSinglePredecessor(); 9163 if (!PBB) 9164 continue; 9165 9166 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9167 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9168 continue; 9169 9170 Value *Condition = ContinuePredicate->getCondition(); 9171 9172 // If we have an edge `E` within the loop body that dominates the only 9173 // latch, the condition guarding `E` also guards the backedge. This 9174 // reasoning works only for loops with a single latch. 9175 9176 BasicBlockEdge DominatingEdge(PBB, BB); 9177 if (DominatingEdge.isSingleEdge()) { 9178 // We're constructively (and conservatively) enumerating edges within the 9179 // loop body that dominate the latch. The dominator tree better agree 9180 // with us on this: 9181 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9182 9183 if (isImpliedCond(Pred, LHS, RHS, Condition, 9184 BB != ContinuePredicate->getSuccessor(0))) 9185 return true; 9186 } 9187 } 9188 9189 return false; 9190 } 9191 9192 bool 9193 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9194 ICmpInst::Predicate Pred, 9195 const SCEV *LHS, const SCEV *RHS) { 9196 // Interpret a null as meaning no loop, where there is obviously no guard 9197 // (interprocedural conditions notwithstanding). 9198 if (!L) return false; 9199 9200 // Both LHS and RHS must be available at loop entry. 9201 assert(isAvailableAtLoopEntry(LHS, L) && 9202 "LHS is not available at Loop Entry"); 9203 assert(isAvailableAtLoopEntry(RHS, L) && 9204 "RHS is not available at Loop Entry"); 9205 9206 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9207 return true; 9208 9209 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9210 // the facts (a >= b && a != b) separately. A typical situation is when the 9211 // non-strict comparison is known from ranges and non-equality is known from 9212 // dominating predicates. If we are proving strict comparison, we always try 9213 // to prove non-equality and non-strict comparison separately. 9214 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9215 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9216 bool ProvedNonStrictComparison = false; 9217 bool ProvedNonEquality = false; 9218 9219 if (ProvingStrictComparison) { 9220 ProvedNonStrictComparison = 9221 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9222 ProvedNonEquality = 9223 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9224 if (ProvedNonStrictComparison && ProvedNonEquality) 9225 return true; 9226 } 9227 9228 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9229 auto ProveViaGuard = [&](BasicBlock *Block) { 9230 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9231 return true; 9232 if (ProvingStrictComparison) { 9233 if (!ProvedNonStrictComparison) 9234 ProvedNonStrictComparison = 9235 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9236 if (!ProvedNonEquality) 9237 ProvedNonEquality = 9238 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9239 if (ProvedNonStrictComparison && ProvedNonEquality) 9240 return true; 9241 } 9242 return false; 9243 }; 9244 9245 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9246 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9247 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9248 return true; 9249 if (ProvingStrictComparison) { 9250 if (!ProvedNonStrictComparison) 9251 ProvedNonStrictComparison = 9252 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9253 if (!ProvedNonEquality) 9254 ProvedNonEquality = 9255 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9256 if (ProvedNonStrictComparison && ProvedNonEquality) 9257 return true; 9258 } 9259 return false; 9260 }; 9261 9262 // Starting at the loop predecessor, climb up the predecessor chain, as long 9263 // as there are predecessors that can be found that have unique successors 9264 // leading to the original header. 9265 for (std::pair<BasicBlock *, BasicBlock *> 9266 Pair(L->getLoopPredecessor(), L->getHeader()); 9267 Pair.first; 9268 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9269 9270 if (ProveViaGuard(Pair.first)) 9271 return true; 9272 9273 BranchInst *LoopEntryPredicate = 9274 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9275 if (!LoopEntryPredicate || 9276 LoopEntryPredicate->isUnconditional()) 9277 continue; 9278 9279 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9280 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9281 return true; 9282 } 9283 9284 // Check conditions due to any @llvm.assume intrinsics. 9285 for (auto &AssumeVH : AC.assumptions()) { 9286 if (!AssumeVH) 9287 continue; 9288 auto *CI = cast<CallInst>(AssumeVH); 9289 if (!DT.dominates(CI, L->getHeader())) 9290 continue; 9291 9292 if (ProveViaCond(CI->getArgOperand(0), false)) 9293 return true; 9294 } 9295 9296 return false; 9297 } 9298 9299 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9300 const SCEV *LHS, const SCEV *RHS, 9301 Value *FoundCondValue, 9302 bool Inverse) { 9303 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9304 return false; 9305 9306 auto ClearOnExit = 9307 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9308 9309 // Recursively handle And and Or conditions. 9310 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9311 if (BO->getOpcode() == Instruction::And) { 9312 if (!Inverse) 9313 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9314 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9315 } else if (BO->getOpcode() == Instruction::Or) { 9316 if (Inverse) 9317 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9318 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9319 } 9320 } 9321 9322 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9323 if (!ICI) return false; 9324 9325 // Now that we found a conditional branch that dominates the loop or controls 9326 // the loop latch. Check to see if it is the comparison we are looking for. 9327 ICmpInst::Predicate FoundPred; 9328 if (Inverse) 9329 FoundPred = ICI->getInversePredicate(); 9330 else 9331 FoundPred = ICI->getPredicate(); 9332 9333 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9334 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9335 9336 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9337 } 9338 9339 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9340 const SCEV *RHS, 9341 ICmpInst::Predicate FoundPred, 9342 const SCEV *FoundLHS, 9343 const SCEV *FoundRHS) { 9344 // Balance the types. 9345 if (getTypeSizeInBits(LHS->getType()) < 9346 getTypeSizeInBits(FoundLHS->getType())) { 9347 if (CmpInst::isSigned(Pred)) { 9348 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9349 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9350 } else { 9351 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9352 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9353 } 9354 } else if (getTypeSizeInBits(LHS->getType()) > 9355 getTypeSizeInBits(FoundLHS->getType())) { 9356 if (CmpInst::isSigned(FoundPred)) { 9357 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9358 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9359 } else { 9360 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9361 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9362 } 9363 } 9364 9365 // Canonicalize the query to match the way instcombine will have 9366 // canonicalized the comparison. 9367 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9368 if (LHS == RHS) 9369 return CmpInst::isTrueWhenEqual(Pred); 9370 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9371 if (FoundLHS == FoundRHS) 9372 return CmpInst::isFalseWhenEqual(FoundPred); 9373 9374 // Check to see if we can make the LHS or RHS match. 9375 if (LHS == FoundRHS || RHS == FoundLHS) { 9376 if (isa<SCEVConstant>(RHS)) { 9377 std::swap(FoundLHS, FoundRHS); 9378 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9379 } else { 9380 std::swap(LHS, RHS); 9381 Pred = ICmpInst::getSwappedPredicate(Pred); 9382 } 9383 } 9384 9385 // Check whether the found predicate is the same as the desired predicate. 9386 if (FoundPred == Pred) 9387 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9388 9389 // Check whether swapping the found predicate makes it the same as the 9390 // desired predicate. 9391 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9392 if (isa<SCEVConstant>(RHS)) 9393 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9394 else 9395 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9396 RHS, LHS, FoundLHS, FoundRHS); 9397 } 9398 9399 // Unsigned comparison is the same as signed comparison when both the operands 9400 // are non-negative. 9401 if (CmpInst::isUnsigned(FoundPred) && 9402 CmpInst::getSignedPredicate(FoundPred) == Pred && 9403 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9404 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9405 9406 // Check if we can make progress by sharpening ranges. 9407 if (FoundPred == ICmpInst::ICMP_NE && 9408 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9409 9410 const SCEVConstant *C = nullptr; 9411 const SCEV *V = nullptr; 9412 9413 if (isa<SCEVConstant>(FoundLHS)) { 9414 C = cast<SCEVConstant>(FoundLHS); 9415 V = FoundRHS; 9416 } else { 9417 C = cast<SCEVConstant>(FoundRHS); 9418 V = FoundLHS; 9419 } 9420 9421 // The guarding predicate tells us that C != V. If the known range 9422 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9423 // range we consider has to correspond to same signedness as the 9424 // predicate we're interested in folding. 9425 9426 APInt Min = ICmpInst::isSigned(Pred) ? 9427 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9428 9429 if (Min == C->getAPInt()) { 9430 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9431 // This is true even if (Min + 1) wraps around -- in case of 9432 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9433 9434 APInt SharperMin = Min + 1; 9435 9436 switch (Pred) { 9437 case ICmpInst::ICMP_SGE: 9438 case ICmpInst::ICMP_UGE: 9439 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9440 // RHS, we're done. 9441 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9442 getConstant(SharperMin))) 9443 return true; 9444 LLVM_FALLTHROUGH; 9445 9446 case ICmpInst::ICMP_SGT: 9447 case ICmpInst::ICMP_UGT: 9448 // We know from the range information that (V `Pred` Min || 9449 // V == Min). We know from the guarding condition that !(V 9450 // == Min). This gives us 9451 // 9452 // V `Pred` Min || V == Min && !(V == Min) 9453 // => V `Pred` Min 9454 // 9455 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9456 9457 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9458 return true; 9459 LLVM_FALLTHROUGH; 9460 9461 default: 9462 // No change 9463 break; 9464 } 9465 } 9466 } 9467 9468 // Check whether the actual condition is beyond sufficient. 9469 if (FoundPred == ICmpInst::ICMP_EQ) 9470 if (ICmpInst::isTrueWhenEqual(Pred)) 9471 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9472 return true; 9473 if (Pred == ICmpInst::ICMP_NE) 9474 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9475 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9476 return true; 9477 9478 // Otherwise assume the worst. 9479 return false; 9480 } 9481 9482 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9483 const SCEV *&L, const SCEV *&R, 9484 SCEV::NoWrapFlags &Flags) { 9485 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9486 if (!AE || AE->getNumOperands() != 2) 9487 return false; 9488 9489 L = AE->getOperand(0); 9490 R = AE->getOperand(1); 9491 Flags = AE->getNoWrapFlags(); 9492 return true; 9493 } 9494 9495 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9496 const SCEV *Less) { 9497 // We avoid subtracting expressions here because this function is usually 9498 // fairly deep in the call stack (i.e. is called many times). 9499 9500 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9501 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9502 const auto *MAR = cast<SCEVAddRecExpr>(More); 9503 9504 if (LAR->getLoop() != MAR->getLoop()) 9505 return None; 9506 9507 // We look at affine expressions only; not for correctness but to keep 9508 // getStepRecurrence cheap. 9509 if (!LAR->isAffine() || !MAR->isAffine()) 9510 return None; 9511 9512 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9513 return None; 9514 9515 Less = LAR->getStart(); 9516 More = MAR->getStart(); 9517 9518 // fall through 9519 } 9520 9521 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9522 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9523 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9524 return M - L; 9525 } 9526 9527 SCEV::NoWrapFlags Flags; 9528 const SCEV *LLess = nullptr, *RLess = nullptr; 9529 const SCEV *LMore = nullptr, *RMore = nullptr; 9530 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9531 // Compare (X + C1) vs X. 9532 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9533 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9534 if (RLess == More) 9535 return -(C1->getAPInt()); 9536 9537 // Compare X vs (X + C2). 9538 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9539 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9540 if (RMore == Less) 9541 return C2->getAPInt(); 9542 9543 // Compare (X + C1) vs (X + C2). 9544 if (C1 && C2 && RLess == RMore) 9545 return C2->getAPInt() - C1->getAPInt(); 9546 9547 return None; 9548 } 9549 9550 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9551 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9552 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9553 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9554 return false; 9555 9556 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9557 if (!AddRecLHS) 9558 return false; 9559 9560 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9561 if (!AddRecFoundLHS) 9562 return false; 9563 9564 // We'd like to let SCEV reason about control dependencies, so we constrain 9565 // both the inequalities to be about add recurrences on the same loop. This 9566 // way we can use isLoopEntryGuardedByCond later. 9567 9568 const Loop *L = AddRecFoundLHS->getLoop(); 9569 if (L != AddRecLHS->getLoop()) 9570 return false; 9571 9572 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9573 // 9574 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9575 // ... (2) 9576 // 9577 // Informal proof for (2), assuming (1) [*]: 9578 // 9579 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9580 // 9581 // Then 9582 // 9583 // FoundLHS s< FoundRHS s< INT_MIN - C 9584 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9585 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9586 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9587 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9588 // <=> FoundLHS + C s< FoundRHS + C 9589 // 9590 // [*]: (1) can be proved by ruling out overflow. 9591 // 9592 // [**]: This can be proved by analyzing all the four possibilities: 9593 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9594 // (A s>= 0, B s>= 0). 9595 // 9596 // Note: 9597 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9598 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9599 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9600 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9601 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9602 // C)". 9603 9604 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9605 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9606 if (!LDiff || !RDiff || *LDiff != *RDiff) 9607 return false; 9608 9609 if (LDiff->isMinValue()) 9610 return true; 9611 9612 APInt FoundRHSLimit; 9613 9614 if (Pred == CmpInst::ICMP_ULT) { 9615 FoundRHSLimit = -(*RDiff); 9616 } else { 9617 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9618 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9619 } 9620 9621 // Try to prove (1) or (2), as needed. 9622 return isAvailableAtLoopEntry(FoundRHS, L) && 9623 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9624 getConstant(FoundRHSLimit)); 9625 } 9626 9627 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9628 const SCEV *LHS, const SCEV *RHS, 9629 const SCEV *FoundLHS, 9630 const SCEV *FoundRHS, unsigned Depth) { 9631 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9632 9633 auto ClearOnExit = make_scope_exit([&]() { 9634 if (LPhi) { 9635 bool Erased = PendingMerges.erase(LPhi); 9636 assert(Erased && "Failed to erase LPhi!"); 9637 (void)Erased; 9638 } 9639 if (RPhi) { 9640 bool Erased = PendingMerges.erase(RPhi); 9641 assert(Erased && "Failed to erase RPhi!"); 9642 (void)Erased; 9643 } 9644 }); 9645 9646 // Find respective Phis and check that they are not being pending. 9647 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9648 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9649 if (!PendingMerges.insert(Phi).second) 9650 return false; 9651 LPhi = Phi; 9652 } 9653 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9654 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9655 // If we detect a loop of Phi nodes being processed by this method, for 9656 // example: 9657 // 9658 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9659 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9660 // 9661 // we don't want to deal with a case that complex, so return conservative 9662 // answer false. 9663 if (!PendingMerges.insert(Phi).second) 9664 return false; 9665 RPhi = Phi; 9666 } 9667 9668 // If none of LHS, RHS is a Phi, nothing to do here. 9669 if (!LPhi && !RPhi) 9670 return false; 9671 9672 // If there is a SCEVUnknown Phi we are interested in, make it left. 9673 if (!LPhi) { 9674 std::swap(LHS, RHS); 9675 std::swap(FoundLHS, FoundRHS); 9676 std::swap(LPhi, RPhi); 9677 Pred = ICmpInst::getSwappedPredicate(Pred); 9678 } 9679 9680 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9681 const BasicBlock *LBB = LPhi->getParent(); 9682 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9683 9684 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9685 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9686 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9687 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9688 }; 9689 9690 if (RPhi && RPhi->getParent() == LBB) { 9691 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9692 // If we compare two Phis from the same block, and for each entry block 9693 // the predicate is true for incoming values from this block, then the 9694 // predicate is also true for the Phis. 9695 for (const BasicBlock *IncBB : predecessors(LBB)) { 9696 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9697 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9698 if (!ProvedEasily(L, R)) 9699 return false; 9700 } 9701 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9702 // Case two: RHS is also a Phi from the same basic block, and it is an 9703 // AddRec. It means that there is a loop which has both AddRec and Unknown 9704 // PHIs, for it we can compare incoming values of AddRec from above the loop 9705 // and latch with their respective incoming values of LPhi. 9706 // TODO: Generalize to handle loops with many inputs in a header. 9707 if (LPhi->getNumIncomingValues() != 2) return false; 9708 9709 auto *RLoop = RAR->getLoop(); 9710 auto *Predecessor = RLoop->getLoopPredecessor(); 9711 assert(Predecessor && "Loop with AddRec with no predecessor?"); 9712 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 9713 if (!ProvedEasily(L1, RAR->getStart())) 9714 return false; 9715 auto *Latch = RLoop->getLoopLatch(); 9716 assert(Latch && "Loop with AddRec with no latch?"); 9717 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 9718 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 9719 return false; 9720 } else { 9721 // In all other cases go over inputs of LHS and compare each of them to RHS, 9722 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 9723 // At this point RHS is either a non-Phi, or it is a Phi from some block 9724 // different from LBB. 9725 for (const BasicBlock *IncBB : predecessors(LBB)) { 9726 // Check that RHS is available in this block. 9727 if (!dominates(RHS, IncBB)) 9728 return false; 9729 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9730 if (!ProvedEasily(L, RHS)) 9731 return false; 9732 } 9733 } 9734 return true; 9735 } 9736 9737 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9738 const SCEV *LHS, const SCEV *RHS, 9739 const SCEV *FoundLHS, 9740 const SCEV *FoundRHS) { 9741 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9742 return true; 9743 9744 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9745 return true; 9746 9747 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9748 FoundLHS, FoundRHS) || 9749 // ~x < ~y --> x > y 9750 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9751 getNotSCEV(FoundRHS), 9752 getNotSCEV(FoundLHS)); 9753 } 9754 9755 /// If Expr computes ~A, return A else return nullptr 9756 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9757 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9758 if (!Add || Add->getNumOperands() != 2 || 9759 !Add->getOperand(0)->isAllOnesValue()) 9760 return nullptr; 9761 9762 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9763 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9764 !AddRHS->getOperand(0)->isAllOnesValue()) 9765 return nullptr; 9766 9767 return AddRHS->getOperand(1); 9768 } 9769 9770 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9771 template<typename MaxExprType> 9772 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9773 const SCEV *Candidate) { 9774 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9775 if (!MaxExpr) return false; 9776 9777 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9778 } 9779 9780 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9781 template<typename MaxExprType> 9782 static bool IsMinConsistingOf(ScalarEvolution &SE, 9783 const SCEV *MaybeMinExpr, 9784 const SCEV *Candidate) { 9785 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9786 if (!MaybeMaxExpr) 9787 return false; 9788 9789 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9790 } 9791 9792 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9793 ICmpInst::Predicate Pred, 9794 const SCEV *LHS, const SCEV *RHS) { 9795 // If both sides are affine addrecs for the same loop, with equal 9796 // steps, and we know the recurrences don't wrap, then we only 9797 // need to check the predicate on the starting values. 9798 9799 if (!ICmpInst::isRelational(Pred)) 9800 return false; 9801 9802 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9803 if (!LAR) 9804 return false; 9805 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9806 if (!RAR) 9807 return false; 9808 if (LAR->getLoop() != RAR->getLoop()) 9809 return false; 9810 if (!LAR->isAffine() || !RAR->isAffine()) 9811 return false; 9812 9813 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9814 return false; 9815 9816 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9817 SCEV::FlagNSW : SCEV::FlagNUW; 9818 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9819 return false; 9820 9821 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9822 } 9823 9824 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9825 /// expression? 9826 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9827 ICmpInst::Predicate Pred, 9828 const SCEV *LHS, const SCEV *RHS) { 9829 switch (Pred) { 9830 default: 9831 return false; 9832 9833 case ICmpInst::ICMP_SGE: 9834 std::swap(LHS, RHS); 9835 LLVM_FALLTHROUGH; 9836 case ICmpInst::ICMP_SLE: 9837 return 9838 // min(A, ...) <= A 9839 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9840 // A <= max(A, ...) 9841 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9842 9843 case ICmpInst::ICMP_UGE: 9844 std::swap(LHS, RHS); 9845 LLVM_FALLTHROUGH; 9846 case ICmpInst::ICMP_ULE: 9847 return 9848 // min(A, ...) <= A 9849 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9850 // A <= max(A, ...) 9851 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9852 } 9853 9854 llvm_unreachable("covered switch fell through?!"); 9855 } 9856 9857 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9858 const SCEV *LHS, const SCEV *RHS, 9859 const SCEV *FoundLHS, 9860 const SCEV *FoundRHS, 9861 unsigned Depth) { 9862 assert(getTypeSizeInBits(LHS->getType()) == 9863 getTypeSizeInBits(RHS->getType()) && 9864 "LHS and RHS have different sizes?"); 9865 assert(getTypeSizeInBits(FoundLHS->getType()) == 9866 getTypeSizeInBits(FoundRHS->getType()) && 9867 "FoundLHS and FoundRHS have different sizes?"); 9868 // We want to avoid hurting the compile time with analysis of too big trees. 9869 if (Depth > MaxSCEVOperationsImplicationDepth) 9870 return false; 9871 // We only want to work with ICMP_SGT comparison so far. 9872 // TODO: Extend to ICMP_UGT? 9873 if (Pred == ICmpInst::ICMP_SLT) { 9874 Pred = ICmpInst::ICMP_SGT; 9875 std::swap(LHS, RHS); 9876 std::swap(FoundLHS, FoundRHS); 9877 } 9878 if (Pred != ICmpInst::ICMP_SGT) 9879 return false; 9880 9881 auto GetOpFromSExt = [&](const SCEV *S) { 9882 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9883 return Ext->getOperand(); 9884 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9885 // the constant in some cases. 9886 return S; 9887 }; 9888 9889 // Acquire values from extensions. 9890 auto *OrigLHS = LHS; 9891 auto *OrigFoundLHS = FoundLHS; 9892 LHS = GetOpFromSExt(LHS); 9893 FoundLHS = GetOpFromSExt(FoundLHS); 9894 9895 // Is the SGT predicate can be proved trivially or using the found context. 9896 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9897 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9898 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9899 FoundRHS, Depth + 1); 9900 }; 9901 9902 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9903 // We want to avoid creation of any new non-constant SCEV. Since we are 9904 // going to compare the operands to RHS, we should be certain that we don't 9905 // need any size extensions for this. So let's decline all cases when the 9906 // sizes of types of LHS and RHS do not match. 9907 // TODO: Maybe try to get RHS from sext to catch more cases? 9908 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9909 return false; 9910 9911 // Should not overflow. 9912 if (!LHSAddExpr->hasNoSignedWrap()) 9913 return false; 9914 9915 auto *LL = LHSAddExpr->getOperand(0); 9916 auto *LR = LHSAddExpr->getOperand(1); 9917 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9918 9919 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9920 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9921 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9922 }; 9923 // Try to prove the following rule: 9924 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9925 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9926 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9927 return true; 9928 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9929 Value *LL, *LR; 9930 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9931 9932 using namespace llvm::PatternMatch; 9933 9934 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9935 // Rules for division. 9936 // We are going to perform some comparisons with Denominator and its 9937 // derivative expressions. In general case, creating a SCEV for it may 9938 // lead to a complex analysis of the entire graph, and in particular it 9939 // can request trip count recalculation for the same loop. This would 9940 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9941 // this, we only want to create SCEVs that are constants in this section. 9942 // So we bail if Denominator is not a constant. 9943 if (!isa<ConstantInt>(LR)) 9944 return false; 9945 9946 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9947 9948 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9949 // then a SCEV for the numerator already exists and matches with FoundLHS. 9950 auto *Numerator = getExistingSCEV(LL); 9951 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9952 return false; 9953 9954 // Make sure that the numerator matches with FoundLHS and the denominator 9955 // is positive. 9956 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9957 return false; 9958 9959 auto *DTy = Denominator->getType(); 9960 auto *FRHSTy = FoundRHS->getType(); 9961 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9962 // One of types is a pointer and another one is not. We cannot extend 9963 // them properly to a wider type, so let us just reject this case. 9964 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9965 // to avoid this check. 9966 return false; 9967 9968 // Given that: 9969 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9970 auto *WTy = getWiderType(DTy, FRHSTy); 9971 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9972 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9973 9974 // Try to prove the following rule: 9975 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9976 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9977 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9978 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9979 if (isKnownNonPositive(RHS) && 9980 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9981 return true; 9982 9983 // Try to prove the following rule: 9984 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9985 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9986 // If we divide it by Denominator > 2, then: 9987 // 1. If FoundLHS is negative, then the result is 0. 9988 // 2. If FoundLHS is non-negative, then the result is non-negative. 9989 // Anyways, the result is non-negative. 9990 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9991 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9992 if (isKnownNegative(RHS) && 9993 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9994 return true; 9995 } 9996 } 9997 9998 // If our expression contained SCEVUnknown Phis, and we split it down and now 9999 // need to prove something for them, try to prove the predicate for every 10000 // possible incoming values of those Phis. 10001 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10002 return true; 10003 10004 return false; 10005 } 10006 10007 bool 10008 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10009 const SCEV *LHS, const SCEV *RHS) { 10010 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10011 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10012 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10013 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10014 } 10015 10016 bool 10017 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10018 const SCEV *LHS, const SCEV *RHS, 10019 const SCEV *FoundLHS, 10020 const SCEV *FoundRHS) { 10021 switch (Pred) { 10022 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10023 case ICmpInst::ICMP_EQ: 10024 case ICmpInst::ICMP_NE: 10025 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10026 return true; 10027 break; 10028 case ICmpInst::ICMP_SLT: 10029 case ICmpInst::ICMP_SLE: 10030 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10031 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10032 return true; 10033 break; 10034 case ICmpInst::ICMP_SGT: 10035 case ICmpInst::ICMP_SGE: 10036 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10037 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10038 return true; 10039 break; 10040 case ICmpInst::ICMP_ULT: 10041 case ICmpInst::ICMP_ULE: 10042 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10043 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10044 return true; 10045 break; 10046 case ICmpInst::ICMP_UGT: 10047 case ICmpInst::ICMP_UGE: 10048 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10049 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10050 return true; 10051 break; 10052 } 10053 10054 // Maybe it can be proved via operations? 10055 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10056 return true; 10057 10058 return false; 10059 } 10060 10061 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10062 const SCEV *LHS, 10063 const SCEV *RHS, 10064 const SCEV *FoundLHS, 10065 const SCEV *FoundRHS) { 10066 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10067 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10068 // reduce the compile time impact of this optimization. 10069 return false; 10070 10071 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10072 if (!Addend) 10073 return false; 10074 10075 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10076 10077 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10078 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10079 ConstantRange FoundLHSRange = 10080 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10081 10082 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10083 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10084 10085 // We can also compute the range of values for `LHS` that satisfy the 10086 // consequent, "`LHS` `Pred` `RHS`": 10087 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10088 ConstantRange SatisfyingLHSRange = 10089 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10090 10091 // The antecedent implies the consequent if every value of `LHS` that 10092 // satisfies the antecedent also satisfies the consequent. 10093 return SatisfyingLHSRange.contains(LHSRange); 10094 } 10095 10096 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10097 bool IsSigned, bool NoWrap) { 10098 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10099 10100 if (NoWrap) return false; 10101 10102 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10103 const SCEV *One = getOne(Stride->getType()); 10104 10105 if (IsSigned) { 10106 APInt MaxRHS = getSignedRangeMax(RHS); 10107 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10108 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10109 10110 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10111 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10112 } 10113 10114 APInt MaxRHS = getUnsignedRangeMax(RHS); 10115 APInt MaxValue = APInt::getMaxValue(BitWidth); 10116 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10117 10118 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10119 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10120 } 10121 10122 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10123 bool IsSigned, bool NoWrap) { 10124 if (NoWrap) return false; 10125 10126 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10127 const SCEV *One = getOne(Stride->getType()); 10128 10129 if (IsSigned) { 10130 APInt MinRHS = getSignedRangeMin(RHS); 10131 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10132 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10133 10134 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10135 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10136 } 10137 10138 APInt MinRHS = getUnsignedRangeMin(RHS); 10139 APInt MinValue = APInt::getMinValue(BitWidth); 10140 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10141 10142 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10143 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10144 } 10145 10146 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10147 bool Equality) { 10148 const SCEV *One = getOne(Step->getType()); 10149 Delta = Equality ? getAddExpr(Delta, Step) 10150 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10151 return getUDivExpr(Delta, Step); 10152 } 10153 10154 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10155 const SCEV *Stride, 10156 const SCEV *End, 10157 unsigned BitWidth, 10158 bool IsSigned) { 10159 10160 assert(!isKnownNonPositive(Stride) && 10161 "Stride is expected strictly positive!"); 10162 // Calculate the maximum backedge count based on the range of values 10163 // permitted by Start, End, and Stride. 10164 const SCEV *MaxBECount; 10165 APInt MinStart = 10166 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10167 10168 APInt StrideForMaxBECount = 10169 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10170 10171 // We already know that the stride is positive, so we paper over conservatism 10172 // in our range computation by forcing StrideForMaxBECount to be at least one. 10173 // In theory this is unnecessary, but we expect MaxBECount to be a 10174 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10175 // is nothing to constant fold it to). 10176 APInt One(BitWidth, 1, IsSigned); 10177 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10178 10179 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10180 : APInt::getMaxValue(BitWidth); 10181 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10182 10183 // Although End can be a MAX expression we estimate MaxEnd considering only 10184 // the case End = RHS of the loop termination condition. This is safe because 10185 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10186 // taken count. 10187 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10188 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10189 10190 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10191 getConstant(StrideForMaxBECount) /* Step */, 10192 false /* Equality */); 10193 10194 return MaxBECount; 10195 } 10196 10197 ScalarEvolution::ExitLimit 10198 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10199 const Loop *L, bool IsSigned, 10200 bool ControlsExit, bool AllowPredicates) { 10201 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10202 10203 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10204 bool PredicatedIV = false; 10205 10206 if (!IV && AllowPredicates) { 10207 // Try to make this an AddRec using runtime tests, in the first X 10208 // iterations of this loop, where X is the SCEV expression found by the 10209 // algorithm below. 10210 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10211 PredicatedIV = true; 10212 } 10213 10214 // Avoid weird loops 10215 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10216 return getCouldNotCompute(); 10217 10218 bool NoWrap = ControlsExit && 10219 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10220 10221 const SCEV *Stride = IV->getStepRecurrence(*this); 10222 10223 bool PositiveStride = isKnownPositive(Stride); 10224 10225 // Avoid negative or zero stride values. 10226 if (!PositiveStride) { 10227 // We can compute the correct backedge taken count for loops with unknown 10228 // strides if we can prove that the loop is not an infinite loop with side 10229 // effects. Here's the loop structure we are trying to handle - 10230 // 10231 // i = start 10232 // do { 10233 // A[i] = i; 10234 // i += s; 10235 // } while (i < end); 10236 // 10237 // The backedge taken count for such loops is evaluated as - 10238 // (max(end, start + stride) - start - 1) /u stride 10239 // 10240 // The additional preconditions that we need to check to prove correctness 10241 // of the above formula is as follows - 10242 // 10243 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10244 // NoWrap flag). 10245 // b) loop is single exit with no side effects. 10246 // 10247 // 10248 // Precondition a) implies that if the stride is negative, this is a single 10249 // trip loop. The backedge taken count formula reduces to zero in this case. 10250 // 10251 // Precondition b) implies that the unknown stride cannot be zero otherwise 10252 // we have UB. 10253 // 10254 // The positive stride case is the same as isKnownPositive(Stride) returning 10255 // true (original behavior of the function). 10256 // 10257 // We want to make sure that the stride is truly unknown as there are edge 10258 // cases where ScalarEvolution propagates no wrap flags to the 10259 // post-increment/decrement IV even though the increment/decrement operation 10260 // itself is wrapping. The computed backedge taken count may be wrong in 10261 // such cases. This is prevented by checking that the stride is not known to 10262 // be either positive or non-positive. For example, no wrap flags are 10263 // propagated to the post-increment IV of this loop with a trip count of 2 - 10264 // 10265 // unsigned char i; 10266 // for(i=127; i<128; i+=129) 10267 // A[i] = i; 10268 // 10269 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10270 !loopHasNoSideEffects(L)) 10271 return getCouldNotCompute(); 10272 } else if (!Stride->isOne() && 10273 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10274 // Avoid proven overflow cases: this will ensure that the backedge taken 10275 // count will not generate any unsigned overflow. Relaxed no-overflow 10276 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10277 // undefined behaviors like the case of C language. 10278 return getCouldNotCompute(); 10279 10280 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10281 : ICmpInst::ICMP_ULT; 10282 const SCEV *Start = IV->getStart(); 10283 const SCEV *End = RHS; 10284 // When the RHS is not invariant, we do not know the end bound of the loop and 10285 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10286 // calculate the MaxBECount, given the start, stride and max value for the end 10287 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10288 // checked above). 10289 if (!isLoopInvariant(RHS, L)) { 10290 const SCEV *MaxBECount = computeMaxBECountForLT( 10291 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10292 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10293 false /*MaxOrZero*/, Predicates); 10294 } 10295 // If the backedge is taken at least once, then it will be taken 10296 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10297 // is the LHS value of the less-than comparison the first time it is evaluated 10298 // and End is the RHS. 10299 const SCEV *BECountIfBackedgeTaken = 10300 computeBECount(getMinusSCEV(End, Start), Stride, false); 10301 // If the loop entry is guarded by the result of the backedge test of the 10302 // first loop iteration, then we know the backedge will be taken at least 10303 // once and so the backedge taken count is as above. If not then we use the 10304 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10305 // as if the backedge is taken at least once max(End,Start) is End and so the 10306 // result is as above, and if not max(End,Start) is Start so we get a backedge 10307 // count of zero. 10308 const SCEV *BECount; 10309 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10310 BECount = BECountIfBackedgeTaken; 10311 else { 10312 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10313 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10314 } 10315 10316 const SCEV *MaxBECount; 10317 bool MaxOrZero = false; 10318 if (isa<SCEVConstant>(BECount)) 10319 MaxBECount = BECount; 10320 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10321 // If we know exactly how many times the backedge will be taken if it's 10322 // taken at least once, then the backedge count will either be that or 10323 // zero. 10324 MaxBECount = BECountIfBackedgeTaken; 10325 MaxOrZero = true; 10326 } else { 10327 MaxBECount = computeMaxBECountForLT( 10328 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10329 } 10330 10331 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10332 !isa<SCEVCouldNotCompute>(BECount)) 10333 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10334 10335 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10336 } 10337 10338 ScalarEvolution::ExitLimit 10339 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10340 const Loop *L, bool IsSigned, 10341 bool ControlsExit, bool AllowPredicates) { 10342 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10343 // We handle only IV > Invariant 10344 if (!isLoopInvariant(RHS, L)) 10345 return getCouldNotCompute(); 10346 10347 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10348 if (!IV && AllowPredicates) 10349 // Try to make this an AddRec using runtime tests, in the first X 10350 // iterations of this loop, where X is the SCEV expression found by the 10351 // algorithm below. 10352 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10353 10354 // Avoid weird loops 10355 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10356 return getCouldNotCompute(); 10357 10358 bool NoWrap = ControlsExit && 10359 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10360 10361 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10362 10363 // Avoid negative or zero stride values 10364 if (!isKnownPositive(Stride)) 10365 return getCouldNotCompute(); 10366 10367 // Avoid proven overflow cases: this will ensure that the backedge taken count 10368 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10369 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10370 // behaviors like the case of C language. 10371 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10372 return getCouldNotCompute(); 10373 10374 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10375 : ICmpInst::ICMP_UGT; 10376 10377 const SCEV *Start = IV->getStart(); 10378 const SCEV *End = RHS; 10379 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10380 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10381 10382 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10383 10384 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10385 : getUnsignedRangeMax(Start); 10386 10387 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10388 : getUnsignedRangeMin(Stride); 10389 10390 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10391 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10392 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10393 10394 // Although End can be a MIN expression we estimate MinEnd considering only 10395 // the case End = RHS. This is safe because in the other case (Start - End) 10396 // is zero, leading to a zero maximum backedge taken count. 10397 APInt MinEnd = 10398 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10399 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10400 10401 10402 const SCEV *MaxBECount = getCouldNotCompute(); 10403 if (isa<SCEVConstant>(BECount)) 10404 MaxBECount = BECount; 10405 else 10406 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10407 getConstant(MinStride), false); 10408 10409 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10410 MaxBECount = BECount; 10411 10412 return ExitLimit(BECount, MaxBECount, false, Predicates); 10413 } 10414 10415 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10416 ScalarEvolution &SE) const { 10417 if (Range.isFullSet()) // Infinite loop. 10418 return SE.getCouldNotCompute(); 10419 10420 // If the start is a non-zero constant, shift the range to simplify things. 10421 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10422 if (!SC->getValue()->isZero()) { 10423 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10424 Operands[0] = SE.getZero(SC->getType()); 10425 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10426 getNoWrapFlags(FlagNW)); 10427 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10428 return ShiftedAddRec->getNumIterationsInRange( 10429 Range.subtract(SC->getAPInt()), SE); 10430 // This is strange and shouldn't happen. 10431 return SE.getCouldNotCompute(); 10432 } 10433 10434 // The only time we can solve this is when we have all constant indices. 10435 // Otherwise, we cannot determine the overflow conditions. 10436 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10437 return SE.getCouldNotCompute(); 10438 10439 // Okay at this point we know that all elements of the chrec are constants and 10440 // that the start element is zero. 10441 10442 // First check to see if the range contains zero. If not, the first 10443 // iteration exits. 10444 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10445 if (!Range.contains(APInt(BitWidth, 0))) 10446 return SE.getZero(getType()); 10447 10448 if (isAffine()) { 10449 // If this is an affine expression then we have this situation: 10450 // Solve {0,+,A} in Range === Ax in Range 10451 10452 // We know that zero is in the range. If A is positive then we know that 10453 // the upper value of the range must be the first possible exit value. 10454 // If A is negative then the lower of the range is the last possible loop 10455 // value. Also note that we already checked for a full range. 10456 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10457 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10458 10459 // The exit value should be (End+A)/A. 10460 APInt ExitVal = (End + A).udiv(A); 10461 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10462 10463 // Evaluate at the exit value. If we really did fall out of the valid 10464 // range, then we computed our trip count, otherwise wrap around or other 10465 // things must have happened. 10466 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10467 if (Range.contains(Val->getValue())) 10468 return SE.getCouldNotCompute(); // Something strange happened 10469 10470 // Ensure that the previous value is in the range. This is a sanity check. 10471 assert(Range.contains( 10472 EvaluateConstantChrecAtConstant(this, 10473 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10474 "Linear scev computation is off in a bad way!"); 10475 return SE.getConstant(ExitValue); 10476 } else if (isQuadratic()) { 10477 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10478 // quadratic equation to solve it. To do this, we must frame our problem in 10479 // terms of figuring out when zero is crossed, instead of when 10480 // Range.getUpper() is crossed. 10481 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10482 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10483 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10484 10485 // Next, solve the constructed addrec 10486 if (auto Roots = 10487 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10488 const SCEVConstant *R1 = Roots->first; 10489 const SCEVConstant *R2 = Roots->second; 10490 // Pick the smallest positive root value. 10491 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10492 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10493 if (!CB->getZExtValue()) 10494 std::swap(R1, R2); // R1 is the minimum root now. 10495 10496 // Make sure the root is not off by one. The returned iteration should 10497 // not be in the range, but the previous one should be. When solving 10498 // for "X*X < 5", for example, we should not return a root of 2. 10499 ConstantInt *R1Val = 10500 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10501 if (Range.contains(R1Val->getValue())) { 10502 // The next iteration must be out of the range... 10503 ConstantInt *NextVal = 10504 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10505 10506 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10507 if (!Range.contains(R1Val->getValue())) 10508 return SE.getConstant(NextVal); 10509 return SE.getCouldNotCompute(); // Something strange happened 10510 } 10511 10512 // If R1 was not in the range, then it is a good return value. Make 10513 // sure that R1-1 WAS in the range though, just in case. 10514 ConstantInt *NextVal = 10515 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10516 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10517 if (Range.contains(R1Val->getValue())) 10518 return R1; 10519 return SE.getCouldNotCompute(); // Something strange happened 10520 } 10521 } 10522 } 10523 10524 return SE.getCouldNotCompute(); 10525 } 10526 10527 const SCEVAddRecExpr * 10528 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10529 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10530 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10531 // but in this case we cannot guarantee that the value returned will be an 10532 // AddRec because SCEV does not have a fixed point where it stops 10533 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10534 // may happen if we reach arithmetic depth limit while simplifying. So we 10535 // construct the returned value explicitly. 10536 SmallVector<const SCEV *, 3> Ops; 10537 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10538 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10539 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10540 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10541 // We know that the last operand is not a constant zero (otherwise it would 10542 // have been popped out earlier). This guarantees us that if the result has 10543 // the same last operand, then it will also not be popped out, meaning that 10544 // the returned value will be an AddRec. 10545 const SCEV *Last = getOperand(getNumOperands() - 1); 10546 assert(!Last->isZero() && "Recurrency with zero step?"); 10547 Ops.push_back(Last); 10548 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10549 SCEV::FlagAnyWrap)); 10550 } 10551 10552 // Return true when S contains at least an undef value. 10553 static inline bool containsUndefs(const SCEV *S) { 10554 return SCEVExprContains(S, [](const SCEV *S) { 10555 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10556 return isa<UndefValue>(SU->getValue()); 10557 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10558 return isa<UndefValue>(SC->getValue()); 10559 return false; 10560 }); 10561 } 10562 10563 namespace { 10564 10565 // Collect all steps of SCEV expressions. 10566 struct SCEVCollectStrides { 10567 ScalarEvolution &SE; 10568 SmallVectorImpl<const SCEV *> &Strides; 10569 10570 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10571 : SE(SE), Strides(S) {} 10572 10573 bool follow(const SCEV *S) { 10574 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10575 Strides.push_back(AR->getStepRecurrence(SE)); 10576 return true; 10577 } 10578 10579 bool isDone() const { return false; } 10580 }; 10581 10582 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10583 struct SCEVCollectTerms { 10584 SmallVectorImpl<const SCEV *> &Terms; 10585 10586 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10587 10588 bool follow(const SCEV *S) { 10589 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10590 isa<SCEVSignExtendExpr>(S)) { 10591 if (!containsUndefs(S)) 10592 Terms.push_back(S); 10593 10594 // Stop recursion: once we collected a term, do not walk its operands. 10595 return false; 10596 } 10597 10598 // Keep looking. 10599 return true; 10600 } 10601 10602 bool isDone() const { return false; } 10603 }; 10604 10605 // Check if a SCEV contains an AddRecExpr. 10606 struct SCEVHasAddRec { 10607 bool &ContainsAddRec; 10608 10609 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10610 ContainsAddRec = false; 10611 } 10612 10613 bool follow(const SCEV *S) { 10614 if (isa<SCEVAddRecExpr>(S)) { 10615 ContainsAddRec = true; 10616 10617 // Stop recursion: once we collected a term, do not walk its operands. 10618 return false; 10619 } 10620 10621 // Keep looking. 10622 return true; 10623 } 10624 10625 bool isDone() const { return false; } 10626 }; 10627 10628 // Find factors that are multiplied with an expression that (possibly as a 10629 // subexpression) contains an AddRecExpr. In the expression: 10630 // 10631 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10632 // 10633 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10634 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10635 // parameters as they form a product with an induction variable. 10636 // 10637 // This collector expects all array size parameters to be in the same MulExpr. 10638 // It might be necessary to later add support for collecting parameters that are 10639 // spread over different nested MulExpr. 10640 struct SCEVCollectAddRecMultiplies { 10641 SmallVectorImpl<const SCEV *> &Terms; 10642 ScalarEvolution &SE; 10643 10644 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10645 : Terms(T), SE(SE) {} 10646 10647 bool follow(const SCEV *S) { 10648 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10649 bool HasAddRec = false; 10650 SmallVector<const SCEV *, 0> Operands; 10651 for (auto Op : Mul->operands()) { 10652 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10653 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10654 Operands.push_back(Op); 10655 } else if (Unknown) { 10656 HasAddRec = true; 10657 } else { 10658 bool ContainsAddRec; 10659 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10660 visitAll(Op, ContiansAddRec); 10661 HasAddRec |= ContainsAddRec; 10662 } 10663 } 10664 if (Operands.size() == 0) 10665 return true; 10666 10667 if (!HasAddRec) 10668 return false; 10669 10670 Terms.push_back(SE.getMulExpr(Operands)); 10671 // Stop recursion: once we collected a term, do not walk its operands. 10672 return false; 10673 } 10674 10675 // Keep looking. 10676 return true; 10677 } 10678 10679 bool isDone() const { return false; } 10680 }; 10681 10682 } // end anonymous namespace 10683 10684 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10685 /// two places: 10686 /// 1) The strides of AddRec expressions. 10687 /// 2) Unknowns that are multiplied with AddRec expressions. 10688 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10689 SmallVectorImpl<const SCEV *> &Terms) { 10690 SmallVector<const SCEV *, 4> Strides; 10691 SCEVCollectStrides StrideCollector(*this, Strides); 10692 visitAll(Expr, StrideCollector); 10693 10694 LLVM_DEBUG({ 10695 dbgs() << "Strides:\n"; 10696 for (const SCEV *S : Strides) 10697 dbgs() << *S << "\n"; 10698 }); 10699 10700 for (const SCEV *S : Strides) { 10701 SCEVCollectTerms TermCollector(Terms); 10702 visitAll(S, TermCollector); 10703 } 10704 10705 LLVM_DEBUG({ 10706 dbgs() << "Terms:\n"; 10707 for (const SCEV *T : Terms) 10708 dbgs() << *T << "\n"; 10709 }); 10710 10711 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10712 visitAll(Expr, MulCollector); 10713 } 10714 10715 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10716 SmallVectorImpl<const SCEV *> &Terms, 10717 SmallVectorImpl<const SCEV *> &Sizes) { 10718 int Last = Terms.size() - 1; 10719 const SCEV *Step = Terms[Last]; 10720 10721 // End of recursion. 10722 if (Last == 0) { 10723 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10724 SmallVector<const SCEV *, 2> Qs; 10725 for (const SCEV *Op : M->operands()) 10726 if (!isa<SCEVConstant>(Op)) 10727 Qs.push_back(Op); 10728 10729 Step = SE.getMulExpr(Qs); 10730 } 10731 10732 Sizes.push_back(Step); 10733 return true; 10734 } 10735 10736 for (const SCEV *&Term : Terms) { 10737 // Normalize the terms before the next call to findArrayDimensionsRec. 10738 const SCEV *Q, *R; 10739 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10740 10741 // Bail out when GCD does not evenly divide one of the terms. 10742 if (!R->isZero()) 10743 return false; 10744 10745 Term = Q; 10746 } 10747 10748 // Remove all SCEVConstants. 10749 Terms.erase( 10750 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10751 Terms.end()); 10752 10753 if (Terms.size() > 0) 10754 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10755 return false; 10756 10757 Sizes.push_back(Step); 10758 return true; 10759 } 10760 10761 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10762 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10763 for (const SCEV *T : Terms) 10764 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10765 return true; 10766 return false; 10767 } 10768 10769 // Return the number of product terms in S. 10770 static inline int numberOfTerms(const SCEV *S) { 10771 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10772 return Expr->getNumOperands(); 10773 return 1; 10774 } 10775 10776 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10777 if (isa<SCEVConstant>(T)) 10778 return nullptr; 10779 10780 if (isa<SCEVUnknown>(T)) 10781 return T; 10782 10783 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10784 SmallVector<const SCEV *, 2> Factors; 10785 for (const SCEV *Op : M->operands()) 10786 if (!isa<SCEVConstant>(Op)) 10787 Factors.push_back(Op); 10788 10789 return SE.getMulExpr(Factors); 10790 } 10791 10792 return T; 10793 } 10794 10795 /// Return the size of an element read or written by Inst. 10796 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10797 Type *Ty; 10798 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10799 Ty = Store->getValueOperand()->getType(); 10800 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10801 Ty = Load->getType(); 10802 else 10803 return nullptr; 10804 10805 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10806 return getSizeOfExpr(ETy, Ty); 10807 } 10808 10809 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10810 SmallVectorImpl<const SCEV *> &Sizes, 10811 const SCEV *ElementSize) { 10812 if (Terms.size() < 1 || !ElementSize) 10813 return; 10814 10815 // Early return when Terms do not contain parameters: we do not delinearize 10816 // non parametric SCEVs. 10817 if (!containsParameters(Terms)) 10818 return; 10819 10820 LLVM_DEBUG({ 10821 dbgs() << "Terms:\n"; 10822 for (const SCEV *T : Terms) 10823 dbgs() << *T << "\n"; 10824 }); 10825 10826 // Remove duplicates. 10827 array_pod_sort(Terms.begin(), Terms.end()); 10828 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10829 10830 // Put larger terms first. 10831 llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10832 return numberOfTerms(LHS) > numberOfTerms(RHS); 10833 }); 10834 10835 // Try to divide all terms by the element size. If term is not divisible by 10836 // element size, proceed with the original term. 10837 for (const SCEV *&Term : Terms) { 10838 const SCEV *Q, *R; 10839 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10840 if (!Q->isZero()) 10841 Term = Q; 10842 } 10843 10844 SmallVector<const SCEV *, 4> NewTerms; 10845 10846 // Remove constant factors. 10847 for (const SCEV *T : Terms) 10848 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10849 NewTerms.push_back(NewT); 10850 10851 LLVM_DEBUG({ 10852 dbgs() << "Terms after sorting:\n"; 10853 for (const SCEV *T : NewTerms) 10854 dbgs() << *T << "\n"; 10855 }); 10856 10857 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10858 Sizes.clear(); 10859 return; 10860 } 10861 10862 // The last element to be pushed into Sizes is the size of an element. 10863 Sizes.push_back(ElementSize); 10864 10865 LLVM_DEBUG({ 10866 dbgs() << "Sizes:\n"; 10867 for (const SCEV *S : Sizes) 10868 dbgs() << *S << "\n"; 10869 }); 10870 } 10871 10872 void ScalarEvolution::computeAccessFunctions( 10873 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10874 SmallVectorImpl<const SCEV *> &Sizes) { 10875 // Early exit in case this SCEV is not an affine multivariate function. 10876 if (Sizes.empty()) 10877 return; 10878 10879 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10880 if (!AR->isAffine()) 10881 return; 10882 10883 const SCEV *Res = Expr; 10884 int Last = Sizes.size() - 1; 10885 for (int i = Last; i >= 0; i--) { 10886 const SCEV *Q, *R; 10887 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10888 10889 LLVM_DEBUG({ 10890 dbgs() << "Res: " << *Res << "\n"; 10891 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10892 dbgs() << "Res divided by Sizes[i]:\n"; 10893 dbgs() << "Quotient: " << *Q << "\n"; 10894 dbgs() << "Remainder: " << *R << "\n"; 10895 }); 10896 10897 Res = Q; 10898 10899 // Do not record the last subscript corresponding to the size of elements in 10900 // the array. 10901 if (i == Last) { 10902 10903 // Bail out if the remainder is too complex. 10904 if (isa<SCEVAddRecExpr>(R)) { 10905 Subscripts.clear(); 10906 Sizes.clear(); 10907 return; 10908 } 10909 10910 continue; 10911 } 10912 10913 // Record the access function for the current subscript. 10914 Subscripts.push_back(R); 10915 } 10916 10917 // Also push in last position the remainder of the last division: it will be 10918 // the access function of the innermost dimension. 10919 Subscripts.push_back(Res); 10920 10921 std::reverse(Subscripts.begin(), Subscripts.end()); 10922 10923 LLVM_DEBUG({ 10924 dbgs() << "Subscripts:\n"; 10925 for (const SCEV *S : Subscripts) 10926 dbgs() << *S << "\n"; 10927 }); 10928 } 10929 10930 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10931 /// sizes of an array access. Returns the remainder of the delinearization that 10932 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10933 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10934 /// expressions in the stride and base of a SCEV corresponding to the 10935 /// computation of a GCD (greatest common divisor) of base and stride. When 10936 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10937 /// 10938 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10939 /// 10940 /// void foo(long n, long m, long o, double A[n][m][o]) { 10941 /// 10942 /// for (long i = 0; i < n; i++) 10943 /// for (long j = 0; j < m; j++) 10944 /// for (long k = 0; k < o; k++) 10945 /// A[i][j][k] = 1.0; 10946 /// } 10947 /// 10948 /// the delinearization input is the following AddRec SCEV: 10949 /// 10950 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10951 /// 10952 /// From this SCEV, we are able to say that the base offset of the access is %A 10953 /// because it appears as an offset that does not divide any of the strides in 10954 /// the loops: 10955 /// 10956 /// CHECK: Base offset: %A 10957 /// 10958 /// and then SCEV->delinearize determines the size of some of the dimensions of 10959 /// the array as these are the multiples by which the strides are happening: 10960 /// 10961 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10962 /// 10963 /// Note that the outermost dimension remains of UnknownSize because there are 10964 /// no strides that would help identifying the size of the last dimension: when 10965 /// the array has been statically allocated, one could compute the size of that 10966 /// dimension by dividing the overall size of the array by the size of the known 10967 /// dimensions: %m * %o * 8. 10968 /// 10969 /// Finally delinearize provides the access functions for the array reference 10970 /// that does correspond to A[i][j][k] of the above C testcase: 10971 /// 10972 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10973 /// 10974 /// The testcases are checking the output of a function pass: 10975 /// DelinearizationPass that walks through all loads and stores of a function 10976 /// asking for the SCEV of the memory access with respect to all enclosing 10977 /// loops, calling SCEV->delinearize on that and printing the results. 10978 void ScalarEvolution::delinearize(const SCEV *Expr, 10979 SmallVectorImpl<const SCEV *> &Subscripts, 10980 SmallVectorImpl<const SCEV *> &Sizes, 10981 const SCEV *ElementSize) { 10982 // First step: collect parametric terms. 10983 SmallVector<const SCEV *, 4> Terms; 10984 collectParametricTerms(Expr, Terms); 10985 10986 if (Terms.empty()) 10987 return; 10988 10989 // Second step: find subscript sizes. 10990 findArrayDimensions(Terms, Sizes, ElementSize); 10991 10992 if (Sizes.empty()) 10993 return; 10994 10995 // Third step: compute the access functions for each subscript. 10996 computeAccessFunctions(Expr, Subscripts, Sizes); 10997 10998 if (Subscripts.empty()) 10999 return; 11000 11001 LLVM_DEBUG({ 11002 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11003 dbgs() << "ArrayDecl[UnknownSize]"; 11004 for (const SCEV *S : Sizes) 11005 dbgs() << "[" << *S << "]"; 11006 11007 dbgs() << "\nArrayRef"; 11008 for (const SCEV *S : Subscripts) 11009 dbgs() << "[" << *S << "]"; 11010 dbgs() << "\n"; 11011 }); 11012 } 11013 11014 //===----------------------------------------------------------------------===// 11015 // SCEVCallbackVH Class Implementation 11016 //===----------------------------------------------------------------------===// 11017 11018 void ScalarEvolution::SCEVCallbackVH::deleted() { 11019 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11020 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11021 SE->ConstantEvolutionLoopExitValue.erase(PN); 11022 SE->eraseValueFromMap(getValPtr()); 11023 // this now dangles! 11024 } 11025 11026 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11027 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11028 11029 // Forget all the expressions associated with users of the old value, 11030 // so that future queries will recompute the expressions using the new 11031 // value. 11032 Value *Old = getValPtr(); 11033 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11034 SmallPtrSet<User *, 8> Visited; 11035 while (!Worklist.empty()) { 11036 User *U = Worklist.pop_back_val(); 11037 // Deleting the Old value will cause this to dangle. Postpone 11038 // that until everything else is done. 11039 if (U == Old) 11040 continue; 11041 if (!Visited.insert(U).second) 11042 continue; 11043 if (PHINode *PN = dyn_cast<PHINode>(U)) 11044 SE->ConstantEvolutionLoopExitValue.erase(PN); 11045 SE->eraseValueFromMap(U); 11046 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11047 } 11048 // Delete the Old value. 11049 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11050 SE->ConstantEvolutionLoopExitValue.erase(PN); 11051 SE->eraseValueFromMap(Old); 11052 // this now dangles! 11053 } 11054 11055 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11056 : CallbackVH(V), SE(se) {} 11057 11058 //===----------------------------------------------------------------------===// 11059 // ScalarEvolution Class Implementation 11060 //===----------------------------------------------------------------------===// 11061 11062 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11063 AssumptionCache &AC, DominatorTree &DT, 11064 LoopInfo &LI) 11065 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11066 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11067 LoopDispositions(64), BlockDispositions(64) { 11068 // To use guards for proving predicates, we need to scan every instruction in 11069 // relevant basic blocks, and not just terminators. Doing this is a waste of 11070 // time if the IR does not actually contain any calls to 11071 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11072 // 11073 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11074 // to _add_ guards to the module when there weren't any before, and wants 11075 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11076 // efficient in lieu of being smart in that rather obscure case. 11077 11078 auto *GuardDecl = F.getParent()->getFunction( 11079 Intrinsic::getName(Intrinsic::experimental_guard)); 11080 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11081 } 11082 11083 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11084 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11085 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11086 ValueExprMap(std::move(Arg.ValueExprMap)), 11087 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11088 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11089 PendingMerges(std::move(Arg.PendingMerges)), 11090 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11091 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11092 PredicatedBackedgeTakenCounts( 11093 std::move(Arg.PredicatedBackedgeTakenCounts)), 11094 ConstantEvolutionLoopExitValue( 11095 std::move(Arg.ConstantEvolutionLoopExitValue)), 11096 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11097 LoopDispositions(std::move(Arg.LoopDispositions)), 11098 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11099 BlockDispositions(std::move(Arg.BlockDispositions)), 11100 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11101 SignedRanges(std::move(Arg.SignedRanges)), 11102 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11103 UniquePreds(std::move(Arg.UniquePreds)), 11104 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11105 LoopUsers(std::move(Arg.LoopUsers)), 11106 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11107 FirstUnknown(Arg.FirstUnknown) { 11108 Arg.FirstUnknown = nullptr; 11109 } 11110 11111 ScalarEvolution::~ScalarEvolution() { 11112 // Iterate through all the SCEVUnknown instances and call their 11113 // destructors, so that they release their references to their values. 11114 for (SCEVUnknown *U = FirstUnknown; U;) { 11115 SCEVUnknown *Tmp = U; 11116 U = U->Next; 11117 Tmp->~SCEVUnknown(); 11118 } 11119 FirstUnknown = nullptr; 11120 11121 ExprValueMap.clear(); 11122 ValueExprMap.clear(); 11123 HasRecMap.clear(); 11124 11125 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11126 // that a loop had multiple computable exits. 11127 for (auto &BTCI : BackedgeTakenCounts) 11128 BTCI.second.clear(); 11129 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11130 BTCI.second.clear(); 11131 11132 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11133 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11134 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11135 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11136 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11137 } 11138 11139 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11140 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11141 } 11142 11143 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11144 const Loop *L) { 11145 // Print all inner loops first 11146 for (Loop *I : *L) 11147 PrintLoopInfo(OS, SE, I); 11148 11149 OS << "Loop "; 11150 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11151 OS << ": "; 11152 11153 SmallVector<BasicBlock *, 8> ExitBlocks; 11154 L->getExitBlocks(ExitBlocks); 11155 if (ExitBlocks.size() != 1) 11156 OS << "<multiple exits> "; 11157 11158 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11159 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11160 } else { 11161 OS << "Unpredictable backedge-taken count. "; 11162 } 11163 11164 OS << "\n" 11165 "Loop "; 11166 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11167 OS << ": "; 11168 11169 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11170 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11171 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11172 OS << ", actual taken count either this or zero."; 11173 } else { 11174 OS << "Unpredictable max backedge-taken count. "; 11175 } 11176 11177 OS << "\n" 11178 "Loop "; 11179 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11180 OS << ": "; 11181 11182 SCEVUnionPredicate Pred; 11183 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11184 if (!isa<SCEVCouldNotCompute>(PBT)) { 11185 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11186 OS << " Predicates:\n"; 11187 Pred.print(OS, 4); 11188 } else { 11189 OS << "Unpredictable predicated backedge-taken count. "; 11190 } 11191 OS << "\n"; 11192 11193 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11194 OS << "Loop "; 11195 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11196 OS << ": "; 11197 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11198 } 11199 } 11200 11201 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11202 switch (LD) { 11203 case ScalarEvolution::LoopVariant: 11204 return "Variant"; 11205 case ScalarEvolution::LoopInvariant: 11206 return "Invariant"; 11207 case ScalarEvolution::LoopComputable: 11208 return "Computable"; 11209 } 11210 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11211 } 11212 11213 void ScalarEvolution::print(raw_ostream &OS) const { 11214 // ScalarEvolution's implementation of the print method is to print 11215 // out SCEV values of all instructions that are interesting. Doing 11216 // this potentially causes it to create new SCEV objects though, 11217 // which technically conflicts with the const qualifier. This isn't 11218 // observable from outside the class though, so casting away the 11219 // const isn't dangerous. 11220 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11221 11222 OS << "Classifying expressions for: "; 11223 F.printAsOperand(OS, /*PrintType=*/false); 11224 OS << "\n"; 11225 for (Instruction &I : instructions(F)) 11226 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11227 OS << I << '\n'; 11228 OS << " --> "; 11229 const SCEV *SV = SE.getSCEV(&I); 11230 SV->print(OS); 11231 if (!isa<SCEVCouldNotCompute>(SV)) { 11232 OS << " U: "; 11233 SE.getUnsignedRange(SV).print(OS); 11234 OS << " S: "; 11235 SE.getSignedRange(SV).print(OS); 11236 } 11237 11238 const Loop *L = LI.getLoopFor(I.getParent()); 11239 11240 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11241 if (AtUse != SV) { 11242 OS << " --> "; 11243 AtUse->print(OS); 11244 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11245 OS << " U: "; 11246 SE.getUnsignedRange(AtUse).print(OS); 11247 OS << " S: "; 11248 SE.getSignedRange(AtUse).print(OS); 11249 } 11250 } 11251 11252 if (L) { 11253 OS << "\t\t" "Exits: "; 11254 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11255 if (!SE.isLoopInvariant(ExitValue, L)) { 11256 OS << "<<Unknown>>"; 11257 } else { 11258 OS << *ExitValue; 11259 } 11260 11261 bool First = true; 11262 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11263 if (First) { 11264 OS << "\t\t" "LoopDispositions: { "; 11265 First = false; 11266 } else { 11267 OS << ", "; 11268 } 11269 11270 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11271 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11272 } 11273 11274 for (auto *InnerL : depth_first(L)) { 11275 if (InnerL == L) 11276 continue; 11277 if (First) { 11278 OS << "\t\t" "LoopDispositions: { "; 11279 First = false; 11280 } else { 11281 OS << ", "; 11282 } 11283 11284 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11285 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11286 } 11287 11288 OS << " }"; 11289 } 11290 11291 OS << "\n"; 11292 } 11293 11294 OS << "Determining loop execution counts for: "; 11295 F.printAsOperand(OS, /*PrintType=*/false); 11296 OS << "\n"; 11297 for (Loop *I : LI) 11298 PrintLoopInfo(OS, &SE, I); 11299 } 11300 11301 ScalarEvolution::LoopDisposition 11302 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11303 auto &Values = LoopDispositions[S]; 11304 for (auto &V : Values) { 11305 if (V.getPointer() == L) 11306 return V.getInt(); 11307 } 11308 Values.emplace_back(L, LoopVariant); 11309 LoopDisposition D = computeLoopDisposition(S, L); 11310 auto &Values2 = LoopDispositions[S]; 11311 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11312 if (V.getPointer() == L) { 11313 V.setInt(D); 11314 break; 11315 } 11316 } 11317 return D; 11318 } 11319 11320 ScalarEvolution::LoopDisposition 11321 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11322 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11323 case scConstant: 11324 return LoopInvariant; 11325 case scTruncate: 11326 case scZeroExtend: 11327 case scSignExtend: 11328 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11329 case scAddRecExpr: { 11330 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11331 11332 // If L is the addrec's loop, it's computable. 11333 if (AR->getLoop() == L) 11334 return LoopComputable; 11335 11336 // Add recurrences are never invariant in the function-body (null loop). 11337 if (!L) 11338 return LoopVariant; 11339 11340 // Everything that is not defined at loop entry is variant. 11341 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11342 return LoopVariant; 11343 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11344 " dominate the contained loop's header?"); 11345 11346 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11347 if (AR->getLoop()->contains(L)) 11348 return LoopInvariant; 11349 11350 // This recurrence is variant w.r.t. L if any of its operands 11351 // are variant. 11352 for (auto *Op : AR->operands()) 11353 if (!isLoopInvariant(Op, L)) 11354 return LoopVariant; 11355 11356 // Otherwise it's loop-invariant. 11357 return LoopInvariant; 11358 } 11359 case scAddExpr: 11360 case scMulExpr: 11361 case scUMaxExpr: 11362 case scSMaxExpr: { 11363 bool HasVarying = false; 11364 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11365 LoopDisposition D = getLoopDisposition(Op, L); 11366 if (D == LoopVariant) 11367 return LoopVariant; 11368 if (D == LoopComputable) 11369 HasVarying = true; 11370 } 11371 return HasVarying ? LoopComputable : LoopInvariant; 11372 } 11373 case scUDivExpr: { 11374 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11375 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11376 if (LD == LoopVariant) 11377 return LoopVariant; 11378 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11379 if (RD == LoopVariant) 11380 return LoopVariant; 11381 return (LD == LoopInvariant && RD == LoopInvariant) ? 11382 LoopInvariant : LoopComputable; 11383 } 11384 case scUnknown: 11385 // All non-instruction values are loop invariant. All instructions are loop 11386 // invariant if they are not contained in the specified loop. 11387 // Instructions are never considered invariant in the function body 11388 // (null loop) because they are defined within the "loop". 11389 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11390 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11391 return LoopInvariant; 11392 case scCouldNotCompute: 11393 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11394 } 11395 llvm_unreachable("Unknown SCEV kind!"); 11396 } 11397 11398 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11399 return getLoopDisposition(S, L) == LoopInvariant; 11400 } 11401 11402 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11403 return getLoopDisposition(S, L) == LoopComputable; 11404 } 11405 11406 ScalarEvolution::BlockDisposition 11407 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11408 auto &Values = BlockDispositions[S]; 11409 for (auto &V : Values) { 11410 if (V.getPointer() == BB) 11411 return V.getInt(); 11412 } 11413 Values.emplace_back(BB, DoesNotDominateBlock); 11414 BlockDisposition D = computeBlockDisposition(S, BB); 11415 auto &Values2 = BlockDispositions[S]; 11416 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11417 if (V.getPointer() == BB) { 11418 V.setInt(D); 11419 break; 11420 } 11421 } 11422 return D; 11423 } 11424 11425 ScalarEvolution::BlockDisposition 11426 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11427 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11428 case scConstant: 11429 return ProperlyDominatesBlock; 11430 case scTruncate: 11431 case scZeroExtend: 11432 case scSignExtend: 11433 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11434 case scAddRecExpr: { 11435 // This uses a "dominates" query instead of "properly dominates" query 11436 // to test for proper dominance too, because the instruction which 11437 // produces the addrec's value is a PHI, and a PHI effectively properly 11438 // dominates its entire containing block. 11439 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11440 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11441 return DoesNotDominateBlock; 11442 11443 // Fall through into SCEVNAryExpr handling. 11444 LLVM_FALLTHROUGH; 11445 } 11446 case scAddExpr: 11447 case scMulExpr: 11448 case scUMaxExpr: 11449 case scSMaxExpr: { 11450 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11451 bool Proper = true; 11452 for (const SCEV *NAryOp : NAry->operands()) { 11453 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11454 if (D == DoesNotDominateBlock) 11455 return DoesNotDominateBlock; 11456 if (D == DominatesBlock) 11457 Proper = false; 11458 } 11459 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11460 } 11461 case scUDivExpr: { 11462 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11463 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11464 BlockDisposition LD = getBlockDisposition(LHS, BB); 11465 if (LD == DoesNotDominateBlock) 11466 return DoesNotDominateBlock; 11467 BlockDisposition RD = getBlockDisposition(RHS, BB); 11468 if (RD == DoesNotDominateBlock) 11469 return DoesNotDominateBlock; 11470 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11471 ProperlyDominatesBlock : DominatesBlock; 11472 } 11473 case scUnknown: 11474 if (Instruction *I = 11475 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11476 if (I->getParent() == BB) 11477 return DominatesBlock; 11478 if (DT.properlyDominates(I->getParent(), BB)) 11479 return ProperlyDominatesBlock; 11480 return DoesNotDominateBlock; 11481 } 11482 return ProperlyDominatesBlock; 11483 case scCouldNotCompute: 11484 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11485 } 11486 llvm_unreachable("Unknown SCEV kind!"); 11487 } 11488 11489 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11490 return getBlockDisposition(S, BB) >= DominatesBlock; 11491 } 11492 11493 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11494 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11495 } 11496 11497 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11498 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11499 } 11500 11501 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11502 auto IsS = [&](const SCEV *X) { return S == X; }; 11503 auto ContainsS = [&](const SCEV *X) { 11504 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11505 }; 11506 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11507 } 11508 11509 void 11510 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11511 ValuesAtScopes.erase(S); 11512 LoopDispositions.erase(S); 11513 BlockDispositions.erase(S); 11514 UnsignedRanges.erase(S); 11515 SignedRanges.erase(S); 11516 ExprValueMap.erase(S); 11517 HasRecMap.erase(S); 11518 MinTrailingZerosCache.erase(S); 11519 11520 for (auto I = PredicatedSCEVRewrites.begin(); 11521 I != PredicatedSCEVRewrites.end();) { 11522 std::pair<const SCEV *, const Loop *> Entry = I->first; 11523 if (Entry.first == S) 11524 PredicatedSCEVRewrites.erase(I++); 11525 else 11526 ++I; 11527 } 11528 11529 auto RemoveSCEVFromBackedgeMap = 11530 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11531 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11532 BackedgeTakenInfo &BEInfo = I->second; 11533 if (BEInfo.hasOperand(S, this)) { 11534 BEInfo.clear(); 11535 Map.erase(I++); 11536 } else 11537 ++I; 11538 } 11539 }; 11540 11541 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11542 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11543 } 11544 11545 void 11546 ScalarEvolution::getUsedLoops(const SCEV *S, 11547 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11548 struct FindUsedLoops { 11549 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11550 : LoopsUsed(LoopsUsed) {} 11551 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11552 bool follow(const SCEV *S) { 11553 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11554 LoopsUsed.insert(AR->getLoop()); 11555 return true; 11556 } 11557 11558 bool isDone() const { return false; } 11559 }; 11560 11561 FindUsedLoops F(LoopsUsed); 11562 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11563 } 11564 11565 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11566 SmallPtrSet<const Loop *, 8> LoopsUsed; 11567 getUsedLoops(S, LoopsUsed); 11568 for (auto *L : LoopsUsed) 11569 LoopUsers[L].push_back(S); 11570 } 11571 11572 void ScalarEvolution::verify() const { 11573 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11574 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11575 11576 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11577 11578 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11579 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11580 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11581 11582 const SCEV *visitConstant(const SCEVConstant *Constant) { 11583 return SE.getConstant(Constant->getAPInt()); 11584 } 11585 11586 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11587 return SE.getUnknown(Expr->getValue()); 11588 } 11589 11590 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11591 return SE.getCouldNotCompute(); 11592 } 11593 }; 11594 11595 SCEVMapper SCM(SE2); 11596 11597 while (!LoopStack.empty()) { 11598 auto *L = LoopStack.pop_back_val(); 11599 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11600 11601 auto *CurBECount = SCM.visit( 11602 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11603 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11604 11605 if (CurBECount == SE2.getCouldNotCompute() || 11606 NewBECount == SE2.getCouldNotCompute()) { 11607 // NB! This situation is legal, but is very suspicious -- whatever pass 11608 // change the loop to make a trip count go from could not compute to 11609 // computable or vice-versa *should have* invalidated SCEV. However, we 11610 // choose not to assert here (for now) since we don't want false 11611 // positives. 11612 continue; 11613 } 11614 11615 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11616 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11617 // not propagate undef aggressively). This means we can (and do) fail 11618 // verification in cases where a transform makes the trip count of a loop 11619 // go from "undef" to "undef+1" (say). The transform is fine, since in 11620 // both cases the loop iterates "undef" times, but SCEV thinks we 11621 // increased the trip count of the loop by 1 incorrectly. 11622 continue; 11623 } 11624 11625 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11626 SE.getTypeSizeInBits(NewBECount->getType())) 11627 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11628 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11629 SE.getTypeSizeInBits(NewBECount->getType())) 11630 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11631 11632 auto *ConstantDelta = 11633 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11634 11635 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11636 dbgs() << "Trip Count Changed!\n"; 11637 dbgs() << "Old: " << *CurBECount << "\n"; 11638 dbgs() << "New: " << *NewBECount << "\n"; 11639 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11640 std::abort(); 11641 } 11642 } 11643 } 11644 11645 bool ScalarEvolution::invalidate( 11646 Function &F, const PreservedAnalyses &PA, 11647 FunctionAnalysisManager::Invalidator &Inv) { 11648 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11649 // of its dependencies is invalidated. 11650 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11651 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11652 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11653 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11654 Inv.invalidate<LoopAnalysis>(F, PA); 11655 } 11656 11657 AnalysisKey ScalarEvolutionAnalysis::Key; 11658 11659 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11660 FunctionAnalysisManager &AM) { 11661 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11662 AM.getResult<AssumptionAnalysis>(F), 11663 AM.getResult<DominatorTreeAnalysis>(F), 11664 AM.getResult<LoopAnalysis>(F)); 11665 } 11666 11667 PreservedAnalyses 11668 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11669 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11670 return PreservedAnalyses::all(); 11671 } 11672 11673 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11674 "Scalar Evolution Analysis", false, true) 11675 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11676 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11677 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11678 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11679 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11680 "Scalar Evolution Analysis", false, true) 11681 11682 char ScalarEvolutionWrapperPass::ID = 0; 11683 11684 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11685 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11686 } 11687 11688 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11689 SE.reset(new ScalarEvolution( 11690 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11691 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11692 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11693 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11694 return false; 11695 } 11696 11697 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11698 11699 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11700 SE->print(OS); 11701 } 11702 11703 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11704 if (!VerifySCEV) 11705 return; 11706 11707 SE->verify(); 11708 } 11709 11710 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11711 AU.setPreservesAll(); 11712 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11713 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11714 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11715 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11716 } 11717 11718 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11719 const SCEV *RHS) { 11720 FoldingSetNodeID ID; 11721 assert(LHS->getType() == RHS->getType() && 11722 "Type mismatch between LHS and RHS"); 11723 // Unique this node based on the arguments 11724 ID.AddInteger(SCEVPredicate::P_Equal); 11725 ID.AddPointer(LHS); 11726 ID.AddPointer(RHS); 11727 void *IP = nullptr; 11728 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11729 return S; 11730 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11731 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11732 UniquePreds.InsertNode(Eq, IP); 11733 return Eq; 11734 } 11735 11736 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11737 const SCEVAddRecExpr *AR, 11738 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11739 FoldingSetNodeID ID; 11740 // Unique this node based on the arguments 11741 ID.AddInteger(SCEVPredicate::P_Wrap); 11742 ID.AddPointer(AR); 11743 ID.AddInteger(AddedFlags); 11744 void *IP = nullptr; 11745 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11746 return S; 11747 auto *OF = new (SCEVAllocator) 11748 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11749 UniquePreds.InsertNode(OF, IP); 11750 return OF; 11751 } 11752 11753 namespace { 11754 11755 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11756 public: 11757 11758 /// Rewrites \p S in the context of a loop L and the SCEV predication 11759 /// infrastructure. 11760 /// 11761 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11762 /// equivalences present in \p Pred. 11763 /// 11764 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11765 /// \p NewPreds such that the result will be an AddRecExpr. 11766 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11767 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11768 SCEVUnionPredicate *Pred) { 11769 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11770 return Rewriter.visit(S); 11771 } 11772 11773 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11774 if (Pred) { 11775 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11776 for (auto *Pred : ExprPreds) 11777 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11778 if (IPred->getLHS() == Expr) 11779 return IPred->getRHS(); 11780 } 11781 return convertToAddRecWithPreds(Expr); 11782 } 11783 11784 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11785 const SCEV *Operand = visit(Expr->getOperand()); 11786 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11787 if (AR && AR->getLoop() == L && AR->isAffine()) { 11788 // This couldn't be folded because the operand didn't have the nuw 11789 // flag. Add the nusw flag as an assumption that we could make. 11790 const SCEV *Step = AR->getStepRecurrence(SE); 11791 Type *Ty = Expr->getType(); 11792 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11793 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11794 SE.getSignExtendExpr(Step, Ty), L, 11795 AR->getNoWrapFlags()); 11796 } 11797 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11798 } 11799 11800 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11801 const SCEV *Operand = visit(Expr->getOperand()); 11802 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11803 if (AR && AR->getLoop() == L && AR->isAffine()) { 11804 // This couldn't be folded because the operand didn't have the nsw 11805 // flag. Add the nssw flag as an assumption that we could make. 11806 const SCEV *Step = AR->getStepRecurrence(SE); 11807 Type *Ty = Expr->getType(); 11808 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11809 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11810 SE.getSignExtendExpr(Step, Ty), L, 11811 AR->getNoWrapFlags()); 11812 } 11813 return SE.getSignExtendExpr(Operand, Expr->getType()); 11814 } 11815 11816 private: 11817 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11818 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11819 SCEVUnionPredicate *Pred) 11820 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11821 11822 bool addOverflowAssumption(const SCEVPredicate *P) { 11823 if (!NewPreds) { 11824 // Check if we've already made this assumption. 11825 return Pred && Pred->implies(P); 11826 } 11827 NewPreds->insert(P); 11828 return true; 11829 } 11830 11831 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11832 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11833 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11834 return addOverflowAssumption(A); 11835 } 11836 11837 // If \p Expr represents a PHINode, we try to see if it can be represented 11838 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11839 // to add this predicate as a runtime overflow check, we return the AddRec. 11840 // If \p Expr does not meet these conditions (is not a PHI node, or we 11841 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11842 // return \p Expr. 11843 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11844 if (!isa<PHINode>(Expr->getValue())) 11845 return Expr; 11846 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11847 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11848 if (!PredicatedRewrite) 11849 return Expr; 11850 for (auto *P : PredicatedRewrite->second){ 11851 // Wrap predicates from outer loops are not supported. 11852 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 11853 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 11854 if (L != AR->getLoop()) 11855 return Expr; 11856 } 11857 if (!addOverflowAssumption(P)) 11858 return Expr; 11859 } 11860 return PredicatedRewrite->first; 11861 } 11862 11863 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11864 SCEVUnionPredicate *Pred; 11865 const Loop *L; 11866 }; 11867 11868 } // end anonymous namespace 11869 11870 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11871 SCEVUnionPredicate &Preds) { 11872 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11873 } 11874 11875 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11876 const SCEV *S, const Loop *L, 11877 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11878 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11879 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11880 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11881 11882 if (!AddRec) 11883 return nullptr; 11884 11885 // Since the transformation was successful, we can now transfer the SCEV 11886 // predicates. 11887 for (auto *P : TransformPreds) 11888 Preds.insert(P); 11889 11890 return AddRec; 11891 } 11892 11893 /// SCEV predicates 11894 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11895 SCEVPredicateKind Kind) 11896 : FastID(ID), Kind(Kind) {} 11897 11898 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11899 const SCEV *LHS, const SCEV *RHS) 11900 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11901 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11902 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11903 } 11904 11905 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11906 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11907 11908 if (!Op) 11909 return false; 11910 11911 return Op->LHS == LHS && Op->RHS == RHS; 11912 } 11913 11914 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11915 11916 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11917 11918 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11919 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11920 } 11921 11922 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11923 const SCEVAddRecExpr *AR, 11924 IncrementWrapFlags Flags) 11925 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11926 11927 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11928 11929 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11930 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11931 11932 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11933 } 11934 11935 bool SCEVWrapPredicate::isAlwaysTrue() const { 11936 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11937 IncrementWrapFlags IFlags = Flags; 11938 11939 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11940 IFlags = clearFlags(IFlags, IncrementNSSW); 11941 11942 return IFlags == IncrementAnyWrap; 11943 } 11944 11945 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11946 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11947 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11948 OS << "<nusw>"; 11949 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11950 OS << "<nssw>"; 11951 OS << "\n"; 11952 } 11953 11954 SCEVWrapPredicate::IncrementWrapFlags 11955 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11956 ScalarEvolution &SE) { 11957 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11958 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11959 11960 // We can safely transfer the NSW flag as NSSW. 11961 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11962 ImpliedFlags = IncrementNSSW; 11963 11964 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11965 // If the increment is positive, the SCEV NUW flag will also imply the 11966 // WrapPredicate NUSW flag. 11967 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11968 if (Step->getValue()->getValue().isNonNegative()) 11969 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11970 } 11971 11972 return ImpliedFlags; 11973 } 11974 11975 /// Union predicates don't get cached so create a dummy set ID for it. 11976 SCEVUnionPredicate::SCEVUnionPredicate() 11977 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11978 11979 bool SCEVUnionPredicate::isAlwaysTrue() const { 11980 return all_of(Preds, 11981 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11982 } 11983 11984 ArrayRef<const SCEVPredicate *> 11985 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11986 auto I = SCEVToPreds.find(Expr); 11987 if (I == SCEVToPreds.end()) 11988 return ArrayRef<const SCEVPredicate *>(); 11989 return I->second; 11990 } 11991 11992 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11993 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11994 return all_of(Set->Preds, 11995 [this](const SCEVPredicate *I) { return this->implies(I); }); 11996 11997 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11998 if (ScevPredsIt == SCEVToPreds.end()) 11999 return false; 12000 auto &SCEVPreds = ScevPredsIt->second; 12001 12002 return any_of(SCEVPreds, 12003 [N](const SCEVPredicate *I) { return I->implies(N); }); 12004 } 12005 12006 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12007 12008 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12009 for (auto Pred : Preds) 12010 Pred->print(OS, Depth); 12011 } 12012 12013 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12014 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12015 for (auto Pred : Set->Preds) 12016 add(Pred); 12017 return; 12018 } 12019 12020 if (implies(N)) 12021 return; 12022 12023 const SCEV *Key = N->getExpr(); 12024 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12025 " associated expression!"); 12026 12027 SCEVToPreds[Key].push_back(N); 12028 Preds.push_back(N); 12029 } 12030 12031 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12032 Loop &L) 12033 : SE(SE), L(L) {} 12034 12035 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12036 const SCEV *Expr = SE.getSCEV(V); 12037 RewriteEntry &Entry = RewriteMap[Expr]; 12038 12039 // If we already have an entry and the version matches, return it. 12040 if (Entry.second && Generation == Entry.first) 12041 return Entry.second; 12042 12043 // We found an entry but it's stale. Rewrite the stale entry 12044 // according to the current predicate. 12045 if (Entry.second) 12046 Expr = Entry.second; 12047 12048 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12049 Entry = {Generation, NewSCEV}; 12050 12051 return NewSCEV; 12052 } 12053 12054 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12055 if (!BackedgeCount) { 12056 SCEVUnionPredicate BackedgePred; 12057 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12058 addPredicate(BackedgePred); 12059 } 12060 return BackedgeCount; 12061 } 12062 12063 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12064 if (Preds.implies(&Pred)) 12065 return; 12066 Preds.add(&Pred); 12067 updateGeneration(); 12068 } 12069 12070 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12071 return Preds; 12072 } 12073 12074 void PredicatedScalarEvolution::updateGeneration() { 12075 // If the generation number wrapped recompute everything. 12076 if (++Generation == 0) { 12077 for (auto &II : RewriteMap) { 12078 const SCEV *Rewritten = II.second.second; 12079 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12080 } 12081 } 12082 } 12083 12084 void PredicatedScalarEvolution::setNoOverflow( 12085 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12086 const SCEV *Expr = getSCEV(V); 12087 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12088 12089 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12090 12091 // Clear the statically implied flags. 12092 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12093 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12094 12095 auto II = FlagsMap.insert({V, Flags}); 12096 if (!II.second) 12097 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12098 } 12099 12100 bool PredicatedScalarEvolution::hasNoOverflow( 12101 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12102 const SCEV *Expr = getSCEV(V); 12103 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12104 12105 Flags = SCEVWrapPredicate::clearFlags( 12106 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12107 12108 auto II = FlagsMap.find(V); 12109 12110 if (II != FlagsMap.end()) 12111 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12112 12113 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12114 } 12115 12116 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12117 const SCEV *Expr = this->getSCEV(V); 12118 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12119 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12120 12121 if (!New) 12122 return nullptr; 12123 12124 for (auto *P : NewPreds) 12125 Preds.add(P); 12126 12127 updateGeneration(); 12128 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12129 return New; 12130 } 12131 12132 PredicatedScalarEvolution::PredicatedScalarEvolution( 12133 const PredicatedScalarEvolution &Init) 12134 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12135 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12136 for (const auto &I : Init.FlagsMap) 12137 FlagsMap.insert(I); 12138 } 12139 12140 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12141 // For each block. 12142 for (auto *BB : L.getBlocks()) 12143 for (auto &I : *BB) { 12144 if (!SE.isSCEVable(I.getType())) 12145 continue; 12146 12147 auto *Expr = SE.getSCEV(&I); 12148 auto II = RewriteMap.find(Expr); 12149 12150 if (II == RewriteMap.end()) 12151 continue; 12152 12153 // Don't print things that are not interesting. 12154 if (II->second.second == Expr) 12155 continue; 12156 12157 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12158 OS.indent(Depth + 2) << *Expr << "\n"; 12159 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12160 } 12161 } 12162 12163 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12164 // arbitrary expressions. 12165 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12166 // 4, A / B becomes X / 8). 12167 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12168 const SCEV *&RHS) { 12169 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12170 if (Add == nullptr || Add->getNumOperands() != 2) 12171 return false; 12172 12173 const SCEV *A = Add->getOperand(1); 12174 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12175 12176 if (Mul == nullptr) 12177 return false; 12178 12179 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12180 // (SomeExpr + (-(SomeExpr / B) * B)). 12181 if (Expr == getURemExpr(A, B)) { 12182 LHS = A; 12183 RHS = B; 12184 return true; 12185 } 12186 return false; 12187 }; 12188 12189 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12190 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12191 return MatchURemWithDivisor(Mul->getOperand(1)) || 12192 MatchURemWithDivisor(Mul->getOperand(2)); 12193 12194 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12195 if (Mul->getNumOperands() == 2) 12196 return MatchURemWithDivisor(Mul->getOperand(1)) || 12197 MatchURemWithDivisor(Mul->getOperand(0)) || 12198 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12199 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12200 return false; 12201 } 12202