1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.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/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (static_cast<SCEVTypes>(getSCEVType())) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 } 308 OS << "("; 309 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 310 I != E; ++I) { 311 OS << **I; 312 if (std::next(I) != E) 313 OS << OpStr; 314 } 315 OS << ")"; 316 switch (NAry->getSCEVType()) { 317 case scAddExpr: 318 case scMulExpr: 319 if (NAry->hasNoUnsignedWrap()) 320 OS << "<nuw>"; 321 if (NAry->hasNoSignedWrap()) 322 OS << "<nsw>"; 323 } 324 return; 325 } 326 case scUDivExpr: { 327 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 328 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 329 return; 330 } 331 case scUnknown: { 332 const SCEVUnknown *U = cast<SCEVUnknown>(this); 333 Type *AllocTy; 334 if (U->isSizeOf(AllocTy)) { 335 OS << "sizeof(" << *AllocTy << ")"; 336 return; 337 } 338 if (U->isAlignOf(AllocTy)) { 339 OS << "alignof(" << *AllocTy << ")"; 340 return; 341 } 342 343 Type *CTy; 344 Constant *FieldNo; 345 if (U->isOffsetOf(CTy, FieldNo)) { 346 OS << "offsetof(" << *CTy << ", "; 347 FieldNo->printAsOperand(OS, false); 348 OS << ")"; 349 return; 350 } 351 352 // Otherwise just print it normally. 353 U->getValue()->printAsOperand(OS, false); 354 return; 355 } 356 case scCouldNotCompute: 357 OS << "***COULDNOTCOMPUTE***"; 358 return; 359 } 360 llvm_unreachable("Unknown SCEV kind!"); 361 } 362 363 Type *SCEV::getType() const { 364 switch (static_cast<SCEVTypes>(getSCEVType())) { 365 case scConstant: 366 return cast<SCEVConstant>(this)->getType(); 367 case scTruncate: 368 case scZeroExtend: 369 case scSignExtend: 370 return cast<SCEVCastExpr>(this)->getType(); 371 case scAddRecExpr: 372 case scMulExpr: 373 case scUMaxExpr: 374 case scSMaxExpr: 375 case scUMinExpr: 376 case scSMinExpr: 377 return cast<SCEVNAryExpr>(this)->getType(); 378 case scAddExpr: 379 return cast<SCEVAddExpr>(this)->getType(); 380 case scUDivExpr: 381 return cast<SCEVUDivExpr>(this)->getType(); 382 case scUnknown: 383 return cast<SCEVUnknown>(this)->getType(); 384 case scCouldNotCompute: 385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 386 } 387 llvm_unreachable("Unknown SCEV kind!"); 388 } 389 390 bool SCEV::isZero() const { 391 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 392 return SC->getValue()->isZero(); 393 return false; 394 } 395 396 bool SCEV::isOne() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isOne(); 399 return false; 400 } 401 402 bool SCEV::isAllOnesValue() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isMinusOne(); 405 return false; 406 } 407 408 bool SCEV::isNonConstantNegative() const { 409 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 410 if (!Mul) return false; 411 412 // If there is a constant factor, it will be first. 413 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 414 if (!SC) return false; 415 416 // Return true if the value is negative, this matches things like (-42 * V). 417 return SC->getAPInt().isNegative(); 418 } 419 420 SCEVCouldNotCompute::SCEVCouldNotCompute() : 421 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 422 423 bool SCEVCouldNotCompute::classof(const SCEV *S) { 424 return S->getSCEVType() == scCouldNotCompute; 425 } 426 427 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 428 FoldingSetNodeID ID; 429 ID.AddInteger(scConstant); 430 ID.AddPointer(V); 431 void *IP = nullptr; 432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 433 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 434 UniqueSCEVs.InsertNode(S, IP); 435 return S; 436 } 437 438 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 439 return getConstant(ConstantInt::get(getContext(), Val)); 440 } 441 442 const SCEV * 443 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 445 return getConstant(ConstantInt::get(ITy, V, isSigned)); 446 } 447 448 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 449 unsigned SCEVTy, const SCEV *op, Type *ty) 450 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 451 Operands[0] = op; 452 } 453 454 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 455 const SCEV *op, Type *ty) 456 : SCEVCastExpr(ID, scTruncate, op, ty) { 457 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 458 "Cannot truncate non-integer value!"); 459 } 460 461 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 462 const SCEV *op, Type *ty) 463 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 464 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 465 "Cannot zero extend non-integer value!"); 466 } 467 468 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 469 const SCEV *op, Type *ty) 470 : SCEVCastExpr(ID, scSignExtend, op, ty) { 471 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 472 "Cannot sign extend non-integer value!"); 473 } 474 475 void SCEVUnknown::deleted() { 476 // Clear this SCEVUnknown from various maps. 477 SE->forgetMemoizedResults(this); 478 479 // Remove this SCEVUnknown from the uniquing map. 480 SE->UniqueSCEVs.RemoveNode(this); 481 482 // Release the value. 483 setValPtr(nullptr); 484 } 485 486 void SCEVUnknown::allUsesReplacedWith(Value *New) { 487 // Remove this SCEVUnknown from the uniquing map. 488 SE->UniqueSCEVs.RemoveNode(this); 489 490 // Update this SCEVUnknown to point to the new value. This is needed 491 // because there may still be outstanding SCEVs which still point to 492 // this SCEVUnknown. 493 setValPtr(New); 494 } 495 496 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 497 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 498 if (VCE->getOpcode() == Instruction::PtrToInt) 499 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 500 if (CE->getOpcode() == Instruction::GetElementPtr && 501 CE->getOperand(0)->isNullValue() && 502 CE->getNumOperands() == 2) 503 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 504 if (CI->isOne()) { 505 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 506 ->getElementType(); 507 return true; 508 } 509 510 return false; 511 } 512 513 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 514 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 515 if (VCE->getOpcode() == Instruction::PtrToInt) 516 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 517 if (CE->getOpcode() == Instruction::GetElementPtr && 518 CE->getOperand(0)->isNullValue()) { 519 Type *Ty = 520 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 521 if (StructType *STy = dyn_cast<StructType>(Ty)) 522 if (!STy->isPacked() && 523 CE->getNumOperands() == 3 && 524 CE->getOperand(1)->isNullValue()) { 525 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 526 if (CI->isOne() && 527 STy->getNumElements() == 2 && 528 STy->getElementType(0)->isIntegerTy(1)) { 529 AllocTy = STy->getElementType(1); 530 return true; 531 } 532 } 533 } 534 535 return false; 536 } 537 538 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 539 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 540 if (VCE->getOpcode() == Instruction::PtrToInt) 541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 542 if (CE->getOpcode() == Instruction::GetElementPtr && 543 CE->getNumOperands() == 3 && 544 CE->getOperand(0)->isNullValue() && 545 CE->getOperand(1)->isNullValue()) { 546 Type *Ty = 547 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 548 // Ignore vector types here so that ScalarEvolutionExpander doesn't 549 // emit getelementptrs that index into vectors. 550 if (Ty->isStructTy() || Ty->isArrayTy()) { 551 CTy = Ty; 552 FieldNo = CE->getOperand(2); 553 return true; 554 } 555 } 556 557 return false; 558 } 559 560 //===----------------------------------------------------------------------===// 561 // SCEV Utilities 562 //===----------------------------------------------------------------------===// 563 564 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 565 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 566 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 567 /// have been previously deemed to be "equally complex" by this routine. It is 568 /// intended to avoid exponential time complexity in cases like: 569 /// 570 /// %a = f(%x, %y) 571 /// %b = f(%a, %a) 572 /// %c = f(%b, %b) 573 /// 574 /// %d = f(%x, %y) 575 /// %e = f(%d, %d) 576 /// %f = f(%e, %e) 577 /// 578 /// CompareValueComplexity(%f, %c) 579 /// 580 /// Since we do not continue running this routine on expression trees once we 581 /// have seen unequal values, there is no need to track them in the cache. 582 static int 583 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 584 const LoopInfo *const LI, Value *LV, Value *RV, 585 unsigned Depth) { 586 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 587 return 0; 588 589 // Order pointer values after integer values. This helps SCEVExpander form 590 // GEPs. 591 bool LIsPointer = LV->getType()->isPointerTy(), 592 RIsPointer = RV->getType()->isPointerTy(); 593 if (LIsPointer != RIsPointer) 594 return (int)LIsPointer - (int)RIsPointer; 595 596 // Compare getValueID values. 597 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 598 if (LID != RID) 599 return (int)LID - (int)RID; 600 601 // Sort arguments by their position. 602 if (const auto *LA = dyn_cast<Argument>(LV)) { 603 const auto *RA = cast<Argument>(RV); 604 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 605 return (int)LArgNo - (int)RArgNo; 606 } 607 608 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 609 const auto *RGV = cast<GlobalValue>(RV); 610 611 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 612 auto LT = GV->getLinkage(); 613 return !(GlobalValue::isPrivateLinkage(LT) || 614 GlobalValue::isInternalLinkage(LT)); 615 }; 616 617 // Use the names to distinguish the two values, but only if the 618 // names are semantically important. 619 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 620 return LGV->getName().compare(RGV->getName()); 621 } 622 623 // For instructions, compare their loop depth, and their operand count. This 624 // is pretty loose. 625 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 626 const auto *RInst = cast<Instruction>(RV); 627 628 // Compare loop depths. 629 const BasicBlock *LParent = LInst->getParent(), 630 *RParent = RInst->getParent(); 631 if (LParent != RParent) { 632 unsigned LDepth = LI->getLoopDepth(LParent), 633 RDepth = LI->getLoopDepth(RParent); 634 if (LDepth != RDepth) 635 return (int)LDepth - (int)RDepth; 636 } 637 638 // Compare the number of operands. 639 unsigned LNumOps = LInst->getNumOperands(), 640 RNumOps = RInst->getNumOperands(); 641 if (LNumOps != RNumOps) 642 return (int)LNumOps - (int)RNumOps; 643 644 for (unsigned Idx : seq(0u, LNumOps)) { 645 int Result = 646 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 647 RInst->getOperand(Idx), Depth + 1); 648 if (Result != 0) 649 return Result; 650 } 651 } 652 653 EqCacheValue.unionSets(LV, RV); 654 return 0; 655 } 656 657 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 658 // than RHS, respectively. A three-way result allows recursive comparisons to be 659 // more efficient. 660 static int CompareSCEVComplexity( 661 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 662 EquivalenceClasses<const Value *> &EqCacheValue, 663 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 664 DominatorTree &DT, unsigned Depth = 0) { 665 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 666 if (LHS == RHS) 667 return 0; 668 669 // Primarily, sort the SCEVs by their getSCEVType(). 670 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 671 if (LType != RType) 672 return (int)LType - (int)RType; 673 674 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 675 return 0; 676 // Aside from the getSCEVType() ordering, the particular ordering 677 // isn't very important except that it's beneficial to be consistent, 678 // so that (a + b) and (b + a) don't end up as different expressions. 679 switch (static_cast<SCEVTypes>(LType)) { 680 case scUnknown: { 681 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 682 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 683 684 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 685 RU->getValue(), Depth + 1); 686 if (X == 0) 687 EqCacheSCEV.unionSets(LHS, RHS); 688 return X; 689 } 690 691 case scConstant: { 692 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 693 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 694 695 // Compare constant values. 696 const APInt &LA = LC->getAPInt(); 697 const APInt &RA = RC->getAPInt(); 698 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 699 if (LBitWidth != RBitWidth) 700 return (int)LBitWidth - (int)RBitWidth; 701 return LA.ult(RA) ? -1 : 1; 702 } 703 704 case scAddRecExpr: { 705 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 706 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 707 708 // There is always a dominance between two recs that are used by one SCEV, 709 // so we can safely sort recs by loop header dominance. We require such 710 // order in getAddExpr. 711 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 712 if (LLoop != RLoop) { 713 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 714 assert(LHead != RHead && "Two loops share the same header?"); 715 if (DT.dominates(LHead, RHead)) 716 return 1; 717 else 718 assert(DT.dominates(RHead, LHead) && 719 "No dominance between recurrences used by one SCEV?"); 720 return -1; 721 } 722 723 // Addrec complexity grows with operand count. 724 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 725 if (LNumOps != RNumOps) 726 return (int)LNumOps - (int)RNumOps; 727 728 // Lexicographically compare. 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LA->getOperand(i), RA->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scAddExpr: 741 case scMulExpr: 742 case scSMaxExpr: 743 case scUMaxExpr: 744 case scSMinExpr: 745 case scUMinExpr: { 746 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 747 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 748 749 // Lexicographically compare n-ary expressions. 750 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 751 if (LNumOps != RNumOps) 752 return (int)LNumOps - (int)RNumOps; 753 754 for (unsigned i = 0; i != LNumOps; ++i) { 755 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 756 LC->getOperand(i), RC->getOperand(i), DT, 757 Depth + 1); 758 if (X != 0) 759 return X; 760 } 761 EqCacheSCEV.unionSets(LHS, RHS); 762 return 0; 763 } 764 765 case scUDivExpr: { 766 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 767 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 768 769 // Lexicographically compare udiv expressions. 770 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 771 RC->getLHS(), DT, Depth + 1); 772 if (X != 0) 773 return X; 774 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 775 RC->getRHS(), DT, Depth + 1); 776 if (X == 0) 777 EqCacheSCEV.unionSets(LHS, RHS); 778 return X; 779 } 780 781 case scTruncate: 782 case scZeroExtend: 783 case scSignExtend: { 784 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 785 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 786 787 // Compare cast expressions by operand. 788 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 789 LC->getOperand(), RC->getOperand(), DT, 790 Depth + 1); 791 if (X == 0) 792 EqCacheSCEV.unionSets(LHS, RHS); 793 return X; 794 } 795 796 case scCouldNotCompute: 797 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 798 } 799 llvm_unreachable("Unknown SCEV kind!"); 800 } 801 802 /// Given a list of SCEV objects, order them by their complexity, and group 803 /// objects of the same complexity together by value. When this routine is 804 /// finished, we know that any duplicates in the vector are consecutive and that 805 /// complexity is monotonically increasing. 806 /// 807 /// Note that we go take special precautions to ensure that we get deterministic 808 /// results from this routine. In other words, we don't want the results of 809 /// this to depend on where the addresses of various SCEV objects happened to 810 /// land in memory. 811 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 812 LoopInfo *LI, DominatorTree &DT) { 813 if (Ops.size() < 2) return; // Noop 814 815 EquivalenceClasses<const SCEV *> EqCacheSCEV; 816 EquivalenceClasses<const Value *> EqCacheValue; 817 if (Ops.size() == 2) { 818 // This is the common case, which also happens to be trivially simple. 819 // Special case it. 820 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 821 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 822 std::swap(LHS, RHS); 823 return; 824 } 825 826 // Do the rough sort by complexity. 827 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 828 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 829 0; 830 }); 831 832 // Now that we are sorted by complexity, group elements of the same 833 // complexity. Note that this is, at worst, N^2, but the vector is likely to 834 // be extremely short in practice. Note that we take this approach because we 835 // do not want to depend on the addresses of the objects we are grouping. 836 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 837 const SCEV *S = Ops[i]; 838 unsigned Complexity = S->getSCEVType(); 839 840 // If there are any objects of the same complexity and same value as this 841 // one, group them. 842 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 843 if (Ops[j] == S) { // Found a duplicate. 844 // Move it to immediately after i'th element. 845 std::swap(Ops[i+1], Ops[j]); 846 ++i; // no need to rescan it. 847 if (i == e-2) return; // Done! 848 } 849 } 850 } 851 } 852 853 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 854 /// least HugeExprThreshold nodes). 855 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 856 return any_of(Ops, [](const SCEV *S) { 857 return S->getExpressionSize() >= HugeExprThreshold; 858 }); 859 } 860 861 //===----------------------------------------------------------------------===// 862 // Simple SCEV method implementations 863 //===----------------------------------------------------------------------===// 864 865 /// Compute BC(It, K). The result has width W. Assume, K > 0. 866 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 867 ScalarEvolution &SE, 868 Type *ResultTy) { 869 // Handle the simplest case efficiently. 870 if (K == 1) 871 return SE.getTruncateOrZeroExtend(It, ResultTy); 872 873 // We are using the following formula for BC(It, K): 874 // 875 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 876 // 877 // Suppose, W is the bitwidth of the return value. We must be prepared for 878 // overflow. Hence, we must assure that the result of our computation is 879 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 880 // safe in modular arithmetic. 881 // 882 // However, this code doesn't use exactly that formula; the formula it uses 883 // is something like the following, where T is the number of factors of 2 in 884 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 885 // exponentiation: 886 // 887 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 888 // 889 // This formula is trivially equivalent to the previous formula. However, 890 // this formula can be implemented much more efficiently. The trick is that 891 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 892 // arithmetic. To do exact division in modular arithmetic, all we have 893 // to do is multiply by the inverse. Therefore, this step can be done at 894 // width W. 895 // 896 // The next issue is how to safely do the division by 2^T. The way this 897 // is done is by doing the multiplication step at a width of at least W + T 898 // bits. This way, the bottom W+T bits of the product are accurate. Then, 899 // when we perform the division by 2^T (which is equivalent to a right shift 900 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 901 // truncated out after the division by 2^T. 902 // 903 // In comparison to just directly using the first formula, this technique 904 // is much more efficient; using the first formula requires W * K bits, 905 // but this formula less than W + K bits. Also, the first formula requires 906 // a division step, whereas this formula only requires multiplies and shifts. 907 // 908 // It doesn't matter whether the subtraction step is done in the calculation 909 // width or the input iteration count's width; if the subtraction overflows, 910 // the result must be zero anyway. We prefer here to do it in the width of 911 // the induction variable because it helps a lot for certain cases; CodeGen 912 // isn't smart enough to ignore the overflow, which leads to much less 913 // efficient code if the width of the subtraction is wider than the native 914 // register width. 915 // 916 // (It's possible to not widen at all by pulling out factors of 2 before 917 // the multiplication; for example, K=2 can be calculated as 918 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 919 // extra arithmetic, so it's not an obvious win, and it gets 920 // much more complicated for K > 3.) 921 922 // Protection from insane SCEVs; this bound is conservative, 923 // but it probably doesn't matter. 924 if (K > 1000) 925 return SE.getCouldNotCompute(); 926 927 unsigned W = SE.getTypeSizeInBits(ResultTy); 928 929 // Calculate K! / 2^T and T; we divide out the factors of two before 930 // multiplying for calculating K! / 2^T to avoid overflow. 931 // Other overflow doesn't matter because we only care about the bottom 932 // W bits of the result. 933 APInt OddFactorial(W, 1); 934 unsigned T = 1; 935 for (unsigned i = 3; i <= K; ++i) { 936 APInt Mult(W, i); 937 unsigned TwoFactors = Mult.countTrailingZeros(); 938 T += TwoFactors; 939 Mult.lshrInPlace(TwoFactors); 940 OddFactorial *= Mult; 941 } 942 943 // We need at least W + T bits for the multiplication step 944 unsigned CalculationBits = W + T; 945 946 // Calculate 2^T, at width T+W. 947 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 948 949 // Calculate the multiplicative inverse of K! / 2^T; 950 // this multiplication factor will perform the exact division by 951 // K! / 2^T. 952 APInt Mod = APInt::getSignedMinValue(W+1); 953 APInt MultiplyFactor = OddFactorial.zext(W+1); 954 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 955 MultiplyFactor = MultiplyFactor.trunc(W); 956 957 // Calculate the product, at width T+W 958 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 959 CalculationBits); 960 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 961 for (unsigned i = 1; i != K; ++i) { 962 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 963 Dividend = SE.getMulExpr(Dividend, 964 SE.getTruncateOrZeroExtend(S, CalculationTy)); 965 } 966 967 // Divide by 2^T 968 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 969 970 // Truncate the result, and divide by K! / 2^T. 971 972 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 973 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 974 } 975 976 /// Return the value of this chain of recurrences at the specified iteration 977 /// number. We can evaluate this recurrence by multiplying each element in the 978 /// chain by the binomial coefficient corresponding to it. In other words, we 979 /// can evaluate {A,+,B,+,C,+,D} as: 980 /// 981 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 982 /// 983 /// where BC(It, k) stands for binomial coefficient. 984 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 985 ScalarEvolution &SE) const { 986 const SCEV *Result = getStart(); 987 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 988 // The computation is correct in the face of overflow provided that the 989 // multiplication is performed _after_ the evaluation of the binomial 990 // coefficient. 991 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 992 if (isa<SCEVCouldNotCompute>(Coeff)) 993 return Coeff; 994 995 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 996 } 997 return Result; 998 } 999 1000 //===----------------------------------------------------------------------===// 1001 // SCEV Expression folder implementations 1002 //===----------------------------------------------------------------------===// 1003 1004 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1005 unsigned Depth) { 1006 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1007 "This is not a truncating conversion!"); 1008 assert(isSCEVable(Ty) && 1009 "This is not a conversion to a SCEVable type!"); 1010 Ty = getEffectiveSCEVType(Ty); 1011 1012 FoldingSetNodeID ID; 1013 ID.AddInteger(scTruncate); 1014 ID.AddPointer(Op); 1015 ID.AddPointer(Ty); 1016 void *IP = nullptr; 1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1018 1019 // Fold if the operand is constant. 1020 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1021 return getConstant( 1022 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1023 1024 // trunc(trunc(x)) --> trunc(x) 1025 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1026 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1027 1028 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1029 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1030 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1031 1032 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1033 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1034 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1035 1036 if (Depth > MaxCastDepth) { 1037 SCEV *S = 1038 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1039 UniqueSCEVs.InsertNode(S, IP); 1040 addToLoopUseLists(S); 1041 return S; 1042 } 1043 1044 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1045 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1046 // if after transforming we have at most one truncate, not counting truncates 1047 // that replace other casts. 1048 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1049 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1050 SmallVector<const SCEV *, 4> Operands; 1051 unsigned numTruncs = 0; 1052 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1053 ++i) { 1054 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1055 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1056 numTruncs++; 1057 Operands.push_back(S); 1058 } 1059 if (numTruncs < 2) { 1060 if (isa<SCEVAddExpr>(Op)) 1061 return getAddExpr(Operands); 1062 else if (isa<SCEVMulExpr>(Op)) 1063 return getMulExpr(Operands); 1064 else 1065 llvm_unreachable("Unexpected SCEV type for Op."); 1066 } 1067 // Although we checked in the beginning that ID is not in the cache, it is 1068 // possible that during recursion and different modification ID was inserted 1069 // into the cache. So if we find it, just return it. 1070 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1071 return S; 1072 } 1073 1074 // If the input value is a chrec scev, truncate the chrec's operands. 1075 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1076 SmallVector<const SCEV *, 4> Operands; 1077 for (const SCEV *Op : AddRec->operands()) 1078 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1079 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1080 } 1081 1082 // The cast wasn't folded; create an explicit cast node. We can reuse 1083 // the existing insert position since if we get here, we won't have 1084 // made any changes which would invalidate it. 1085 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1086 Op, Ty); 1087 UniqueSCEVs.InsertNode(S, IP); 1088 addToLoopUseLists(S); 1089 return S; 1090 } 1091 1092 // Get the limit of a recurrence such that incrementing by Step cannot cause 1093 // signed overflow as long as the value of the recurrence within the 1094 // loop does not exceed this limit before incrementing. 1095 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1096 ICmpInst::Predicate *Pred, 1097 ScalarEvolution *SE) { 1098 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1099 if (SE->isKnownPositive(Step)) { 1100 *Pred = ICmpInst::ICMP_SLT; 1101 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1102 SE->getSignedRangeMax(Step)); 1103 } 1104 if (SE->isKnownNegative(Step)) { 1105 *Pred = ICmpInst::ICMP_SGT; 1106 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1107 SE->getSignedRangeMin(Step)); 1108 } 1109 return nullptr; 1110 } 1111 1112 // Get the limit of a recurrence such that incrementing by Step cannot cause 1113 // unsigned overflow as long as the value of the recurrence within the loop does 1114 // not exceed this limit before incrementing. 1115 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1116 ICmpInst::Predicate *Pred, 1117 ScalarEvolution *SE) { 1118 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1119 *Pred = ICmpInst::ICMP_ULT; 1120 1121 return SE->getConstant(APInt::getMinValue(BitWidth) - 1122 SE->getUnsignedRangeMax(Step)); 1123 } 1124 1125 namespace { 1126 1127 struct ExtendOpTraitsBase { 1128 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1129 unsigned); 1130 }; 1131 1132 // Used to make code generic over signed and unsigned overflow. 1133 template <typename ExtendOp> struct ExtendOpTraits { 1134 // Members present: 1135 // 1136 // static const SCEV::NoWrapFlags WrapType; 1137 // 1138 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1139 // 1140 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1141 // ICmpInst::Predicate *Pred, 1142 // ScalarEvolution *SE); 1143 }; 1144 1145 template <> 1146 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1147 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1148 1149 static const GetExtendExprTy GetExtendExpr; 1150 1151 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1152 ICmpInst::Predicate *Pred, 1153 ScalarEvolution *SE) { 1154 return getSignedOverflowLimitForStep(Step, Pred, SE); 1155 } 1156 }; 1157 1158 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1159 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1160 1161 template <> 1162 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1163 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1164 1165 static const GetExtendExprTy GetExtendExpr; 1166 1167 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1168 ICmpInst::Predicate *Pred, 1169 ScalarEvolution *SE) { 1170 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1171 } 1172 }; 1173 1174 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1175 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1176 1177 } // end anonymous namespace 1178 1179 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1180 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1181 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1182 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1183 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1184 // expression "Step + sext/zext(PreIncAR)" is congruent with 1185 // "sext/zext(PostIncAR)" 1186 template <typename ExtendOpTy> 1187 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1188 ScalarEvolution *SE, unsigned Depth) { 1189 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1190 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1191 1192 const Loop *L = AR->getLoop(); 1193 const SCEV *Start = AR->getStart(); 1194 const SCEV *Step = AR->getStepRecurrence(*SE); 1195 1196 // Check for a simple looking step prior to loop entry. 1197 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1198 if (!SA) 1199 return nullptr; 1200 1201 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1202 // subtraction is expensive. For this purpose, perform a quick and dirty 1203 // difference, by checking for Step in the operand list. 1204 SmallVector<const SCEV *, 4> DiffOps; 1205 for (const SCEV *Op : SA->operands()) 1206 if (Op != Step) 1207 DiffOps.push_back(Op); 1208 1209 if (DiffOps.size() == SA->getNumOperands()) 1210 return nullptr; 1211 1212 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1213 // `Step`: 1214 1215 // 1. NSW/NUW flags on the step increment. 1216 auto PreStartFlags = 1217 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1218 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1219 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1220 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1221 1222 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1223 // "S+X does not sign/unsign-overflow". 1224 // 1225 1226 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1227 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1228 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1229 return PreStart; 1230 1231 // 2. Direct overflow check on the step operation's expression. 1232 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1233 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1234 const SCEV *OperandExtendedStart = 1235 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1236 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1237 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1238 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1239 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1240 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1241 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1242 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1243 } 1244 return PreStart; 1245 } 1246 1247 // 3. Loop precondition. 1248 ICmpInst::Predicate Pred; 1249 const SCEV *OverflowLimit = 1250 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1251 1252 if (OverflowLimit && 1253 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1254 return PreStart; 1255 1256 return nullptr; 1257 } 1258 1259 // Get the normalized zero or sign extended expression for this AddRec's Start. 1260 template <typename ExtendOpTy> 1261 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1262 ScalarEvolution *SE, 1263 unsigned Depth) { 1264 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1265 1266 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1267 if (!PreStart) 1268 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1269 1270 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1271 Depth), 1272 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1273 } 1274 1275 // Try to prove away overflow by looking at "nearby" add recurrences. A 1276 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1277 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1278 // 1279 // Formally: 1280 // 1281 // {S,+,X} == {S-T,+,X} + T 1282 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1283 // 1284 // If ({S-T,+,X} + T) does not overflow ... (1) 1285 // 1286 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1287 // 1288 // If {S-T,+,X} does not overflow ... (2) 1289 // 1290 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1291 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1292 // 1293 // If (S-T)+T does not overflow ... (3) 1294 // 1295 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1296 // == {Ext(S),+,Ext(X)} == LHS 1297 // 1298 // Thus, if (1), (2) and (3) are true for some T, then 1299 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1300 // 1301 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1302 // does not overflow" restricted to the 0th iteration. Therefore we only need 1303 // to check for (1) and (2). 1304 // 1305 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1306 // is `Delta` (defined below). 1307 template <typename ExtendOpTy> 1308 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1309 const SCEV *Step, 1310 const Loop *L) { 1311 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1312 1313 // We restrict `Start` to a constant to prevent SCEV from spending too much 1314 // time here. It is correct (but more expensive) to continue with a 1315 // non-constant `Start` and do a general SCEV subtraction to compute 1316 // `PreStart` below. 1317 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1318 if (!StartC) 1319 return false; 1320 1321 APInt StartAI = StartC->getAPInt(); 1322 1323 for (unsigned Delta : {-2, -1, 1, 2}) { 1324 const SCEV *PreStart = getConstant(StartAI - Delta); 1325 1326 FoldingSetNodeID ID; 1327 ID.AddInteger(scAddRecExpr); 1328 ID.AddPointer(PreStart); 1329 ID.AddPointer(Step); 1330 ID.AddPointer(L); 1331 void *IP = nullptr; 1332 const auto *PreAR = 1333 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1334 1335 // Give up if we don't already have the add recurrence we need because 1336 // actually constructing an add recurrence is relatively expensive. 1337 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1338 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1339 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1340 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1341 DeltaS, &Pred, this); 1342 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1343 return true; 1344 } 1345 } 1346 1347 return false; 1348 } 1349 1350 // Finds an integer D for an expression (C + x + y + ...) such that the top 1351 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1352 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1353 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1354 // the (C + x + y + ...) expression is \p WholeAddExpr. 1355 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1356 const SCEVConstant *ConstantTerm, 1357 const SCEVAddExpr *WholeAddExpr) { 1358 const APInt &C = ConstantTerm->getAPInt(); 1359 const unsigned BitWidth = C.getBitWidth(); 1360 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1361 uint32_t TZ = BitWidth; 1362 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1363 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1364 if (TZ) { 1365 // Set D to be as many least significant bits of C as possible while still 1366 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1367 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1368 } 1369 return APInt(BitWidth, 0); 1370 } 1371 1372 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1373 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1374 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1375 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1376 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1377 const APInt &ConstantStart, 1378 const SCEV *Step) { 1379 const unsigned BitWidth = ConstantStart.getBitWidth(); 1380 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1381 if (TZ) 1382 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1383 : ConstantStart; 1384 return APInt(BitWidth, 0); 1385 } 1386 1387 const SCEV * 1388 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1389 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1390 "This is not an extending conversion!"); 1391 assert(isSCEVable(Ty) && 1392 "This is not a conversion to a SCEVable type!"); 1393 Ty = getEffectiveSCEVType(Ty); 1394 1395 // Fold if the operand is constant. 1396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1397 return getConstant( 1398 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1399 1400 // zext(zext(x)) --> zext(x) 1401 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1402 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1403 1404 // Before doing any expensive analysis, check to see if we've already 1405 // computed a SCEV for this Op and Ty. 1406 FoldingSetNodeID ID; 1407 ID.AddInteger(scZeroExtend); 1408 ID.AddPointer(Op); 1409 ID.AddPointer(Ty); 1410 void *IP = nullptr; 1411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1412 if (Depth > MaxCastDepth) { 1413 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1414 Op, Ty); 1415 UniqueSCEVs.InsertNode(S, IP); 1416 addToLoopUseLists(S); 1417 return S; 1418 } 1419 1420 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1421 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1422 // It's possible the bits taken off by the truncate were all zero bits. If 1423 // so, we should be able to simplify this further. 1424 const SCEV *X = ST->getOperand(); 1425 ConstantRange CR = getUnsignedRange(X); 1426 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1427 unsigned NewBits = getTypeSizeInBits(Ty); 1428 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1429 CR.zextOrTrunc(NewBits))) 1430 return getTruncateOrZeroExtend(X, Ty, Depth); 1431 } 1432 1433 // If the input value is a chrec scev, and we can prove that the value 1434 // did not overflow the old, smaller, value, we can zero extend all of the 1435 // operands (often constants). This allows analysis of something like 1436 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1437 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1438 if (AR->isAffine()) { 1439 const SCEV *Start = AR->getStart(); 1440 const SCEV *Step = AR->getStepRecurrence(*this); 1441 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1442 const Loop *L = AR->getLoop(); 1443 1444 if (!AR->hasNoUnsignedWrap()) { 1445 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1446 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1447 } 1448 1449 // If we have special knowledge that this addrec won't overflow, 1450 // we don't need to do any further analysis. 1451 if (AR->hasNoUnsignedWrap()) 1452 return getAddRecExpr( 1453 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1454 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1455 1456 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1457 // Note that this serves two purposes: It filters out loops that are 1458 // simply not analyzable, and it covers the case where this code is 1459 // being called from within backedge-taken count analysis, such that 1460 // attempting to ask for the backedge-taken count would likely result 1461 // in infinite recursion. In the later case, the analysis code will 1462 // cope with a conservative value, and it will take care to purge 1463 // that value once it has finished. 1464 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1465 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1466 // Manually compute the final value for AR, checking for 1467 // overflow. 1468 1469 // Check whether the backedge-taken count can be losslessly casted to 1470 // the addrec's type. The count is always unsigned. 1471 const SCEV *CastedMaxBECount = 1472 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1473 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1474 CastedMaxBECount, MaxBECount->getType(), Depth); 1475 if (MaxBECount == RecastedMaxBECount) { 1476 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1477 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1478 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1479 SCEV::FlagAnyWrap, Depth + 1); 1480 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1481 SCEV::FlagAnyWrap, 1482 Depth + 1), 1483 WideTy, Depth + 1); 1484 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1485 const SCEV *WideMaxBECount = 1486 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1487 const SCEV *OperandExtendedAdd = 1488 getAddExpr(WideStart, 1489 getMulExpr(WideMaxBECount, 1490 getZeroExtendExpr(Step, WideTy, Depth + 1), 1491 SCEV::FlagAnyWrap, Depth + 1), 1492 SCEV::FlagAnyWrap, Depth + 1); 1493 if (ZAdd == OperandExtendedAdd) { 1494 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1495 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1496 // Return the expression with the addrec on the outside. 1497 return getAddRecExpr( 1498 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1499 Depth + 1), 1500 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1501 AR->getNoWrapFlags()); 1502 } 1503 // Similar to above, only this time treat the step value as signed. 1504 // This covers loops that count down. 1505 OperandExtendedAdd = 1506 getAddExpr(WideStart, 1507 getMulExpr(WideMaxBECount, 1508 getSignExtendExpr(Step, WideTy, Depth + 1), 1509 SCEV::FlagAnyWrap, Depth + 1), 1510 SCEV::FlagAnyWrap, Depth + 1); 1511 if (ZAdd == OperandExtendedAdd) { 1512 // Cache knowledge of AR NW, which is propagated to this AddRec. 1513 // Negative step causes unsigned wrap, but it still can't self-wrap. 1514 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1515 // Return the expression with the addrec on the outside. 1516 return getAddRecExpr( 1517 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1518 Depth + 1), 1519 getSignExtendExpr(Step, Ty, Depth + 1), L, 1520 AR->getNoWrapFlags()); 1521 } 1522 } 1523 } 1524 1525 // Normally, in the cases we can prove no-overflow via a 1526 // backedge guarding condition, we can also compute a backedge 1527 // taken count for the loop. The exceptions are assumptions and 1528 // guards present in the loop -- SCEV is not great at exploiting 1529 // these to compute max backedge taken counts, but can still use 1530 // these to prove lack of overflow. Use this fact to avoid 1531 // doing extra work that may not pay off. 1532 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1533 !AC.assumptions().empty()) { 1534 // If the backedge is guarded by a comparison with the pre-inc 1535 // value the addrec is safe. Also, if the entry is guarded by 1536 // a comparison with the start value and the backedge is 1537 // guarded by a comparison with the post-inc value, the addrec 1538 // is safe. 1539 if (isKnownPositive(Step)) { 1540 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1541 getUnsignedRangeMax(Step)); 1542 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1543 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1544 // Cache knowledge of AR NUW, which is propagated to this 1545 // AddRec. 1546 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1547 // Return the expression with the addrec on the outside. 1548 return getAddRecExpr( 1549 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1550 Depth + 1), 1551 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1552 AR->getNoWrapFlags()); 1553 } 1554 } else if (isKnownNegative(Step)) { 1555 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1556 getSignedRangeMin(Step)); 1557 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1558 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1559 // Cache knowledge of AR NW, which is propagated to this 1560 // AddRec. Negative step causes unsigned wrap, but it 1561 // still can't self-wrap. 1562 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1563 // Return the expression with the addrec on the outside. 1564 return getAddRecExpr( 1565 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1566 Depth + 1), 1567 getSignExtendExpr(Step, Ty, Depth + 1), L, 1568 AR->getNoWrapFlags()); 1569 } 1570 } 1571 } 1572 1573 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1574 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1575 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1576 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1577 const APInt &C = SC->getAPInt(); 1578 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1579 if (D != 0) { 1580 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1581 const SCEV *SResidual = 1582 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1583 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1584 return getAddExpr(SZExtD, SZExtR, 1585 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1586 Depth + 1); 1587 } 1588 } 1589 1590 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1591 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1592 return getAddRecExpr( 1593 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1594 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1595 } 1596 } 1597 1598 // zext(A % B) --> zext(A) % zext(B) 1599 { 1600 const SCEV *LHS; 1601 const SCEV *RHS; 1602 if (matchURem(Op, LHS, RHS)) 1603 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1604 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1605 } 1606 1607 // zext(A / B) --> zext(A) / zext(B). 1608 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1609 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1610 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1611 1612 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1613 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1614 if (SA->hasNoUnsignedWrap()) { 1615 // If the addition does not unsign overflow then we can, by definition, 1616 // commute the zero extension with the addition operation. 1617 SmallVector<const SCEV *, 4> Ops; 1618 for (const auto *Op : SA->operands()) 1619 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1620 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1621 } 1622 1623 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1624 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1625 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1626 // 1627 // Often address arithmetics contain expressions like 1628 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1629 // This transformation is useful while proving that such expressions are 1630 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1631 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1632 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1633 if (D != 0) { 1634 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1635 const SCEV *SResidual = 1636 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1637 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1638 return getAddExpr(SZExtD, SZExtR, 1639 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1640 Depth + 1); 1641 } 1642 } 1643 } 1644 1645 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1646 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1647 if (SM->hasNoUnsignedWrap()) { 1648 // If the multiply does not unsign overflow then we can, by definition, 1649 // commute the zero extension with the multiply operation. 1650 SmallVector<const SCEV *, 4> Ops; 1651 for (const auto *Op : SM->operands()) 1652 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1653 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1654 } 1655 1656 // zext(2^K * (trunc X to iN)) to iM -> 1657 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1658 // 1659 // Proof: 1660 // 1661 // zext(2^K * (trunc X to iN)) to iM 1662 // = zext((trunc X to iN) << K) to iM 1663 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1664 // (because shl removes the top K bits) 1665 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1666 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1667 // 1668 if (SM->getNumOperands() == 2) 1669 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1670 if (MulLHS->getAPInt().isPowerOf2()) 1671 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1672 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1673 MulLHS->getAPInt().logBase2(); 1674 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1675 return getMulExpr( 1676 getZeroExtendExpr(MulLHS, Ty), 1677 getZeroExtendExpr( 1678 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1679 SCEV::FlagNUW, Depth + 1); 1680 } 1681 } 1682 1683 // The cast wasn't folded; create an explicit cast node. 1684 // Recompute the insert position, as it may have been invalidated. 1685 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1686 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1687 Op, Ty); 1688 UniqueSCEVs.InsertNode(S, IP); 1689 addToLoopUseLists(S); 1690 return S; 1691 } 1692 1693 const SCEV * 1694 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1695 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1696 "This is not an extending conversion!"); 1697 assert(isSCEVable(Ty) && 1698 "This is not a conversion to a SCEVable type!"); 1699 Ty = getEffectiveSCEVType(Ty); 1700 1701 // Fold if the operand is constant. 1702 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1703 return getConstant( 1704 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1705 1706 // sext(sext(x)) --> sext(x) 1707 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1708 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1709 1710 // sext(zext(x)) --> zext(x) 1711 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1712 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1713 1714 // Before doing any expensive analysis, check to see if we've already 1715 // computed a SCEV for this Op and Ty. 1716 FoldingSetNodeID ID; 1717 ID.AddInteger(scSignExtend); 1718 ID.AddPointer(Op); 1719 ID.AddPointer(Ty); 1720 void *IP = nullptr; 1721 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1722 // Limit recursion depth. 1723 if (Depth > MaxCastDepth) { 1724 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1725 Op, Ty); 1726 UniqueSCEVs.InsertNode(S, IP); 1727 addToLoopUseLists(S); 1728 return S; 1729 } 1730 1731 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1732 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1733 // It's possible the bits taken off by the truncate were all sign bits. If 1734 // so, we should be able to simplify this further. 1735 const SCEV *X = ST->getOperand(); 1736 ConstantRange CR = getSignedRange(X); 1737 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1738 unsigned NewBits = getTypeSizeInBits(Ty); 1739 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1740 CR.sextOrTrunc(NewBits))) 1741 return getTruncateOrSignExtend(X, Ty, Depth); 1742 } 1743 1744 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1745 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1746 if (SA->hasNoSignedWrap()) { 1747 // If the addition does not sign overflow then we can, by definition, 1748 // commute the sign extension with the addition operation. 1749 SmallVector<const SCEV *, 4> Ops; 1750 for (const auto *Op : SA->operands()) 1751 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1752 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1753 } 1754 1755 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1756 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1757 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1758 // 1759 // For instance, this will bring two seemingly different expressions: 1760 // 1 + sext(5 + 20 * %x + 24 * %y) and 1761 // sext(6 + 20 * %x + 24 * %y) 1762 // to the same form: 1763 // 2 + sext(4 + 20 * %x + 24 * %y) 1764 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1765 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1766 if (D != 0) { 1767 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1768 const SCEV *SResidual = 1769 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1770 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1771 return getAddExpr(SSExtD, SSExtR, 1772 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1773 Depth + 1); 1774 } 1775 } 1776 } 1777 // If the input value is a chrec scev, and we can prove that the value 1778 // did not overflow the old, smaller, value, we can sign extend all of the 1779 // operands (often constants). This allows analysis of something like 1780 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1781 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1782 if (AR->isAffine()) { 1783 const SCEV *Start = AR->getStart(); 1784 const SCEV *Step = AR->getStepRecurrence(*this); 1785 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1786 const Loop *L = AR->getLoop(); 1787 1788 if (!AR->hasNoSignedWrap()) { 1789 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1790 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1791 } 1792 1793 // If we have special knowledge that this addrec won't overflow, 1794 // we don't need to do any further analysis. 1795 if (AR->hasNoSignedWrap()) 1796 return getAddRecExpr( 1797 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1798 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1799 1800 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1801 // Note that this serves two purposes: It filters out loops that are 1802 // simply not analyzable, and it covers the case where this code is 1803 // being called from within backedge-taken count analysis, such that 1804 // attempting to ask for the backedge-taken count would likely result 1805 // in infinite recursion. In the later case, the analysis code will 1806 // cope with a conservative value, and it will take care to purge 1807 // that value once it has finished. 1808 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1809 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1810 // Manually compute the final value for AR, checking for 1811 // overflow. 1812 1813 // Check whether the backedge-taken count can be losslessly casted to 1814 // the addrec's type. The count is always unsigned. 1815 const SCEV *CastedMaxBECount = 1816 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1817 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1818 CastedMaxBECount, MaxBECount->getType(), Depth); 1819 if (MaxBECount == RecastedMaxBECount) { 1820 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1821 // Check whether Start+Step*MaxBECount has no signed overflow. 1822 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1823 SCEV::FlagAnyWrap, Depth + 1); 1824 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1825 SCEV::FlagAnyWrap, 1826 Depth + 1), 1827 WideTy, Depth + 1); 1828 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1829 const SCEV *WideMaxBECount = 1830 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1831 const SCEV *OperandExtendedAdd = 1832 getAddExpr(WideStart, 1833 getMulExpr(WideMaxBECount, 1834 getSignExtendExpr(Step, WideTy, Depth + 1), 1835 SCEV::FlagAnyWrap, Depth + 1), 1836 SCEV::FlagAnyWrap, Depth + 1); 1837 if (SAdd == OperandExtendedAdd) { 1838 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1839 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1840 // Return the expression with the addrec on the outside. 1841 return getAddRecExpr( 1842 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1843 Depth + 1), 1844 getSignExtendExpr(Step, Ty, Depth + 1), L, 1845 AR->getNoWrapFlags()); 1846 } 1847 // Similar to above, only this time treat the step value as unsigned. 1848 // This covers loops that count up with an unsigned step. 1849 OperandExtendedAdd = 1850 getAddExpr(WideStart, 1851 getMulExpr(WideMaxBECount, 1852 getZeroExtendExpr(Step, WideTy, Depth + 1), 1853 SCEV::FlagAnyWrap, Depth + 1), 1854 SCEV::FlagAnyWrap, Depth + 1); 1855 if (SAdd == OperandExtendedAdd) { 1856 // If AR wraps around then 1857 // 1858 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1859 // => SAdd != OperandExtendedAdd 1860 // 1861 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1862 // (SAdd == OperandExtendedAdd => AR is NW) 1863 1864 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1865 1866 // Return the expression with the addrec on the outside. 1867 return getAddRecExpr( 1868 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1869 Depth + 1), 1870 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1871 AR->getNoWrapFlags()); 1872 } 1873 } 1874 } 1875 1876 // Normally, in the cases we can prove no-overflow via a 1877 // backedge guarding condition, we can also compute a backedge 1878 // taken count for the loop. The exceptions are assumptions and 1879 // guards present in the loop -- SCEV is not great at exploiting 1880 // these to compute max backedge taken counts, but can still use 1881 // these to prove lack of overflow. Use this fact to avoid 1882 // doing extra work that may not pay off. 1883 1884 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1885 !AC.assumptions().empty()) { 1886 // If the backedge is guarded by a comparison with the pre-inc 1887 // value the addrec is safe. Also, if the entry is guarded by 1888 // a comparison with the start value and the backedge is 1889 // guarded by a comparison with the post-inc value, the addrec 1890 // is safe. 1891 ICmpInst::Predicate Pred; 1892 const SCEV *OverflowLimit = 1893 getSignedOverflowLimitForStep(Step, &Pred, this); 1894 if (OverflowLimit && 1895 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1896 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1897 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1898 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1899 return getAddRecExpr( 1900 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1901 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1902 } 1903 } 1904 1905 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 1906 // if D + (C - D + Step * n) could be proven to not signed wrap 1907 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1908 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1909 const APInt &C = SC->getAPInt(); 1910 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1911 if (D != 0) { 1912 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1913 const SCEV *SResidual = 1914 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1915 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1916 return getAddExpr(SSExtD, SSExtR, 1917 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1918 Depth + 1); 1919 } 1920 } 1921 1922 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1923 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1924 return getAddRecExpr( 1925 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1926 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1927 } 1928 } 1929 1930 // If the input value is provably positive and we could not simplify 1931 // away the sext build a zext instead. 1932 if (isKnownNonNegative(Op)) 1933 return getZeroExtendExpr(Op, Ty, Depth + 1); 1934 1935 // The cast wasn't folded; create an explicit cast node. 1936 // Recompute the insert position, as it may have been invalidated. 1937 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1938 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1939 Op, Ty); 1940 UniqueSCEVs.InsertNode(S, IP); 1941 addToLoopUseLists(S); 1942 return S; 1943 } 1944 1945 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1946 /// unspecified bits out to the given type. 1947 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1948 Type *Ty) { 1949 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1950 "This is not an extending conversion!"); 1951 assert(isSCEVable(Ty) && 1952 "This is not a conversion to a SCEVable type!"); 1953 Ty = getEffectiveSCEVType(Ty); 1954 1955 // Sign-extend negative constants. 1956 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1957 if (SC->getAPInt().isNegative()) 1958 return getSignExtendExpr(Op, Ty); 1959 1960 // Peel off a truncate cast. 1961 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1962 const SCEV *NewOp = T->getOperand(); 1963 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1964 return getAnyExtendExpr(NewOp, Ty); 1965 return getTruncateOrNoop(NewOp, Ty); 1966 } 1967 1968 // Next try a zext cast. If the cast is folded, use it. 1969 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1970 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1971 return ZExt; 1972 1973 // Next try a sext cast. If the cast is folded, use it. 1974 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1975 if (!isa<SCEVSignExtendExpr>(SExt)) 1976 return SExt; 1977 1978 // Force the cast to be folded into the operands of an addrec. 1979 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1980 SmallVector<const SCEV *, 4> Ops; 1981 for (const SCEV *Op : AR->operands()) 1982 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1983 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1984 } 1985 1986 // If the expression is obviously signed, use the sext cast value. 1987 if (isa<SCEVSMaxExpr>(Op)) 1988 return SExt; 1989 1990 // Absent any other information, use the zext cast value. 1991 return ZExt; 1992 } 1993 1994 /// Process the given Ops list, which is a list of operands to be added under 1995 /// the given scale, update the given map. This is a helper function for 1996 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1997 /// that would form an add expression like this: 1998 /// 1999 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2000 /// 2001 /// where A and B are constants, update the map with these values: 2002 /// 2003 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2004 /// 2005 /// and add 13 + A*B*29 to AccumulatedConstant. 2006 /// This will allow getAddRecExpr to produce this: 2007 /// 2008 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2009 /// 2010 /// This form often exposes folding opportunities that are hidden in 2011 /// the original operand list. 2012 /// 2013 /// Return true iff it appears that any interesting folding opportunities 2014 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2015 /// the common case where no interesting opportunities are present, and 2016 /// is also used as a check to avoid infinite recursion. 2017 static bool 2018 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2019 SmallVectorImpl<const SCEV *> &NewOps, 2020 APInt &AccumulatedConstant, 2021 const SCEV *const *Ops, size_t NumOperands, 2022 const APInt &Scale, 2023 ScalarEvolution &SE) { 2024 bool Interesting = false; 2025 2026 // Iterate over the add operands. They are sorted, with constants first. 2027 unsigned i = 0; 2028 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2029 ++i; 2030 // Pull a buried constant out to the outside. 2031 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2032 Interesting = true; 2033 AccumulatedConstant += Scale * C->getAPInt(); 2034 } 2035 2036 // Next comes everything else. We're especially interested in multiplies 2037 // here, but they're in the middle, so just visit the rest with one loop. 2038 for (; i != NumOperands; ++i) { 2039 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2040 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2041 APInt NewScale = 2042 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2043 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2044 // A multiplication of a constant with another add; recurse. 2045 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2046 Interesting |= 2047 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2048 Add->op_begin(), Add->getNumOperands(), 2049 NewScale, SE); 2050 } else { 2051 // A multiplication of a constant with some other value. Update 2052 // the map. 2053 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2054 const SCEV *Key = SE.getMulExpr(MulOps); 2055 auto Pair = M.insert({Key, NewScale}); 2056 if (Pair.second) { 2057 NewOps.push_back(Pair.first->first); 2058 } else { 2059 Pair.first->second += NewScale; 2060 // The map already had an entry for this value, which may indicate 2061 // a folding opportunity. 2062 Interesting = true; 2063 } 2064 } 2065 } else { 2066 // An ordinary operand. Update the map. 2067 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2068 M.insert({Ops[i], Scale}); 2069 if (Pair.second) { 2070 NewOps.push_back(Pair.first->first); 2071 } else { 2072 Pair.first->second += Scale; 2073 // The map already had an entry for this value, which may indicate 2074 // a folding opportunity. 2075 Interesting = true; 2076 } 2077 } 2078 } 2079 2080 return Interesting; 2081 } 2082 2083 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2084 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2085 // can't-overflow flags for the operation if possible. 2086 static SCEV::NoWrapFlags 2087 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2088 const ArrayRef<const SCEV *> Ops, 2089 SCEV::NoWrapFlags Flags) { 2090 using namespace std::placeholders; 2091 2092 using OBO = OverflowingBinaryOperator; 2093 2094 bool CanAnalyze = 2095 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2096 (void)CanAnalyze; 2097 assert(CanAnalyze && "don't call from other places!"); 2098 2099 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2100 SCEV::NoWrapFlags SignOrUnsignWrap = 2101 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2102 2103 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2104 auto IsKnownNonNegative = [&](const SCEV *S) { 2105 return SE->isKnownNonNegative(S); 2106 }; 2107 2108 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2109 Flags = 2110 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2111 2112 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2113 2114 if (SignOrUnsignWrap != SignOrUnsignMask && 2115 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2116 isa<SCEVConstant>(Ops[0])) { 2117 2118 auto Opcode = [&] { 2119 switch (Type) { 2120 case scAddExpr: 2121 return Instruction::Add; 2122 case scMulExpr: 2123 return Instruction::Mul; 2124 default: 2125 llvm_unreachable("Unexpected SCEV op."); 2126 } 2127 }(); 2128 2129 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2130 2131 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2132 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2133 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2134 Opcode, C, OBO::NoSignedWrap); 2135 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2136 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2137 } 2138 2139 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2140 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2141 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2142 Opcode, C, OBO::NoUnsignedWrap); 2143 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2144 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2145 } 2146 } 2147 2148 return Flags; 2149 } 2150 2151 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2152 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2153 } 2154 2155 /// Get a canonical add expression, or something simpler if possible. 2156 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2157 SCEV::NoWrapFlags Flags, 2158 unsigned Depth) { 2159 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2160 "only nuw or nsw allowed"); 2161 assert(!Ops.empty() && "Cannot get empty add!"); 2162 if (Ops.size() == 1) return Ops[0]; 2163 #ifndef NDEBUG 2164 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2165 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2166 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2167 "SCEVAddExpr operand types don't match!"); 2168 #endif 2169 2170 // Sort by complexity, this groups all similar expression types together. 2171 GroupByComplexity(Ops, &LI, DT); 2172 2173 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2174 2175 // If there are any constants, fold them together. 2176 unsigned Idx = 0; 2177 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2178 ++Idx; 2179 assert(Idx < Ops.size()); 2180 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2181 // We found two constants, fold them together! 2182 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2183 if (Ops.size() == 2) return Ops[0]; 2184 Ops.erase(Ops.begin()+1); // Erase the folded element 2185 LHSC = cast<SCEVConstant>(Ops[0]); 2186 } 2187 2188 // If we are left with a constant zero being added, strip it off. 2189 if (LHSC->getValue()->isZero()) { 2190 Ops.erase(Ops.begin()); 2191 --Idx; 2192 } 2193 2194 if (Ops.size() == 1) return Ops[0]; 2195 } 2196 2197 // Limit recursion calls depth. 2198 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2199 return getOrCreateAddExpr(Ops, Flags); 2200 2201 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2202 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2203 return S; 2204 } 2205 2206 // Okay, check to see if the same value occurs in the operand list more than 2207 // once. If so, merge them together into an multiply expression. Since we 2208 // sorted the list, these values are required to be adjacent. 2209 Type *Ty = Ops[0]->getType(); 2210 bool FoundMatch = false; 2211 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2212 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2213 // Scan ahead to count how many equal operands there are. 2214 unsigned Count = 2; 2215 while (i+Count != e && Ops[i+Count] == Ops[i]) 2216 ++Count; 2217 // Merge the values into a multiply. 2218 const SCEV *Scale = getConstant(Ty, Count); 2219 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2220 if (Ops.size() == Count) 2221 return Mul; 2222 Ops[i] = Mul; 2223 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2224 --i; e -= Count - 1; 2225 FoundMatch = true; 2226 } 2227 if (FoundMatch) 2228 return getAddExpr(Ops, Flags, Depth + 1); 2229 2230 // Check for truncates. If all the operands are truncated from the same 2231 // type, see if factoring out the truncate would permit the result to be 2232 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2233 // if the contents of the resulting outer trunc fold to something simple. 2234 auto FindTruncSrcType = [&]() -> Type * { 2235 // We're ultimately looking to fold an addrec of truncs and muls of only 2236 // constants and truncs, so if we find any other types of SCEV 2237 // as operands of the addrec then we bail and return nullptr here. 2238 // Otherwise, we return the type of the operand of a trunc that we find. 2239 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2240 return T->getOperand()->getType(); 2241 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2242 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2243 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2244 return T->getOperand()->getType(); 2245 } 2246 return nullptr; 2247 }; 2248 if (auto *SrcType = FindTruncSrcType()) { 2249 SmallVector<const SCEV *, 8> LargeOps; 2250 bool Ok = true; 2251 // Check all the operands to see if they can be represented in the 2252 // source type of the truncate. 2253 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2254 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2255 if (T->getOperand()->getType() != SrcType) { 2256 Ok = false; 2257 break; 2258 } 2259 LargeOps.push_back(T->getOperand()); 2260 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2261 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2262 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2263 SmallVector<const SCEV *, 8> LargeMulOps; 2264 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2265 if (const SCEVTruncateExpr *T = 2266 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2267 if (T->getOperand()->getType() != SrcType) { 2268 Ok = false; 2269 break; 2270 } 2271 LargeMulOps.push_back(T->getOperand()); 2272 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2273 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2274 } else { 2275 Ok = false; 2276 break; 2277 } 2278 } 2279 if (Ok) 2280 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2281 } else { 2282 Ok = false; 2283 break; 2284 } 2285 } 2286 if (Ok) { 2287 // Evaluate the expression in the larger type. 2288 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2289 // If it folds to something simple, use it. Otherwise, don't. 2290 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2291 return getTruncateExpr(Fold, Ty); 2292 } 2293 } 2294 2295 // Skip past any other cast SCEVs. 2296 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2297 ++Idx; 2298 2299 // If there are add operands they would be next. 2300 if (Idx < Ops.size()) { 2301 bool DeletedAdd = false; 2302 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2303 if (Ops.size() > AddOpsInlineThreshold || 2304 Add->getNumOperands() > AddOpsInlineThreshold) 2305 break; 2306 // If we have an add, expand the add operands onto the end of the operands 2307 // list. 2308 Ops.erase(Ops.begin()+Idx); 2309 Ops.append(Add->op_begin(), Add->op_end()); 2310 DeletedAdd = true; 2311 } 2312 2313 // If we deleted at least one add, we added operands to the end of the list, 2314 // and they are not necessarily sorted. Recurse to resort and resimplify 2315 // any operands we just acquired. 2316 if (DeletedAdd) 2317 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2318 } 2319 2320 // Skip over the add expression until we get to a multiply. 2321 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2322 ++Idx; 2323 2324 // Check to see if there are any folding opportunities present with 2325 // operands multiplied by constant values. 2326 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2327 uint64_t BitWidth = getTypeSizeInBits(Ty); 2328 DenseMap<const SCEV *, APInt> M; 2329 SmallVector<const SCEV *, 8> NewOps; 2330 APInt AccumulatedConstant(BitWidth, 0); 2331 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2332 Ops.data(), Ops.size(), 2333 APInt(BitWidth, 1), *this)) { 2334 struct APIntCompare { 2335 bool operator()(const APInt &LHS, const APInt &RHS) const { 2336 return LHS.ult(RHS); 2337 } 2338 }; 2339 2340 // Some interesting folding opportunity is present, so its worthwhile to 2341 // re-generate the operands list. Group the operands by constant scale, 2342 // to avoid multiplying by the same constant scale multiple times. 2343 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2344 for (const SCEV *NewOp : NewOps) 2345 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2346 // Re-generate the operands list. 2347 Ops.clear(); 2348 if (AccumulatedConstant != 0) 2349 Ops.push_back(getConstant(AccumulatedConstant)); 2350 for (auto &MulOp : MulOpLists) 2351 if (MulOp.first != 0) 2352 Ops.push_back(getMulExpr( 2353 getConstant(MulOp.first), 2354 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2355 SCEV::FlagAnyWrap, Depth + 1)); 2356 if (Ops.empty()) 2357 return getZero(Ty); 2358 if (Ops.size() == 1) 2359 return Ops[0]; 2360 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2361 } 2362 } 2363 2364 // If we are adding something to a multiply expression, make sure the 2365 // something is not already an operand of the multiply. If so, merge it into 2366 // the multiply. 2367 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2368 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2369 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2370 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2371 if (isa<SCEVConstant>(MulOpSCEV)) 2372 continue; 2373 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2374 if (MulOpSCEV == Ops[AddOp]) { 2375 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2376 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2377 if (Mul->getNumOperands() != 2) { 2378 // If the multiply has more than two operands, we must get the 2379 // Y*Z term. 2380 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2381 Mul->op_begin()+MulOp); 2382 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2383 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2384 } 2385 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2386 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2387 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2388 SCEV::FlagAnyWrap, Depth + 1); 2389 if (Ops.size() == 2) return OuterMul; 2390 if (AddOp < Idx) { 2391 Ops.erase(Ops.begin()+AddOp); 2392 Ops.erase(Ops.begin()+Idx-1); 2393 } else { 2394 Ops.erase(Ops.begin()+Idx); 2395 Ops.erase(Ops.begin()+AddOp-1); 2396 } 2397 Ops.push_back(OuterMul); 2398 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2399 } 2400 2401 // Check this multiply against other multiplies being added together. 2402 for (unsigned OtherMulIdx = Idx+1; 2403 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2404 ++OtherMulIdx) { 2405 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2406 // If MulOp occurs in OtherMul, we can fold the two multiplies 2407 // together. 2408 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2409 OMulOp != e; ++OMulOp) 2410 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2411 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2412 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2413 if (Mul->getNumOperands() != 2) { 2414 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2415 Mul->op_begin()+MulOp); 2416 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2417 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2418 } 2419 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2420 if (OtherMul->getNumOperands() != 2) { 2421 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2422 OtherMul->op_begin()+OMulOp); 2423 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2424 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2425 } 2426 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2427 const SCEV *InnerMulSum = 2428 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2429 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2430 SCEV::FlagAnyWrap, Depth + 1); 2431 if (Ops.size() == 2) return OuterMul; 2432 Ops.erase(Ops.begin()+Idx); 2433 Ops.erase(Ops.begin()+OtherMulIdx-1); 2434 Ops.push_back(OuterMul); 2435 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2436 } 2437 } 2438 } 2439 } 2440 2441 // If there are any add recurrences in the operands list, see if any other 2442 // added values are loop invariant. If so, we can fold them into the 2443 // recurrence. 2444 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2445 ++Idx; 2446 2447 // Scan over all recurrences, trying to fold loop invariants into them. 2448 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2449 // Scan all of the other operands to this add and add them to the vector if 2450 // they are loop invariant w.r.t. the recurrence. 2451 SmallVector<const SCEV *, 8> LIOps; 2452 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2453 const Loop *AddRecLoop = AddRec->getLoop(); 2454 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2455 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2456 LIOps.push_back(Ops[i]); 2457 Ops.erase(Ops.begin()+i); 2458 --i; --e; 2459 } 2460 2461 // If we found some loop invariants, fold them into the recurrence. 2462 if (!LIOps.empty()) { 2463 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2464 LIOps.push_back(AddRec->getStart()); 2465 2466 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2467 AddRec->op_end()); 2468 // This follows from the fact that the no-wrap flags on the outer add 2469 // expression are applicable on the 0th iteration, when the add recurrence 2470 // will be equal to its start value. 2471 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2472 2473 // Build the new addrec. Propagate the NUW and NSW flags if both the 2474 // outer add and the inner addrec are guaranteed to have no overflow. 2475 // Always propagate NW. 2476 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2477 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2478 2479 // If all of the other operands were loop invariant, we are done. 2480 if (Ops.size() == 1) return NewRec; 2481 2482 // Otherwise, add the folded AddRec by the non-invariant parts. 2483 for (unsigned i = 0;; ++i) 2484 if (Ops[i] == AddRec) { 2485 Ops[i] = NewRec; 2486 break; 2487 } 2488 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2489 } 2490 2491 // Okay, if there weren't any loop invariants to be folded, check to see if 2492 // there are multiple AddRec's with the same loop induction variable being 2493 // added together. If so, we can fold them. 2494 for (unsigned OtherIdx = Idx+1; 2495 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2496 ++OtherIdx) { 2497 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2498 // so that the 1st found AddRecExpr is dominated by all others. 2499 assert(DT.dominates( 2500 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2501 AddRec->getLoop()->getHeader()) && 2502 "AddRecExprs are not sorted in reverse dominance order?"); 2503 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2504 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2505 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2506 AddRec->op_end()); 2507 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2508 ++OtherIdx) { 2509 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2510 if (OtherAddRec->getLoop() == AddRecLoop) { 2511 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2512 i != e; ++i) { 2513 if (i >= AddRecOps.size()) { 2514 AddRecOps.append(OtherAddRec->op_begin()+i, 2515 OtherAddRec->op_end()); 2516 break; 2517 } 2518 SmallVector<const SCEV *, 2> TwoOps = { 2519 AddRecOps[i], OtherAddRec->getOperand(i)}; 2520 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2521 } 2522 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2523 } 2524 } 2525 // Step size has changed, so we cannot guarantee no self-wraparound. 2526 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2527 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2528 } 2529 } 2530 2531 // Otherwise couldn't fold anything into this recurrence. Move onto the 2532 // next one. 2533 } 2534 2535 // Okay, it looks like we really DO need an add expr. Check to see if we 2536 // already have one, otherwise create a new one. 2537 return getOrCreateAddExpr(Ops, Flags); 2538 } 2539 2540 const SCEV * 2541 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2542 SCEV::NoWrapFlags Flags) { 2543 FoldingSetNodeID ID; 2544 ID.AddInteger(scAddExpr); 2545 for (const SCEV *Op : Ops) 2546 ID.AddPointer(Op); 2547 void *IP = nullptr; 2548 SCEVAddExpr *S = 2549 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2550 if (!S) { 2551 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2552 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2553 S = new (SCEVAllocator) 2554 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2555 UniqueSCEVs.InsertNode(S, IP); 2556 addToLoopUseLists(S); 2557 } 2558 S->setNoWrapFlags(Flags); 2559 return S; 2560 } 2561 2562 const SCEV * 2563 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2564 const Loop *L, SCEV::NoWrapFlags Flags) { 2565 FoldingSetNodeID ID; 2566 ID.AddInteger(scAddRecExpr); 2567 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2568 ID.AddPointer(Ops[i]); 2569 ID.AddPointer(L); 2570 void *IP = nullptr; 2571 SCEVAddRecExpr *S = 2572 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2573 if (!S) { 2574 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2575 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2576 S = new (SCEVAllocator) 2577 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2578 UniqueSCEVs.InsertNode(S, IP); 2579 addToLoopUseLists(S); 2580 } 2581 S->setNoWrapFlags(Flags); 2582 return S; 2583 } 2584 2585 const SCEV * 2586 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2587 SCEV::NoWrapFlags Flags) { 2588 FoldingSetNodeID ID; 2589 ID.AddInteger(scMulExpr); 2590 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2591 ID.AddPointer(Ops[i]); 2592 void *IP = nullptr; 2593 SCEVMulExpr *S = 2594 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2595 if (!S) { 2596 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2597 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2598 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2599 O, Ops.size()); 2600 UniqueSCEVs.InsertNode(S, IP); 2601 addToLoopUseLists(S); 2602 } 2603 S->setNoWrapFlags(Flags); 2604 return S; 2605 } 2606 2607 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2608 uint64_t k = i*j; 2609 if (j > 1 && k / j != i) Overflow = true; 2610 return k; 2611 } 2612 2613 /// Compute the result of "n choose k", the binomial coefficient. If an 2614 /// intermediate computation overflows, Overflow will be set and the return will 2615 /// be garbage. Overflow is not cleared on absence of overflow. 2616 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2617 // We use the multiplicative formula: 2618 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2619 // At each iteration, we take the n-th term of the numeral and divide by the 2620 // (k-n)th term of the denominator. This division will always produce an 2621 // integral result, and helps reduce the chance of overflow in the 2622 // intermediate computations. However, we can still overflow even when the 2623 // final result would fit. 2624 2625 if (n == 0 || n == k) return 1; 2626 if (k > n) return 0; 2627 2628 if (k > n/2) 2629 k = n-k; 2630 2631 uint64_t r = 1; 2632 for (uint64_t i = 1; i <= k; ++i) { 2633 r = umul_ov(r, n-(i-1), Overflow); 2634 r /= i; 2635 } 2636 return r; 2637 } 2638 2639 /// Determine if any of the operands in this SCEV are a constant or if 2640 /// any of the add or multiply expressions in this SCEV contain a constant. 2641 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2642 struct FindConstantInAddMulChain { 2643 bool FoundConstant = false; 2644 2645 bool follow(const SCEV *S) { 2646 FoundConstant |= isa<SCEVConstant>(S); 2647 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2648 } 2649 2650 bool isDone() const { 2651 return FoundConstant; 2652 } 2653 }; 2654 2655 FindConstantInAddMulChain F; 2656 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2657 ST.visitAll(StartExpr); 2658 return F.FoundConstant; 2659 } 2660 2661 /// Get a canonical multiply expression, or something simpler if possible. 2662 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2663 SCEV::NoWrapFlags Flags, 2664 unsigned Depth) { 2665 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2666 "only nuw or nsw allowed"); 2667 assert(!Ops.empty() && "Cannot get empty mul!"); 2668 if (Ops.size() == 1) return Ops[0]; 2669 #ifndef NDEBUG 2670 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2671 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2672 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2673 "SCEVMulExpr operand types don't match!"); 2674 #endif 2675 2676 // Sort by complexity, this groups all similar expression types together. 2677 GroupByComplexity(Ops, &LI, DT); 2678 2679 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2680 2681 // Limit recursion calls depth, but fold all-constant expressions. 2682 // `Ops` is sorted, so it's enough to check just last one. 2683 if ((Depth > MaxArithDepth || hasHugeExpression(Ops)) && 2684 !isa<SCEVConstant>(Ops.back())) 2685 return getOrCreateMulExpr(Ops, Flags); 2686 2687 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2688 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2689 return S; 2690 } 2691 2692 // If there are any constants, fold them together. 2693 unsigned Idx = 0; 2694 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2695 2696 if (Ops.size() == 2) 2697 // C1*(C2+V) -> C1*C2 + C1*V 2698 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2699 // If any of Add's ops are Adds or Muls with a constant, apply this 2700 // transformation as well. 2701 // 2702 // TODO: There are some cases where this transformation is not 2703 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2704 // this transformation should be narrowed down. 2705 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2706 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2707 SCEV::FlagAnyWrap, Depth + 1), 2708 getMulExpr(LHSC, Add->getOperand(1), 2709 SCEV::FlagAnyWrap, Depth + 1), 2710 SCEV::FlagAnyWrap, Depth + 1); 2711 2712 ++Idx; 2713 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2714 // We found two constants, fold them together! 2715 ConstantInt *Fold = 2716 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2717 Ops[0] = getConstant(Fold); 2718 Ops.erase(Ops.begin()+1); // Erase the folded element 2719 if (Ops.size() == 1) return Ops[0]; 2720 LHSC = cast<SCEVConstant>(Ops[0]); 2721 } 2722 2723 // If we are left with a constant one being multiplied, strip it off. 2724 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2725 Ops.erase(Ops.begin()); 2726 --Idx; 2727 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2728 // If we have a multiply of zero, it will always be zero. 2729 return Ops[0]; 2730 } else if (Ops[0]->isAllOnesValue()) { 2731 // If we have a mul by -1 of an add, try distributing the -1 among the 2732 // add operands. 2733 if (Ops.size() == 2) { 2734 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2735 SmallVector<const SCEV *, 4> NewOps; 2736 bool AnyFolded = false; 2737 for (const SCEV *AddOp : Add->operands()) { 2738 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2739 Depth + 1); 2740 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2741 NewOps.push_back(Mul); 2742 } 2743 if (AnyFolded) 2744 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2745 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2746 // Negation preserves a recurrence's no self-wrap property. 2747 SmallVector<const SCEV *, 4> Operands; 2748 for (const SCEV *AddRecOp : AddRec->operands()) 2749 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2750 Depth + 1)); 2751 2752 return getAddRecExpr(Operands, AddRec->getLoop(), 2753 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2754 } 2755 } 2756 } 2757 2758 if (Ops.size() == 1) 2759 return Ops[0]; 2760 } 2761 2762 // Skip over the add expression until we get to a multiply. 2763 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2764 ++Idx; 2765 2766 // If there are mul operands inline them all into this expression. 2767 if (Idx < Ops.size()) { 2768 bool DeletedMul = false; 2769 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2770 if (Ops.size() > MulOpsInlineThreshold) 2771 break; 2772 // If we have an mul, expand the mul operands onto the end of the 2773 // operands list. 2774 Ops.erase(Ops.begin()+Idx); 2775 Ops.append(Mul->op_begin(), Mul->op_end()); 2776 DeletedMul = true; 2777 } 2778 2779 // If we deleted at least one mul, we added operands to the end of the 2780 // list, and they are not necessarily sorted. Recurse to resort and 2781 // resimplify any operands we just acquired. 2782 if (DeletedMul) 2783 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2784 } 2785 2786 // If there are any add recurrences in the operands list, see if any other 2787 // added values are loop invariant. If so, we can fold them into the 2788 // recurrence. 2789 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2790 ++Idx; 2791 2792 // Scan over all recurrences, trying to fold loop invariants into them. 2793 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2794 // Scan all of the other operands to this mul and add them to the vector 2795 // if they are loop invariant w.r.t. the recurrence. 2796 SmallVector<const SCEV *, 8> LIOps; 2797 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2798 const Loop *AddRecLoop = AddRec->getLoop(); 2799 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2800 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2801 LIOps.push_back(Ops[i]); 2802 Ops.erase(Ops.begin()+i); 2803 --i; --e; 2804 } 2805 2806 // If we found some loop invariants, fold them into the recurrence. 2807 if (!LIOps.empty()) { 2808 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2809 SmallVector<const SCEV *, 4> NewOps; 2810 NewOps.reserve(AddRec->getNumOperands()); 2811 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2812 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2813 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2814 SCEV::FlagAnyWrap, Depth + 1)); 2815 2816 // Build the new addrec. Propagate the NUW and NSW flags if both the 2817 // outer mul and the inner addrec are guaranteed to have no overflow. 2818 // 2819 // No self-wrap cannot be guaranteed after changing the step size, but 2820 // will be inferred if either NUW or NSW is true. 2821 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2822 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2823 2824 // If all of the other operands were loop invariant, we are done. 2825 if (Ops.size() == 1) return NewRec; 2826 2827 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2828 for (unsigned i = 0;; ++i) 2829 if (Ops[i] == AddRec) { 2830 Ops[i] = NewRec; 2831 break; 2832 } 2833 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2834 } 2835 2836 // Okay, if there weren't any loop invariants to be folded, check to see 2837 // if there are multiple AddRec's with the same loop induction variable 2838 // being multiplied together. If so, we can fold them. 2839 2840 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2841 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2842 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2843 // ]]],+,...up to x=2n}. 2844 // Note that the arguments to choose() are always integers with values 2845 // known at compile time, never SCEV objects. 2846 // 2847 // The implementation avoids pointless extra computations when the two 2848 // addrec's are of different length (mathematically, it's equivalent to 2849 // an infinite stream of zeros on the right). 2850 bool OpsModified = false; 2851 for (unsigned OtherIdx = Idx+1; 2852 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2853 ++OtherIdx) { 2854 const SCEVAddRecExpr *OtherAddRec = 2855 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2856 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2857 continue; 2858 2859 // Limit max number of arguments to avoid creation of unreasonably big 2860 // SCEVAddRecs with very complex operands. 2861 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2862 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 2863 continue; 2864 2865 bool Overflow = false; 2866 Type *Ty = AddRec->getType(); 2867 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2868 SmallVector<const SCEV*, 7> AddRecOps; 2869 for (int x = 0, xe = AddRec->getNumOperands() + 2870 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2871 SmallVector <const SCEV *, 7> SumOps; 2872 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2873 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2874 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2875 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2876 z < ze && !Overflow; ++z) { 2877 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2878 uint64_t Coeff; 2879 if (LargerThan64Bits) 2880 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2881 else 2882 Coeff = Coeff1*Coeff2; 2883 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2884 const SCEV *Term1 = AddRec->getOperand(y-z); 2885 const SCEV *Term2 = OtherAddRec->getOperand(z); 2886 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 2887 SCEV::FlagAnyWrap, Depth + 1)); 2888 } 2889 } 2890 if (SumOps.empty()) 2891 SumOps.push_back(getZero(Ty)); 2892 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 2893 } 2894 if (!Overflow) { 2895 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 2896 SCEV::FlagAnyWrap); 2897 if (Ops.size() == 2) return NewAddRec; 2898 Ops[Idx] = NewAddRec; 2899 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2900 OpsModified = true; 2901 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2902 if (!AddRec) 2903 break; 2904 } 2905 } 2906 if (OpsModified) 2907 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2908 2909 // Otherwise couldn't fold anything into this recurrence. Move onto the 2910 // next one. 2911 } 2912 2913 // Okay, it looks like we really DO need an mul expr. Check to see if we 2914 // already have one, otherwise create a new one. 2915 return getOrCreateMulExpr(Ops, Flags); 2916 } 2917 2918 /// Represents an unsigned remainder expression based on unsigned division. 2919 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2920 const SCEV *RHS) { 2921 assert(getEffectiveSCEVType(LHS->getType()) == 2922 getEffectiveSCEVType(RHS->getType()) && 2923 "SCEVURemExpr operand types don't match!"); 2924 2925 // Short-circuit easy cases 2926 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2927 // If constant is one, the result is trivial 2928 if (RHSC->getValue()->isOne()) 2929 return getZero(LHS->getType()); // X urem 1 --> 0 2930 2931 // If constant is a power of two, fold into a zext(trunc(LHS)). 2932 if (RHSC->getAPInt().isPowerOf2()) { 2933 Type *FullTy = LHS->getType(); 2934 Type *TruncTy = 2935 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2936 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2937 } 2938 } 2939 2940 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2941 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2942 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2943 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2944 } 2945 2946 /// Get a canonical unsigned division expression, or something simpler if 2947 /// possible. 2948 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2949 const SCEV *RHS) { 2950 assert(getEffectiveSCEVType(LHS->getType()) == 2951 getEffectiveSCEVType(RHS->getType()) && 2952 "SCEVUDivExpr operand types don't match!"); 2953 2954 FoldingSetNodeID ID; 2955 ID.AddInteger(scUDivExpr); 2956 ID.AddPointer(LHS); 2957 ID.AddPointer(RHS); 2958 void *IP = nullptr; 2959 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 2960 return S; 2961 2962 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2963 if (RHSC->getValue()->isOne()) 2964 return LHS; // X udiv 1 --> x 2965 // If the denominator is zero, the result of the udiv is undefined. Don't 2966 // try to analyze it, because the resolution chosen here may differ from 2967 // the resolution chosen in other parts of the compiler. 2968 if (!RHSC->getValue()->isZero()) { 2969 // Determine if the division can be folded into the operands of 2970 // its operands. 2971 // TODO: Generalize this to non-constants by using known-bits information. 2972 Type *Ty = LHS->getType(); 2973 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2974 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2975 // For non-power-of-two values, effectively round the value up to the 2976 // nearest power of two. 2977 if (!RHSC->getAPInt().isPowerOf2()) 2978 ++MaxShiftAmt; 2979 IntegerType *ExtTy = 2980 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2981 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2982 if (const SCEVConstant *Step = 2983 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2984 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2985 const APInt &StepInt = Step->getAPInt(); 2986 const APInt &DivInt = RHSC->getAPInt(); 2987 if (!StepInt.urem(DivInt) && 2988 getZeroExtendExpr(AR, ExtTy) == 2989 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2990 getZeroExtendExpr(Step, ExtTy), 2991 AR->getLoop(), SCEV::FlagAnyWrap)) { 2992 SmallVector<const SCEV *, 4> Operands; 2993 for (const SCEV *Op : AR->operands()) 2994 Operands.push_back(getUDivExpr(Op, RHS)); 2995 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2996 } 2997 /// Get a canonical UDivExpr for a recurrence. 2998 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2999 // We can currently only fold X%N if X is constant. 3000 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3001 if (StartC && !DivInt.urem(StepInt) && 3002 getZeroExtendExpr(AR, ExtTy) == 3003 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3004 getZeroExtendExpr(Step, ExtTy), 3005 AR->getLoop(), SCEV::FlagAnyWrap)) { 3006 const APInt &StartInt = StartC->getAPInt(); 3007 const APInt &StartRem = StartInt.urem(StepInt); 3008 if (StartRem != 0) { 3009 const SCEV *NewLHS = 3010 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3011 AR->getLoop(), SCEV::FlagNW); 3012 if (LHS != NewLHS) { 3013 LHS = NewLHS; 3014 3015 // Reset the ID to include the new LHS, and check if it is 3016 // already cached. 3017 ID.clear(); 3018 ID.AddInteger(scUDivExpr); 3019 ID.AddPointer(LHS); 3020 ID.AddPointer(RHS); 3021 IP = nullptr; 3022 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3023 return S; 3024 } 3025 } 3026 } 3027 } 3028 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3029 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3030 SmallVector<const SCEV *, 4> Operands; 3031 for (const SCEV *Op : M->operands()) 3032 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3033 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3034 // Find an operand that's safely divisible. 3035 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3036 const SCEV *Op = M->getOperand(i); 3037 const SCEV *Div = getUDivExpr(Op, RHSC); 3038 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3039 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3040 M->op_end()); 3041 Operands[i] = Div; 3042 return getMulExpr(Operands); 3043 } 3044 } 3045 } 3046 3047 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3048 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3049 if (auto *DivisorConstant = 3050 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3051 bool Overflow = false; 3052 APInt NewRHS = 3053 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3054 if (Overflow) { 3055 return getConstant(RHSC->getType(), 0, false); 3056 } 3057 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3058 } 3059 } 3060 3061 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3062 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3063 SmallVector<const SCEV *, 4> Operands; 3064 for (const SCEV *Op : A->operands()) 3065 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3066 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3067 Operands.clear(); 3068 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3069 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3070 if (isa<SCEVUDivExpr>(Op) || 3071 getMulExpr(Op, RHS) != A->getOperand(i)) 3072 break; 3073 Operands.push_back(Op); 3074 } 3075 if (Operands.size() == A->getNumOperands()) 3076 return getAddExpr(Operands); 3077 } 3078 } 3079 3080 // Fold if both operands are constant. 3081 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3082 Constant *LHSCV = LHSC->getValue(); 3083 Constant *RHSCV = RHSC->getValue(); 3084 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3085 RHSCV))); 3086 } 3087 } 3088 } 3089 3090 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3091 // changes). Make sure we get a new one. 3092 IP = nullptr; 3093 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3094 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3095 LHS, RHS); 3096 UniqueSCEVs.InsertNode(S, IP); 3097 addToLoopUseLists(S); 3098 return S; 3099 } 3100 3101 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3102 APInt A = C1->getAPInt().abs(); 3103 APInt B = C2->getAPInt().abs(); 3104 uint32_t ABW = A.getBitWidth(); 3105 uint32_t BBW = B.getBitWidth(); 3106 3107 if (ABW > BBW) 3108 B = B.zext(ABW); 3109 else if (ABW < BBW) 3110 A = A.zext(BBW); 3111 3112 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3113 } 3114 3115 /// Get a canonical unsigned division expression, or something simpler if 3116 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3117 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3118 /// it's not exact because the udiv may be clearing bits. 3119 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3120 const SCEV *RHS) { 3121 // TODO: we could try to find factors in all sorts of things, but for now we 3122 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3123 // end of this file for inspiration. 3124 3125 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3126 if (!Mul || !Mul->hasNoUnsignedWrap()) 3127 return getUDivExpr(LHS, RHS); 3128 3129 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3130 // If the mulexpr multiplies by a constant, then that constant must be the 3131 // first element of the mulexpr. 3132 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3133 if (LHSCst == RHSCst) { 3134 SmallVector<const SCEV *, 2> Operands; 3135 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3136 return getMulExpr(Operands); 3137 } 3138 3139 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3140 // that there's a factor provided by one of the other terms. We need to 3141 // check. 3142 APInt Factor = gcd(LHSCst, RHSCst); 3143 if (!Factor.isIntN(1)) { 3144 LHSCst = 3145 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3146 RHSCst = 3147 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3148 SmallVector<const SCEV *, 2> Operands; 3149 Operands.push_back(LHSCst); 3150 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3151 LHS = getMulExpr(Operands); 3152 RHS = RHSCst; 3153 Mul = dyn_cast<SCEVMulExpr>(LHS); 3154 if (!Mul) 3155 return getUDivExactExpr(LHS, RHS); 3156 } 3157 } 3158 } 3159 3160 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3161 if (Mul->getOperand(i) == RHS) { 3162 SmallVector<const SCEV *, 2> Operands; 3163 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3164 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3165 return getMulExpr(Operands); 3166 } 3167 } 3168 3169 return getUDivExpr(LHS, RHS); 3170 } 3171 3172 /// Get an add recurrence expression for the specified loop. Simplify the 3173 /// expression as much as possible. 3174 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3175 const Loop *L, 3176 SCEV::NoWrapFlags Flags) { 3177 SmallVector<const SCEV *, 4> Operands; 3178 Operands.push_back(Start); 3179 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3180 if (StepChrec->getLoop() == L) { 3181 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3182 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3183 } 3184 3185 Operands.push_back(Step); 3186 return getAddRecExpr(Operands, L, Flags); 3187 } 3188 3189 /// Get an add recurrence expression for the specified loop. Simplify the 3190 /// expression as much as possible. 3191 const SCEV * 3192 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3193 const Loop *L, SCEV::NoWrapFlags Flags) { 3194 if (Operands.size() == 1) return Operands[0]; 3195 #ifndef NDEBUG 3196 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3197 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3198 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3199 "SCEVAddRecExpr operand types don't match!"); 3200 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3201 assert(isLoopInvariant(Operands[i], L) && 3202 "SCEVAddRecExpr operand is not loop-invariant!"); 3203 #endif 3204 3205 if (Operands.back()->isZero()) { 3206 Operands.pop_back(); 3207 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3208 } 3209 3210 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3211 // use that information to infer NUW and NSW flags. However, computing a 3212 // BE count requires calling getAddRecExpr, so we may not yet have a 3213 // meaningful BE count at this point (and if we don't, we'd be stuck 3214 // with a SCEVCouldNotCompute as the cached BE count). 3215 3216 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3217 3218 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3219 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3220 const Loop *NestedLoop = NestedAR->getLoop(); 3221 if (L->contains(NestedLoop) 3222 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3223 : (!NestedLoop->contains(L) && 3224 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3225 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3226 NestedAR->op_end()); 3227 Operands[0] = NestedAR->getStart(); 3228 // AddRecs require their operands be loop-invariant with respect to their 3229 // loops. Don't perform this transformation if it would break this 3230 // requirement. 3231 bool AllInvariant = all_of( 3232 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3233 3234 if (AllInvariant) { 3235 // Create a recurrence for the outer loop with the same step size. 3236 // 3237 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3238 // inner recurrence has the same property. 3239 SCEV::NoWrapFlags OuterFlags = 3240 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3241 3242 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3243 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3244 return isLoopInvariant(Op, NestedLoop); 3245 }); 3246 3247 if (AllInvariant) { 3248 // Ok, both add recurrences are valid after the transformation. 3249 // 3250 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3251 // the outer recurrence has the same property. 3252 SCEV::NoWrapFlags InnerFlags = 3253 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3254 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3255 } 3256 } 3257 // Reset Operands to its original state. 3258 Operands[0] = NestedAR; 3259 } 3260 } 3261 3262 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3263 // already have one, otherwise create a new one. 3264 return getOrCreateAddRecExpr(Operands, L, Flags); 3265 } 3266 3267 const SCEV * 3268 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3269 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3270 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3271 // getSCEV(Base)->getType() has the same address space as Base->getType() 3272 // because SCEV::getType() preserves the address space. 3273 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3274 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3275 // instruction to its SCEV, because the Instruction may be guarded by control 3276 // flow and the no-overflow bits may not be valid for the expression in any 3277 // context. This can be fixed similarly to how these flags are handled for 3278 // adds. 3279 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3280 : SCEV::FlagAnyWrap; 3281 3282 const SCEV *TotalOffset = getZero(IntIdxTy); 3283 Type *CurTy = GEP->getType(); 3284 bool FirstIter = true; 3285 for (const SCEV *IndexExpr : IndexExprs) { 3286 // Compute the (potentially symbolic) offset in bytes for this index. 3287 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3288 // For a struct, add the member offset. 3289 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3290 unsigned FieldNo = Index->getZExtValue(); 3291 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3292 3293 // Add the field offset to the running total offset. 3294 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3295 3296 // Update CurTy to the type of the field at Index. 3297 CurTy = STy->getTypeAtIndex(Index); 3298 } else { 3299 // Update CurTy to its element type. 3300 if (FirstIter) { 3301 assert(isa<PointerType>(CurTy) && 3302 "The first index of a GEP indexes a pointer"); 3303 CurTy = GEP->getSourceElementType(); 3304 FirstIter = false; 3305 } else { 3306 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3307 } 3308 // For an array, add the element offset, explicitly scaled. 3309 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3310 // Getelementptr indices are signed. 3311 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3312 3313 // Multiply the index by the element size to compute the element offset. 3314 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3315 3316 // Add the element offset to the running total offset. 3317 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3318 } 3319 } 3320 3321 // Add the total offset from all the GEP indices to the base. 3322 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3323 } 3324 3325 std::tuple<SCEV *, FoldingSetNodeID, void *> 3326 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3327 ArrayRef<const SCEV *> Ops) { 3328 FoldingSetNodeID ID; 3329 void *IP = nullptr; 3330 ID.AddInteger(SCEVType); 3331 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3332 ID.AddPointer(Ops[i]); 3333 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3334 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3335 } 3336 3337 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3338 SmallVectorImpl<const SCEV *> &Ops) { 3339 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3340 if (Ops.size() == 1) return Ops[0]; 3341 #ifndef NDEBUG 3342 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3343 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3344 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3345 "Operand types don't match!"); 3346 #endif 3347 3348 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3349 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3350 3351 // Sort by complexity, this groups all similar expression types together. 3352 GroupByComplexity(Ops, &LI, DT); 3353 3354 // Check if we have created the same expression before. 3355 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3356 return S; 3357 } 3358 3359 // If there are any constants, fold them together. 3360 unsigned Idx = 0; 3361 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3362 ++Idx; 3363 assert(Idx < Ops.size()); 3364 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3365 if (Kind == scSMaxExpr) 3366 return APIntOps::smax(LHS, RHS); 3367 else if (Kind == scSMinExpr) 3368 return APIntOps::smin(LHS, RHS); 3369 else if (Kind == scUMaxExpr) 3370 return APIntOps::umax(LHS, RHS); 3371 else if (Kind == scUMinExpr) 3372 return APIntOps::umin(LHS, RHS); 3373 llvm_unreachable("Unknown SCEV min/max opcode"); 3374 }; 3375 3376 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3377 // We found two constants, fold them together! 3378 ConstantInt *Fold = ConstantInt::get( 3379 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3380 Ops[0] = getConstant(Fold); 3381 Ops.erase(Ops.begin()+1); // Erase the folded element 3382 if (Ops.size() == 1) return Ops[0]; 3383 LHSC = cast<SCEVConstant>(Ops[0]); 3384 } 3385 3386 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3387 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3388 3389 if (IsMax ? IsMinV : IsMaxV) { 3390 // If we are left with a constant minimum(/maximum)-int, strip it off. 3391 Ops.erase(Ops.begin()); 3392 --Idx; 3393 } else if (IsMax ? IsMaxV : IsMinV) { 3394 // If we have a max(/min) with a constant maximum(/minimum)-int, 3395 // it will always be the extremum. 3396 return LHSC; 3397 } 3398 3399 if (Ops.size() == 1) return Ops[0]; 3400 } 3401 3402 // Find the first operation of the same kind 3403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3404 ++Idx; 3405 3406 // Check to see if one of the operands is of the same kind. If so, expand its 3407 // operands onto our operand list, and recurse to simplify. 3408 if (Idx < Ops.size()) { 3409 bool DeletedAny = false; 3410 while (Ops[Idx]->getSCEVType() == Kind) { 3411 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3412 Ops.erase(Ops.begin()+Idx); 3413 Ops.append(SMME->op_begin(), SMME->op_end()); 3414 DeletedAny = true; 3415 } 3416 3417 if (DeletedAny) 3418 return getMinMaxExpr(Kind, Ops); 3419 } 3420 3421 // Okay, check to see if the same value occurs in the operand list twice. If 3422 // so, delete one. Since we sorted the list, these values are required to 3423 // be adjacent. 3424 llvm::CmpInst::Predicate GEPred = 3425 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3426 llvm::CmpInst::Predicate LEPred = 3427 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3428 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3429 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3430 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3431 if (Ops[i] == Ops[i + 1] || 3432 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3433 // X op Y op Y --> X op Y 3434 // X op Y --> X, if we know X, Y are ordered appropriately 3435 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3436 --i; 3437 --e; 3438 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3439 Ops[i + 1])) { 3440 // X op Y --> Y, if we know X, Y are ordered appropriately 3441 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3442 --i; 3443 --e; 3444 } 3445 } 3446 3447 if (Ops.size() == 1) return Ops[0]; 3448 3449 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3450 3451 // Okay, it looks like we really DO need an expr. Check to see if we 3452 // already have one, otherwise create a new one. 3453 const SCEV *ExistingSCEV; 3454 FoldingSetNodeID ID; 3455 void *IP; 3456 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3457 if (ExistingSCEV) 3458 return ExistingSCEV; 3459 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3460 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3461 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3462 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3463 3464 UniqueSCEVs.InsertNode(S, IP); 3465 addToLoopUseLists(S); 3466 return S; 3467 } 3468 3469 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3470 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3471 return getSMaxExpr(Ops); 3472 } 3473 3474 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3475 return getMinMaxExpr(scSMaxExpr, Ops); 3476 } 3477 3478 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3479 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3480 return getUMaxExpr(Ops); 3481 } 3482 3483 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3484 return getMinMaxExpr(scUMaxExpr, Ops); 3485 } 3486 3487 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3488 const SCEV *RHS) { 3489 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3490 return getSMinExpr(Ops); 3491 } 3492 3493 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3494 return getMinMaxExpr(scSMinExpr, Ops); 3495 } 3496 3497 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3498 const SCEV *RHS) { 3499 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3500 return getUMinExpr(Ops); 3501 } 3502 3503 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3504 return getMinMaxExpr(scUMinExpr, Ops); 3505 } 3506 3507 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3508 if (isa<ScalableVectorType>(AllocTy)) { 3509 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3510 Constant *One = ConstantInt::get(IntTy, 1); 3511 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3512 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3513 } 3514 // We can bypass creating a target-independent 3515 // constant expression and then folding it back into a ConstantInt. 3516 // This is just a compile-time optimization. 3517 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3518 } 3519 3520 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3521 StructType *STy, 3522 unsigned FieldNo) { 3523 // We can bypass creating a target-independent 3524 // constant expression and then folding it back into a ConstantInt. 3525 // This is just a compile-time optimization. 3526 return getConstant( 3527 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3528 } 3529 3530 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3531 // Don't attempt to do anything other than create a SCEVUnknown object 3532 // here. createSCEV only calls getUnknown after checking for all other 3533 // interesting possibilities, and any other code that calls getUnknown 3534 // is doing so in order to hide a value from SCEV canonicalization. 3535 3536 FoldingSetNodeID ID; 3537 ID.AddInteger(scUnknown); 3538 ID.AddPointer(V); 3539 void *IP = nullptr; 3540 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3541 assert(cast<SCEVUnknown>(S)->getValue() == V && 3542 "Stale SCEVUnknown in uniquing map!"); 3543 return S; 3544 } 3545 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3546 FirstUnknown); 3547 FirstUnknown = cast<SCEVUnknown>(S); 3548 UniqueSCEVs.InsertNode(S, IP); 3549 return S; 3550 } 3551 3552 //===----------------------------------------------------------------------===// 3553 // Basic SCEV Analysis and PHI Idiom Recognition Code 3554 // 3555 3556 /// Test if values of the given type are analyzable within the SCEV 3557 /// framework. This primarily includes integer types, and it can optionally 3558 /// include pointer types if the ScalarEvolution class has access to 3559 /// target-specific information. 3560 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3561 // Integers and pointers are always SCEVable. 3562 return Ty->isIntOrPtrTy(); 3563 } 3564 3565 /// Return the size in bits of the specified type, for which isSCEVable must 3566 /// return true. 3567 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3568 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3569 if (Ty->isPointerTy()) 3570 return getDataLayout().getIndexTypeSizeInBits(Ty); 3571 return getDataLayout().getTypeSizeInBits(Ty); 3572 } 3573 3574 /// Return a type with the same bitwidth as the given type and which represents 3575 /// how SCEV will treat the given type, for which isSCEVable must return 3576 /// true. For pointer types, this is the pointer index sized integer type. 3577 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3578 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3579 3580 if (Ty->isIntegerTy()) 3581 return Ty; 3582 3583 // The only other support type is pointer. 3584 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3585 return getDataLayout().getIndexType(Ty); 3586 } 3587 3588 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3589 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3590 } 3591 3592 const SCEV *ScalarEvolution::getCouldNotCompute() { 3593 return CouldNotCompute.get(); 3594 } 3595 3596 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3597 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3598 auto *SU = dyn_cast<SCEVUnknown>(S); 3599 return SU && SU->getValue() == nullptr; 3600 }); 3601 3602 return !ContainsNulls; 3603 } 3604 3605 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3606 HasRecMapType::iterator I = HasRecMap.find(S); 3607 if (I != HasRecMap.end()) 3608 return I->second; 3609 3610 bool FoundAddRec = 3611 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3612 HasRecMap.insert({S, FoundAddRec}); 3613 return FoundAddRec; 3614 } 3615 3616 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3617 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3618 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3619 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3620 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3621 if (!Add) 3622 return {S, nullptr}; 3623 3624 if (Add->getNumOperands() != 2) 3625 return {S, nullptr}; 3626 3627 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3628 if (!ConstOp) 3629 return {S, nullptr}; 3630 3631 return {Add->getOperand(1), ConstOp->getValue()}; 3632 } 3633 3634 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3635 /// by the value and offset from any ValueOffsetPair in the set. 3636 SetVector<ScalarEvolution::ValueOffsetPair> * 3637 ScalarEvolution::getSCEVValues(const SCEV *S) { 3638 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3639 if (SI == ExprValueMap.end()) 3640 return nullptr; 3641 #ifndef NDEBUG 3642 if (VerifySCEVMap) { 3643 // Check there is no dangling Value in the set returned. 3644 for (const auto &VE : SI->second) 3645 assert(ValueExprMap.count(VE.first)); 3646 } 3647 #endif 3648 return &SI->second; 3649 } 3650 3651 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3652 /// cannot be used separately. eraseValueFromMap should be used to remove 3653 /// V from ValueExprMap and ExprValueMap at the same time. 3654 void ScalarEvolution::eraseValueFromMap(Value *V) { 3655 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3656 if (I != ValueExprMap.end()) { 3657 const SCEV *S = I->second; 3658 // Remove {V, 0} from the set of ExprValueMap[S] 3659 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3660 SV->remove({V, nullptr}); 3661 3662 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3663 const SCEV *Stripped; 3664 ConstantInt *Offset; 3665 std::tie(Stripped, Offset) = splitAddExpr(S); 3666 if (Offset != nullptr) { 3667 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3668 SV->remove({V, Offset}); 3669 } 3670 ValueExprMap.erase(V); 3671 } 3672 } 3673 3674 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3675 /// TODO: In reality it is better to check the poison recursively 3676 /// but this is better than nothing. 3677 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3678 if (auto *I = dyn_cast<Instruction>(V)) { 3679 if (isa<OverflowingBinaryOperator>(I)) { 3680 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3681 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3682 return true; 3683 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3684 return true; 3685 } 3686 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3687 return true; 3688 } 3689 return false; 3690 } 3691 3692 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3693 /// create a new one. 3694 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3695 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3696 3697 const SCEV *S = getExistingSCEV(V); 3698 if (S == nullptr) { 3699 S = createSCEV(V); 3700 // During PHI resolution, it is possible to create two SCEVs for the same 3701 // V, so it is needed to double check whether V->S is inserted into 3702 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3703 std::pair<ValueExprMapType::iterator, bool> Pair = 3704 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3705 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3706 ExprValueMap[S].insert({V, nullptr}); 3707 3708 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3709 // ExprValueMap. 3710 const SCEV *Stripped = S; 3711 ConstantInt *Offset = nullptr; 3712 std::tie(Stripped, Offset) = splitAddExpr(S); 3713 // If stripped is SCEVUnknown, don't bother to save 3714 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3715 // increase the complexity of the expansion code. 3716 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3717 // because it may generate add/sub instead of GEP in SCEV expansion. 3718 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3719 !isa<GetElementPtrInst>(V)) 3720 ExprValueMap[Stripped].insert({V, Offset}); 3721 } 3722 } 3723 return S; 3724 } 3725 3726 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3727 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3728 3729 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3730 if (I != ValueExprMap.end()) { 3731 const SCEV *S = I->second; 3732 if (checkValidity(S)) 3733 return S; 3734 eraseValueFromMap(V); 3735 forgetMemoizedResults(S); 3736 } 3737 return nullptr; 3738 } 3739 3740 /// Return a SCEV corresponding to -V = -1*V 3741 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3742 SCEV::NoWrapFlags Flags) { 3743 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3744 return getConstant( 3745 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3746 3747 Type *Ty = V->getType(); 3748 Ty = getEffectiveSCEVType(Ty); 3749 return getMulExpr( 3750 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3751 } 3752 3753 /// If Expr computes ~A, return A else return nullptr 3754 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3755 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3756 if (!Add || Add->getNumOperands() != 2 || 3757 !Add->getOperand(0)->isAllOnesValue()) 3758 return nullptr; 3759 3760 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3761 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3762 !AddRHS->getOperand(0)->isAllOnesValue()) 3763 return nullptr; 3764 3765 return AddRHS->getOperand(1); 3766 } 3767 3768 /// Return a SCEV corresponding to ~V = -1-V 3769 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3770 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3771 return getConstant( 3772 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3773 3774 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3775 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3776 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3777 SmallVector<const SCEV *, 2> MatchedOperands; 3778 for (const SCEV *Operand : MME->operands()) { 3779 const SCEV *Matched = MatchNotExpr(Operand); 3780 if (!Matched) 3781 return (const SCEV *)nullptr; 3782 MatchedOperands.push_back(Matched); 3783 } 3784 return getMinMaxExpr( 3785 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3786 MatchedOperands); 3787 }; 3788 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3789 return Replaced; 3790 } 3791 3792 Type *Ty = V->getType(); 3793 Ty = getEffectiveSCEVType(Ty); 3794 const SCEV *AllOnes = 3795 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3796 return getMinusSCEV(AllOnes, V); 3797 } 3798 3799 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3800 SCEV::NoWrapFlags Flags, 3801 unsigned Depth) { 3802 // Fast path: X - X --> 0. 3803 if (LHS == RHS) 3804 return getZero(LHS->getType()); 3805 3806 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3807 // makes it so that we cannot make much use of NUW. 3808 auto AddFlags = SCEV::FlagAnyWrap; 3809 const bool RHSIsNotMinSigned = 3810 !getSignedRangeMin(RHS).isMinSignedValue(); 3811 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3812 // Let M be the minimum representable signed value. Then (-1)*RHS 3813 // signed-wraps if and only if RHS is M. That can happen even for 3814 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3815 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3816 // (-1)*RHS, we need to prove that RHS != M. 3817 // 3818 // If LHS is non-negative and we know that LHS - RHS does not 3819 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3820 // either by proving that RHS > M or that LHS >= 0. 3821 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3822 AddFlags = SCEV::FlagNSW; 3823 } 3824 } 3825 3826 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3827 // RHS is NSW and LHS >= 0. 3828 // 3829 // The difficulty here is that the NSW flag may have been proven 3830 // relative to a loop that is to be found in a recurrence in LHS and 3831 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3832 // larger scope than intended. 3833 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3834 3835 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3836 } 3837 3838 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3839 unsigned Depth) { 3840 Type *SrcTy = V->getType(); 3841 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3842 "Cannot truncate or zero extend with non-integer arguments!"); 3843 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3844 return V; // No conversion 3845 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3846 return getTruncateExpr(V, Ty, Depth); 3847 return getZeroExtendExpr(V, Ty, Depth); 3848 } 3849 3850 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 3851 unsigned Depth) { 3852 Type *SrcTy = V->getType(); 3853 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3854 "Cannot truncate or zero extend with non-integer arguments!"); 3855 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3856 return V; // No conversion 3857 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3858 return getTruncateExpr(V, Ty, Depth); 3859 return getSignExtendExpr(V, Ty, Depth); 3860 } 3861 3862 const SCEV * 3863 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3864 Type *SrcTy = V->getType(); 3865 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3866 "Cannot noop or zero extend with non-integer arguments!"); 3867 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3868 "getNoopOrZeroExtend cannot truncate!"); 3869 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3870 return V; // No conversion 3871 return getZeroExtendExpr(V, Ty); 3872 } 3873 3874 const SCEV * 3875 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3876 Type *SrcTy = V->getType(); 3877 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3878 "Cannot noop or sign extend with non-integer arguments!"); 3879 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3880 "getNoopOrSignExtend cannot truncate!"); 3881 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3882 return V; // No conversion 3883 return getSignExtendExpr(V, Ty); 3884 } 3885 3886 const SCEV * 3887 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3888 Type *SrcTy = V->getType(); 3889 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3890 "Cannot noop or any extend with non-integer arguments!"); 3891 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3892 "getNoopOrAnyExtend cannot truncate!"); 3893 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3894 return V; // No conversion 3895 return getAnyExtendExpr(V, Ty); 3896 } 3897 3898 const SCEV * 3899 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3900 Type *SrcTy = V->getType(); 3901 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3902 "Cannot truncate or noop with non-integer arguments!"); 3903 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3904 "getTruncateOrNoop cannot extend!"); 3905 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3906 return V; // No conversion 3907 return getTruncateExpr(V, Ty); 3908 } 3909 3910 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3911 const SCEV *RHS) { 3912 const SCEV *PromotedLHS = LHS; 3913 const SCEV *PromotedRHS = RHS; 3914 3915 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3916 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3917 else 3918 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3919 3920 return getUMaxExpr(PromotedLHS, PromotedRHS); 3921 } 3922 3923 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3924 const SCEV *RHS) { 3925 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3926 return getUMinFromMismatchedTypes(Ops); 3927 } 3928 3929 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 3930 SmallVectorImpl<const SCEV *> &Ops) { 3931 assert(!Ops.empty() && "At least one operand must be!"); 3932 // Trivial case. 3933 if (Ops.size() == 1) 3934 return Ops[0]; 3935 3936 // Find the max type first. 3937 Type *MaxType = nullptr; 3938 for (auto *S : Ops) 3939 if (MaxType) 3940 MaxType = getWiderType(MaxType, S->getType()); 3941 else 3942 MaxType = S->getType(); 3943 assert(MaxType && "Failed to find maximum type!"); 3944 3945 // Extend all ops to max type. 3946 SmallVector<const SCEV *, 2> PromotedOps; 3947 for (auto *S : Ops) 3948 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 3949 3950 // Generate umin. 3951 return getUMinExpr(PromotedOps); 3952 } 3953 3954 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3955 // A pointer operand may evaluate to a nonpointer expression, such as null. 3956 if (!V->getType()->isPointerTy()) 3957 return V; 3958 3959 while (true) { 3960 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3961 V = Cast->getOperand(); 3962 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3963 const SCEV *PtrOp = nullptr; 3964 for (const SCEV *NAryOp : NAry->operands()) { 3965 if (NAryOp->getType()->isPointerTy()) { 3966 // Cannot find the base of an expression with multiple pointer ops. 3967 if (PtrOp) 3968 return V; 3969 PtrOp = NAryOp; 3970 } 3971 } 3972 if (!PtrOp) // All operands were non-pointer. 3973 return V; 3974 V = PtrOp; 3975 } else // Not something we can look further into. 3976 return V; 3977 } 3978 } 3979 3980 /// Push users of the given Instruction onto the given Worklist. 3981 static void 3982 PushDefUseChildren(Instruction *I, 3983 SmallVectorImpl<Instruction *> &Worklist) { 3984 // Push the def-use children onto the Worklist stack. 3985 for (User *U : I->users()) 3986 Worklist.push_back(cast<Instruction>(U)); 3987 } 3988 3989 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3990 SmallVector<Instruction *, 16> Worklist; 3991 PushDefUseChildren(PN, Worklist); 3992 3993 SmallPtrSet<Instruction *, 8> Visited; 3994 Visited.insert(PN); 3995 while (!Worklist.empty()) { 3996 Instruction *I = Worklist.pop_back_val(); 3997 if (!Visited.insert(I).second) 3998 continue; 3999 4000 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4001 if (It != ValueExprMap.end()) { 4002 const SCEV *Old = It->second; 4003 4004 // Short-circuit the def-use traversal if the symbolic name 4005 // ceases to appear in expressions. 4006 if (Old != SymName && !hasOperand(Old, SymName)) 4007 continue; 4008 4009 // SCEVUnknown for a PHI either means that it has an unrecognized 4010 // structure, it's a PHI that's in the progress of being computed 4011 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4012 // additional loop trip count information isn't going to change anything. 4013 // In the second case, createNodeForPHI will perform the necessary 4014 // updates on its own when it gets to that point. In the third, we do 4015 // want to forget the SCEVUnknown. 4016 if (!isa<PHINode>(I) || 4017 !isa<SCEVUnknown>(Old) || 4018 (I != PN && Old == SymName)) { 4019 eraseValueFromMap(It->first); 4020 forgetMemoizedResults(Old); 4021 } 4022 } 4023 4024 PushDefUseChildren(I, Worklist); 4025 } 4026 } 4027 4028 namespace { 4029 4030 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4031 /// expression in case its Loop is L. If it is not L then 4032 /// if IgnoreOtherLoops is true then use AddRec itself 4033 /// otherwise rewrite cannot be done. 4034 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4035 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4036 public: 4037 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4038 bool IgnoreOtherLoops = true) { 4039 SCEVInitRewriter Rewriter(L, SE); 4040 const SCEV *Result = Rewriter.visit(S); 4041 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4042 return SE.getCouldNotCompute(); 4043 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4044 ? SE.getCouldNotCompute() 4045 : Result; 4046 } 4047 4048 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4049 if (!SE.isLoopInvariant(Expr, L)) 4050 SeenLoopVariantSCEVUnknown = true; 4051 return Expr; 4052 } 4053 4054 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4055 // Only re-write AddRecExprs for this loop. 4056 if (Expr->getLoop() == L) 4057 return Expr->getStart(); 4058 SeenOtherLoops = true; 4059 return Expr; 4060 } 4061 4062 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4063 4064 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4065 4066 private: 4067 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4068 : SCEVRewriteVisitor(SE), L(L) {} 4069 4070 const Loop *L; 4071 bool SeenLoopVariantSCEVUnknown = false; 4072 bool SeenOtherLoops = false; 4073 }; 4074 4075 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4076 /// increment expression in case its Loop is L. If it is not L then 4077 /// use AddRec itself. 4078 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4079 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4080 public: 4081 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4082 SCEVPostIncRewriter Rewriter(L, SE); 4083 const SCEV *Result = Rewriter.visit(S); 4084 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4085 ? SE.getCouldNotCompute() 4086 : Result; 4087 } 4088 4089 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4090 if (!SE.isLoopInvariant(Expr, L)) 4091 SeenLoopVariantSCEVUnknown = true; 4092 return Expr; 4093 } 4094 4095 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4096 // Only re-write AddRecExprs for this loop. 4097 if (Expr->getLoop() == L) 4098 return Expr->getPostIncExpr(SE); 4099 SeenOtherLoops = true; 4100 return Expr; 4101 } 4102 4103 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4104 4105 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4106 4107 private: 4108 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4109 : SCEVRewriteVisitor(SE), L(L) {} 4110 4111 const Loop *L; 4112 bool SeenLoopVariantSCEVUnknown = false; 4113 bool SeenOtherLoops = false; 4114 }; 4115 4116 /// This class evaluates the compare condition by matching it against the 4117 /// condition of loop latch. If there is a match we assume a true value 4118 /// for the condition while building SCEV nodes. 4119 class SCEVBackedgeConditionFolder 4120 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4121 public: 4122 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4123 ScalarEvolution &SE) { 4124 bool IsPosBECond = false; 4125 Value *BECond = nullptr; 4126 if (BasicBlock *Latch = L->getLoopLatch()) { 4127 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4128 if (BI && BI->isConditional()) { 4129 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4130 "Both outgoing branches should not target same header!"); 4131 BECond = BI->getCondition(); 4132 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4133 } else { 4134 return S; 4135 } 4136 } 4137 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4138 return Rewriter.visit(S); 4139 } 4140 4141 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4142 const SCEV *Result = Expr; 4143 bool InvariantF = SE.isLoopInvariant(Expr, L); 4144 4145 if (!InvariantF) { 4146 Instruction *I = cast<Instruction>(Expr->getValue()); 4147 switch (I->getOpcode()) { 4148 case Instruction::Select: { 4149 SelectInst *SI = cast<SelectInst>(I); 4150 Optional<const SCEV *> Res = 4151 compareWithBackedgeCondition(SI->getCondition()); 4152 if (Res.hasValue()) { 4153 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4154 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4155 } 4156 break; 4157 } 4158 default: { 4159 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4160 if (Res.hasValue()) 4161 Result = Res.getValue(); 4162 break; 4163 } 4164 } 4165 } 4166 return Result; 4167 } 4168 4169 private: 4170 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4171 bool IsPosBECond, ScalarEvolution &SE) 4172 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4173 IsPositiveBECond(IsPosBECond) {} 4174 4175 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4176 4177 const Loop *L; 4178 /// Loop back condition. 4179 Value *BackedgeCond = nullptr; 4180 /// Set to true if loop back is on positive branch condition. 4181 bool IsPositiveBECond; 4182 }; 4183 4184 Optional<const SCEV *> 4185 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4186 4187 // If value matches the backedge condition for loop latch, 4188 // then return a constant evolution node based on loopback 4189 // branch taken. 4190 if (BackedgeCond == IC) 4191 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4192 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4193 return None; 4194 } 4195 4196 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4197 public: 4198 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4199 ScalarEvolution &SE) { 4200 SCEVShiftRewriter Rewriter(L, SE); 4201 const SCEV *Result = Rewriter.visit(S); 4202 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4203 } 4204 4205 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4206 // Only allow AddRecExprs for this loop. 4207 if (!SE.isLoopInvariant(Expr, L)) 4208 Valid = false; 4209 return Expr; 4210 } 4211 4212 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4213 if (Expr->getLoop() == L && Expr->isAffine()) 4214 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4215 Valid = false; 4216 return Expr; 4217 } 4218 4219 bool isValid() { return Valid; } 4220 4221 private: 4222 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4223 : SCEVRewriteVisitor(SE), L(L) {} 4224 4225 const Loop *L; 4226 bool Valid = true; 4227 }; 4228 4229 } // end anonymous namespace 4230 4231 SCEV::NoWrapFlags 4232 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4233 if (!AR->isAffine()) 4234 return SCEV::FlagAnyWrap; 4235 4236 using OBO = OverflowingBinaryOperator; 4237 4238 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4239 4240 if (!AR->hasNoSignedWrap()) { 4241 ConstantRange AddRecRange = getSignedRange(AR); 4242 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4243 4244 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4245 Instruction::Add, IncRange, OBO::NoSignedWrap); 4246 if (NSWRegion.contains(AddRecRange)) 4247 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4248 } 4249 4250 if (!AR->hasNoUnsignedWrap()) { 4251 ConstantRange AddRecRange = getUnsignedRange(AR); 4252 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4253 4254 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4255 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4256 if (NUWRegion.contains(AddRecRange)) 4257 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4258 } 4259 4260 return Result; 4261 } 4262 4263 namespace { 4264 4265 /// Represents an abstract binary operation. This may exist as a 4266 /// normal instruction or constant expression, or may have been 4267 /// derived from an expression tree. 4268 struct BinaryOp { 4269 unsigned Opcode; 4270 Value *LHS; 4271 Value *RHS; 4272 bool IsNSW = false; 4273 bool IsNUW = false; 4274 4275 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4276 /// constant expression. 4277 Operator *Op = nullptr; 4278 4279 explicit BinaryOp(Operator *Op) 4280 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4281 Op(Op) { 4282 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4283 IsNSW = OBO->hasNoSignedWrap(); 4284 IsNUW = OBO->hasNoUnsignedWrap(); 4285 } 4286 } 4287 4288 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4289 bool IsNUW = false) 4290 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4291 }; 4292 4293 } // end anonymous namespace 4294 4295 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4296 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4297 auto *Op = dyn_cast<Operator>(V); 4298 if (!Op) 4299 return None; 4300 4301 // Implementation detail: all the cleverness here should happen without 4302 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4303 // SCEV expressions when possible, and we should not break that. 4304 4305 switch (Op->getOpcode()) { 4306 case Instruction::Add: 4307 case Instruction::Sub: 4308 case Instruction::Mul: 4309 case Instruction::UDiv: 4310 case Instruction::URem: 4311 case Instruction::And: 4312 case Instruction::Or: 4313 case Instruction::AShr: 4314 case Instruction::Shl: 4315 return BinaryOp(Op); 4316 4317 case Instruction::Xor: 4318 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4319 // If the RHS of the xor is a signmask, then this is just an add. 4320 // Instcombine turns add of signmask into xor as a strength reduction step. 4321 if (RHSC->getValue().isSignMask()) 4322 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4323 return BinaryOp(Op); 4324 4325 case Instruction::LShr: 4326 // Turn logical shift right of a constant into a unsigned divide. 4327 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4328 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4329 4330 // If the shift count is not less than the bitwidth, the result of 4331 // the shift is undefined. Don't try to analyze it, because the 4332 // resolution chosen here may differ from the resolution chosen in 4333 // other parts of the compiler. 4334 if (SA->getValue().ult(BitWidth)) { 4335 Constant *X = 4336 ConstantInt::get(SA->getContext(), 4337 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4338 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4339 } 4340 } 4341 return BinaryOp(Op); 4342 4343 case Instruction::ExtractValue: { 4344 auto *EVI = cast<ExtractValueInst>(Op); 4345 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4346 break; 4347 4348 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4349 if (!WO) 4350 break; 4351 4352 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4353 bool Signed = WO->isSigned(); 4354 // TODO: Should add nuw/nsw flags for mul as well. 4355 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4356 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4357 4358 // Now that we know that all uses of the arithmetic-result component of 4359 // CI are guarded by the overflow check, we can go ahead and pretend 4360 // that the arithmetic is non-overflowing. 4361 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4362 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4363 } 4364 4365 default: 4366 break; 4367 } 4368 4369 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4370 // semantics as a Sub, return a binary sub expression. 4371 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4372 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4373 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4374 4375 return None; 4376 } 4377 4378 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4379 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4380 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4381 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4382 /// follows one of the following patterns: 4383 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4384 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4385 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4386 /// we return the type of the truncation operation, and indicate whether the 4387 /// truncated type should be treated as signed/unsigned by setting 4388 /// \p Signed to true/false, respectively. 4389 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4390 bool &Signed, ScalarEvolution &SE) { 4391 // The case where Op == SymbolicPHI (that is, with no type conversions on 4392 // the way) is handled by the regular add recurrence creating logic and 4393 // would have already been triggered in createAddRecForPHI. Reaching it here 4394 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4395 // because one of the other operands of the SCEVAddExpr updating this PHI is 4396 // not invariant). 4397 // 4398 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4399 // this case predicates that allow us to prove that Op == SymbolicPHI will 4400 // be added. 4401 if (Op == SymbolicPHI) 4402 return nullptr; 4403 4404 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4405 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4406 if (SourceBits != NewBits) 4407 return nullptr; 4408 4409 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4410 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4411 if (!SExt && !ZExt) 4412 return nullptr; 4413 const SCEVTruncateExpr *Trunc = 4414 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4415 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4416 if (!Trunc) 4417 return nullptr; 4418 const SCEV *X = Trunc->getOperand(); 4419 if (X != SymbolicPHI) 4420 return nullptr; 4421 Signed = SExt != nullptr; 4422 return Trunc->getType(); 4423 } 4424 4425 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4426 if (!PN->getType()->isIntegerTy()) 4427 return nullptr; 4428 const Loop *L = LI.getLoopFor(PN->getParent()); 4429 if (!L || L->getHeader() != PN->getParent()) 4430 return nullptr; 4431 return L; 4432 } 4433 4434 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4435 // computation that updates the phi follows the following pattern: 4436 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4437 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4438 // If so, try to see if it can be rewritten as an AddRecExpr under some 4439 // Predicates. If successful, return them as a pair. Also cache the results 4440 // of the analysis. 4441 // 4442 // Example usage scenario: 4443 // Say the Rewriter is called for the following SCEV: 4444 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4445 // where: 4446 // %X = phi i64 (%Start, %BEValue) 4447 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4448 // and call this function with %SymbolicPHI = %X. 4449 // 4450 // The analysis will find that the value coming around the backedge has 4451 // the following SCEV: 4452 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4453 // Upon concluding that this matches the desired pattern, the function 4454 // will return the pair {NewAddRec, SmallPredsVec} where: 4455 // NewAddRec = {%Start,+,%Step} 4456 // SmallPredsVec = {P1, P2, P3} as follows: 4457 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4458 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4459 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4460 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4461 // under the predicates {P1,P2,P3}. 4462 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4463 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4464 // 4465 // TODO's: 4466 // 4467 // 1) Extend the Induction descriptor to also support inductions that involve 4468 // casts: When needed (namely, when we are called in the context of the 4469 // vectorizer induction analysis), a Set of cast instructions will be 4470 // populated by this method, and provided back to isInductionPHI. This is 4471 // needed to allow the vectorizer to properly record them to be ignored by 4472 // the cost model and to avoid vectorizing them (otherwise these casts, 4473 // which are redundant under the runtime overflow checks, will be 4474 // vectorized, which can be costly). 4475 // 4476 // 2) Support additional induction/PHISCEV patterns: We also want to support 4477 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4478 // after the induction update operation (the induction increment): 4479 // 4480 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4481 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4482 // 4483 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4484 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4485 // 4486 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4487 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4488 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4489 SmallVector<const SCEVPredicate *, 3> Predicates; 4490 4491 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4492 // return an AddRec expression under some predicate. 4493 4494 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4495 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4496 assert(L && "Expecting an integer loop header phi"); 4497 4498 // The loop may have multiple entrances or multiple exits; we can analyze 4499 // this phi as an addrec if it has a unique entry value and a unique 4500 // backedge value. 4501 Value *BEValueV = nullptr, *StartValueV = nullptr; 4502 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4503 Value *V = PN->getIncomingValue(i); 4504 if (L->contains(PN->getIncomingBlock(i))) { 4505 if (!BEValueV) { 4506 BEValueV = V; 4507 } else if (BEValueV != V) { 4508 BEValueV = nullptr; 4509 break; 4510 } 4511 } else if (!StartValueV) { 4512 StartValueV = V; 4513 } else if (StartValueV != V) { 4514 StartValueV = nullptr; 4515 break; 4516 } 4517 } 4518 if (!BEValueV || !StartValueV) 4519 return None; 4520 4521 const SCEV *BEValue = getSCEV(BEValueV); 4522 4523 // If the value coming around the backedge is an add with the symbolic 4524 // value we just inserted, possibly with casts that we can ignore under 4525 // an appropriate runtime guard, then we found a simple induction variable! 4526 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4527 if (!Add) 4528 return None; 4529 4530 // If there is a single occurrence of the symbolic value, possibly 4531 // casted, replace it with a recurrence. 4532 unsigned FoundIndex = Add->getNumOperands(); 4533 Type *TruncTy = nullptr; 4534 bool Signed; 4535 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4536 if ((TruncTy = 4537 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4538 if (FoundIndex == e) { 4539 FoundIndex = i; 4540 break; 4541 } 4542 4543 if (FoundIndex == Add->getNumOperands()) 4544 return None; 4545 4546 // Create an add with everything but the specified operand. 4547 SmallVector<const SCEV *, 8> Ops; 4548 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4549 if (i != FoundIndex) 4550 Ops.push_back(Add->getOperand(i)); 4551 const SCEV *Accum = getAddExpr(Ops); 4552 4553 // The runtime checks will not be valid if the step amount is 4554 // varying inside the loop. 4555 if (!isLoopInvariant(Accum, L)) 4556 return None; 4557 4558 // *** Part2: Create the predicates 4559 4560 // Analysis was successful: we have a phi-with-cast pattern for which we 4561 // can return an AddRec expression under the following predicates: 4562 // 4563 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4564 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4565 // P2: An Equal predicate that guarantees that 4566 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4567 // P3: An Equal predicate that guarantees that 4568 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4569 // 4570 // As we next prove, the above predicates guarantee that: 4571 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4572 // 4573 // 4574 // More formally, we want to prove that: 4575 // Expr(i+1) = Start + (i+1) * Accum 4576 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4577 // 4578 // Given that: 4579 // 1) Expr(0) = Start 4580 // 2) Expr(1) = Start + Accum 4581 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4582 // 3) Induction hypothesis (step i): 4583 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4584 // 4585 // Proof: 4586 // Expr(i+1) = 4587 // = Start + (i+1)*Accum 4588 // = (Start + i*Accum) + Accum 4589 // = Expr(i) + Accum 4590 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4591 // :: from step i 4592 // 4593 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4594 // 4595 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4596 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4597 // + Accum :: from P3 4598 // 4599 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4600 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4601 // 4602 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4603 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4604 // 4605 // By induction, the same applies to all iterations 1<=i<n: 4606 // 4607 4608 // Create a truncated addrec for which we will add a no overflow check (P1). 4609 const SCEV *StartVal = getSCEV(StartValueV); 4610 const SCEV *PHISCEV = 4611 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4612 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4613 4614 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4615 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4616 // will be constant. 4617 // 4618 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4619 // add P1. 4620 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4621 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4622 Signed ? SCEVWrapPredicate::IncrementNSSW 4623 : SCEVWrapPredicate::IncrementNUSW; 4624 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4625 Predicates.push_back(AddRecPred); 4626 } 4627 4628 // Create the Equal Predicates P2,P3: 4629 4630 // It is possible that the predicates P2 and/or P3 are computable at 4631 // compile time due to StartVal and/or Accum being constants. 4632 // If either one is, then we can check that now and escape if either P2 4633 // or P3 is false. 4634 4635 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4636 // for each of StartVal and Accum 4637 auto getExtendedExpr = [&](const SCEV *Expr, 4638 bool CreateSignExtend) -> const SCEV * { 4639 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4640 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4641 const SCEV *ExtendedExpr = 4642 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4643 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4644 return ExtendedExpr; 4645 }; 4646 4647 // Given: 4648 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4649 // = getExtendedExpr(Expr) 4650 // Determine whether the predicate P: Expr == ExtendedExpr 4651 // is known to be false at compile time 4652 auto PredIsKnownFalse = [&](const SCEV *Expr, 4653 const SCEV *ExtendedExpr) -> bool { 4654 return Expr != ExtendedExpr && 4655 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4656 }; 4657 4658 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4659 if (PredIsKnownFalse(StartVal, StartExtended)) { 4660 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4661 return None; 4662 } 4663 4664 // The Step is always Signed (because the overflow checks are either 4665 // NSSW or NUSW) 4666 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4667 if (PredIsKnownFalse(Accum, AccumExtended)) { 4668 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4669 return None; 4670 } 4671 4672 auto AppendPredicate = [&](const SCEV *Expr, 4673 const SCEV *ExtendedExpr) -> void { 4674 if (Expr != ExtendedExpr && 4675 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4676 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4677 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4678 Predicates.push_back(Pred); 4679 } 4680 }; 4681 4682 AppendPredicate(StartVal, StartExtended); 4683 AppendPredicate(Accum, AccumExtended); 4684 4685 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4686 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4687 // into NewAR if it will also add the runtime overflow checks specified in 4688 // Predicates. 4689 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4690 4691 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4692 std::make_pair(NewAR, Predicates); 4693 // Remember the result of the analysis for this SCEV at this locayyytion. 4694 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4695 return PredRewrite; 4696 } 4697 4698 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4699 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4700 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4701 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4702 if (!L) 4703 return None; 4704 4705 // Check to see if we already analyzed this PHI. 4706 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4707 if (I != PredicatedSCEVRewrites.end()) { 4708 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4709 I->second; 4710 // Analysis was done before and failed to create an AddRec: 4711 if (Rewrite.first == SymbolicPHI) 4712 return None; 4713 // Analysis was done before and succeeded to create an AddRec under 4714 // a predicate: 4715 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4716 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4717 return Rewrite; 4718 } 4719 4720 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4721 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4722 4723 // Record in the cache that the analysis failed 4724 if (!Rewrite) { 4725 SmallVector<const SCEVPredicate *, 3> Predicates; 4726 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4727 return None; 4728 } 4729 4730 return Rewrite; 4731 } 4732 4733 // FIXME: This utility is currently required because the Rewriter currently 4734 // does not rewrite this expression: 4735 // {0, +, (sext ix (trunc iy to ix) to iy)} 4736 // into {0, +, %step}, 4737 // even when the following Equal predicate exists: 4738 // "%step == (sext ix (trunc iy to ix) to iy)". 4739 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4740 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4741 if (AR1 == AR2) 4742 return true; 4743 4744 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4745 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4746 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4747 return false; 4748 return true; 4749 }; 4750 4751 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4752 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4753 return false; 4754 return true; 4755 } 4756 4757 /// A helper function for createAddRecFromPHI to handle simple cases. 4758 /// 4759 /// This function tries to find an AddRec expression for the simplest (yet most 4760 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4761 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4762 /// technique for finding the AddRec expression. 4763 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4764 Value *BEValueV, 4765 Value *StartValueV) { 4766 const Loop *L = LI.getLoopFor(PN->getParent()); 4767 assert(L && L->getHeader() == PN->getParent()); 4768 assert(BEValueV && StartValueV); 4769 4770 auto BO = MatchBinaryOp(BEValueV, DT); 4771 if (!BO) 4772 return nullptr; 4773 4774 if (BO->Opcode != Instruction::Add) 4775 return nullptr; 4776 4777 const SCEV *Accum = nullptr; 4778 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4779 Accum = getSCEV(BO->RHS); 4780 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4781 Accum = getSCEV(BO->LHS); 4782 4783 if (!Accum) 4784 return nullptr; 4785 4786 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4787 if (BO->IsNUW) 4788 Flags = setFlags(Flags, SCEV::FlagNUW); 4789 if (BO->IsNSW) 4790 Flags = setFlags(Flags, SCEV::FlagNSW); 4791 4792 const SCEV *StartVal = getSCEV(StartValueV); 4793 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4794 4795 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4796 4797 // We can add Flags to the post-inc expression only if we 4798 // know that it is *undefined behavior* for BEValueV to 4799 // overflow. 4800 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4801 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4802 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4803 4804 return PHISCEV; 4805 } 4806 4807 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4808 const Loop *L = LI.getLoopFor(PN->getParent()); 4809 if (!L || L->getHeader() != PN->getParent()) 4810 return nullptr; 4811 4812 // The loop may have multiple entrances or multiple exits; we can analyze 4813 // this phi as an addrec if it has a unique entry value and a unique 4814 // backedge value. 4815 Value *BEValueV = nullptr, *StartValueV = nullptr; 4816 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4817 Value *V = PN->getIncomingValue(i); 4818 if (L->contains(PN->getIncomingBlock(i))) { 4819 if (!BEValueV) { 4820 BEValueV = V; 4821 } else if (BEValueV != V) { 4822 BEValueV = nullptr; 4823 break; 4824 } 4825 } else if (!StartValueV) { 4826 StartValueV = V; 4827 } else if (StartValueV != V) { 4828 StartValueV = nullptr; 4829 break; 4830 } 4831 } 4832 if (!BEValueV || !StartValueV) 4833 return nullptr; 4834 4835 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4836 "PHI node already processed?"); 4837 4838 // First, try to find AddRec expression without creating a fictituos symbolic 4839 // value for PN. 4840 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4841 return S; 4842 4843 // Handle PHI node value symbolically. 4844 const SCEV *SymbolicName = getUnknown(PN); 4845 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4846 4847 // Using this symbolic name for the PHI, analyze the value coming around 4848 // the back-edge. 4849 const SCEV *BEValue = getSCEV(BEValueV); 4850 4851 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4852 // has a special value for the first iteration of the loop. 4853 4854 // If the value coming around the backedge is an add with the symbolic 4855 // value we just inserted, then we found a simple induction variable! 4856 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4857 // If there is a single occurrence of the symbolic value, replace it 4858 // with a recurrence. 4859 unsigned FoundIndex = Add->getNumOperands(); 4860 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4861 if (Add->getOperand(i) == SymbolicName) 4862 if (FoundIndex == e) { 4863 FoundIndex = i; 4864 break; 4865 } 4866 4867 if (FoundIndex != Add->getNumOperands()) { 4868 // Create an add with everything but the specified operand. 4869 SmallVector<const SCEV *, 8> Ops; 4870 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4871 if (i != FoundIndex) 4872 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4873 L, *this)); 4874 const SCEV *Accum = getAddExpr(Ops); 4875 4876 // This is not a valid addrec if the step amount is varying each 4877 // loop iteration, but is not itself an addrec in this loop. 4878 if (isLoopInvariant(Accum, L) || 4879 (isa<SCEVAddRecExpr>(Accum) && 4880 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4881 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4882 4883 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4884 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4885 if (BO->IsNUW) 4886 Flags = setFlags(Flags, SCEV::FlagNUW); 4887 if (BO->IsNSW) 4888 Flags = setFlags(Flags, SCEV::FlagNSW); 4889 } 4890 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4891 // If the increment is an inbounds GEP, then we know the address 4892 // space cannot be wrapped around. We cannot make any guarantee 4893 // about signed or unsigned overflow because pointers are 4894 // unsigned but we may have a negative index from the base 4895 // pointer. We can guarantee that no unsigned wrap occurs if the 4896 // indices form a positive value. 4897 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4898 Flags = setFlags(Flags, SCEV::FlagNW); 4899 4900 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4901 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4902 Flags = setFlags(Flags, SCEV::FlagNUW); 4903 } 4904 4905 // We cannot transfer nuw and nsw flags from subtraction 4906 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4907 // for instance. 4908 } 4909 4910 const SCEV *StartVal = getSCEV(StartValueV); 4911 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4912 4913 // Okay, for the entire analysis of this edge we assumed the PHI 4914 // to be symbolic. We now need to go back and purge all of the 4915 // entries for the scalars that use the symbolic expression. 4916 forgetSymbolicName(PN, SymbolicName); 4917 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4918 4919 // We can add Flags to the post-inc expression only if we 4920 // know that it is *undefined behavior* for BEValueV to 4921 // overflow. 4922 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4923 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4924 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4925 4926 return PHISCEV; 4927 } 4928 } 4929 } else { 4930 // Otherwise, this could be a loop like this: 4931 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4932 // In this case, j = {1,+,1} and BEValue is j. 4933 // Because the other in-value of i (0) fits the evolution of BEValue 4934 // i really is an addrec evolution. 4935 // 4936 // We can generalize this saying that i is the shifted value of BEValue 4937 // by one iteration: 4938 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4939 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4940 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4941 if (Shifted != getCouldNotCompute() && 4942 Start != getCouldNotCompute()) { 4943 const SCEV *StartVal = getSCEV(StartValueV); 4944 if (Start == StartVal) { 4945 // Okay, for the entire analysis of this edge we assumed the PHI 4946 // to be symbolic. We now need to go back and purge all of the 4947 // entries for the scalars that use the symbolic expression. 4948 forgetSymbolicName(PN, SymbolicName); 4949 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4950 return Shifted; 4951 } 4952 } 4953 } 4954 4955 // Remove the temporary PHI node SCEV that has been inserted while intending 4956 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4957 // as it will prevent later (possibly simpler) SCEV expressions to be added 4958 // to the ValueExprMap. 4959 eraseValueFromMap(PN); 4960 4961 return nullptr; 4962 } 4963 4964 // Checks if the SCEV S is available at BB. S is considered available at BB 4965 // if S can be materialized at BB without introducing a fault. 4966 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4967 BasicBlock *BB) { 4968 struct CheckAvailable { 4969 bool TraversalDone = false; 4970 bool Available = true; 4971 4972 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4973 BasicBlock *BB = nullptr; 4974 DominatorTree &DT; 4975 4976 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4977 : L(L), BB(BB), DT(DT) {} 4978 4979 bool setUnavailable() { 4980 TraversalDone = true; 4981 Available = false; 4982 return false; 4983 } 4984 4985 bool follow(const SCEV *S) { 4986 switch (S->getSCEVType()) { 4987 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4988 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4989 case scUMinExpr: 4990 case scSMinExpr: 4991 // These expressions are available if their operand(s) is/are. 4992 return true; 4993 4994 case scAddRecExpr: { 4995 // We allow add recurrences that are on the loop BB is in, or some 4996 // outer loop. This guarantees availability because the value of the 4997 // add recurrence at BB is simply the "current" value of the induction 4998 // variable. We can relax this in the future; for instance an add 4999 // recurrence on a sibling dominating loop is also available at BB. 5000 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5001 if (L && (ARLoop == L || ARLoop->contains(L))) 5002 return true; 5003 5004 return setUnavailable(); 5005 } 5006 5007 case scUnknown: { 5008 // For SCEVUnknown, we check for simple dominance. 5009 const auto *SU = cast<SCEVUnknown>(S); 5010 Value *V = SU->getValue(); 5011 5012 if (isa<Argument>(V)) 5013 return false; 5014 5015 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5016 return false; 5017 5018 return setUnavailable(); 5019 } 5020 5021 case scUDivExpr: 5022 case scCouldNotCompute: 5023 // We do not try to smart about these at all. 5024 return setUnavailable(); 5025 } 5026 llvm_unreachable("switch should be fully covered!"); 5027 } 5028 5029 bool isDone() { return TraversalDone; } 5030 }; 5031 5032 CheckAvailable CA(L, BB, DT); 5033 SCEVTraversal<CheckAvailable> ST(CA); 5034 5035 ST.visitAll(S); 5036 return CA.Available; 5037 } 5038 5039 // Try to match a control flow sequence that branches out at BI and merges back 5040 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5041 // match. 5042 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5043 Value *&C, Value *&LHS, Value *&RHS) { 5044 C = BI->getCondition(); 5045 5046 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5047 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5048 5049 if (!LeftEdge.isSingleEdge()) 5050 return false; 5051 5052 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5053 5054 Use &LeftUse = Merge->getOperandUse(0); 5055 Use &RightUse = Merge->getOperandUse(1); 5056 5057 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5058 LHS = LeftUse; 5059 RHS = RightUse; 5060 return true; 5061 } 5062 5063 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5064 LHS = RightUse; 5065 RHS = LeftUse; 5066 return true; 5067 } 5068 5069 return false; 5070 } 5071 5072 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5073 auto IsReachable = 5074 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5075 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5076 const Loop *L = LI.getLoopFor(PN->getParent()); 5077 5078 // We don't want to break LCSSA, even in a SCEV expression tree. 5079 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5080 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5081 return nullptr; 5082 5083 // Try to match 5084 // 5085 // br %cond, label %left, label %right 5086 // left: 5087 // br label %merge 5088 // right: 5089 // br label %merge 5090 // merge: 5091 // V = phi [ %x, %left ], [ %y, %right ] 5092 // 5093 // as "select %cond, %x, %y" 5094 5095 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5096 assert(IDom && "At least the entry block should dominate PN"); 5097 5098 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5099 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5100 5101 if (BI && BI->isConditional() && 5102 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5103 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5104 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5105 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5106 } 5107 5108 return nullptr; 5109 } 5110 5111 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5112 if (const SCEV *S = createAddRecFromPHI(PN)) 5113 return S; 5114 5115 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5116 return S; 5117 5118 // If the PHI has a single incoming value, follow that value, unless the 5119 // PHI's incoming blocks are in a different loop, in which case doing so 5120 // risks breaking LCSSA form. Instcombine would normally zap these, but 5121 // it doesn't have DominatorTree information, so it may miss cases. 5122 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5123 if (LI.replacementPreservesLCSSAForm(PN, V)) 5124 return getSCEV(V); 5125 5126 // If it's not a loop phi, we can't handle it yet. 5127 return getUnknown(PN); 5128 } 5129 5130 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5131 Value *Cond, 5132 Value *TrueVal, 5133 Value *FalseVal) { 5134 // Handle "constant" branch or select. This can occur for instance when a 5135 // loop pass transforms an inner loop and moves on to process the outer loop. 5136 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5137 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5138 5139 // Try to match some simple smax or umax patterns. 5140 auto *ICI = dyn_cast<ICmpInst>(Cond); 5141 if (!ICI) 5142 return getUnknown(I); 5143 5144 Value *LHS = ICI->getOperand(0); 5145 Value *RHS = ICI->getOperand(1); 5146 5147 switch (ICI->getPredicate()) { 5148 case ICmpInst::ICMP_SLT: 5149 case ICmpInst::ICMP_SLE: 5150 std::swap(LHS, RHS); 5151 LLVM_FALLTHROUGH; 5152 case ICmpInst::ICMP_SGT: 5153 case ICmpInst::ICMP_SGE: 5154 // a >s b ? a+x : b+x -> smax(a, b)+x 5155 // a >s b ? b+x : a+x -> smin(a, b)+x 5156 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5157 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5158 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5159 const SCEV *LA = getSCEV(TrueVal); 5160 const SCEV *RA = getSCEV(FalseVal); 5161 const SCEV *LDiff = getMinusSCEV(LA, LS); 5162 const SCEV *RDiff = getMinusSCEV(RA, RS); 5163 if (LDiff == RDiff) 5164 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5165 LDiff = getMinusSCEV(LA, RS); 5166 RDiff = getMinusSCEV(RA, LS); 5167 if (LDiff == RDiff) 5168 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5169 } 5170 break; 5171 case ICmpInst::ICMP_ULT: 5172 case ICmpInst::ICMP_ULE: 5173 std::swap(LHS, RHS); 5174 LLVM_FALLTHROUGH; 5175 case ICmpInst::ICMP_UGT: 5176 case ICmpInst::ICMP_UGE: 5177 // a >u b ? a+x : b+x -> umax(a, b)+x 5178 // a >u b ? b+x : a+x -> umin(a, b)+x 5179 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5180 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5181 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5182 const SCEV *LA = getSCEV(TrueVal); 5183 const SCEV *RA = getSCEV(FalseVal); 5184 const SCEV *LDiff = getMinusSCEV(LA, LS); 5185 const SCEV *RDiff = getMinusSCEV(RA, RS); 5186 if (LDiff == RDiff) 5187 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5188 LDiff = getMinusSCEV(LA, RS); 5189 RDiff = getMinusSCEV(RA, LS); 5190 if (LDiff == RDiff) 5191 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5192 } 5193 break; 5194 case ICmpInst::ICMP_NE: 5195 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5196 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5197 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5198 const SCEV *One = getOne(I->getType()); 5199 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5200 const SCEV *LA = getSCEV(TrueVal); 5201 const SCEV *RA = getSCEV(FalseVal); 5202 const SCEV *LDiff = getMinusSCEV(LA, LS); 5203 const SCEV *RDiff = getMinusSCEV(RA, One); 5204 if (LDiff == RDiff) 5205 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5206 } 5207 break; 5208 case ICmpInst::ICMP_EQ: 5209 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5210 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5211 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5212 const SCEV *One = getOne(I->getType()); 5213 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5214 const SCEV *LA = getSCEV(TrueVal); 5215 const SCEV *RA = getSCEV(FalseVal); 5216 const SCEV *LDiff = getMinusSCEV(LA, One); 5217 const SCEV *RDiff = getMinusSCEV(RA, LS); 5218 if (LDiff == RDiff) 5219 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5220 } 5221 break; 5222 default: 5223 break; 5224 } 5225 5226 return getUnknown(I); 5227 } 5228 5229 /// Expand GEP instructions into add and multiply operations. This allows them 5230 /// to be analyzed by regular SCEV code. 5231 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5232 // Don't attempt to analyze GEPs over unsized objects. 5233 if (!GEP->getSourceElementType()->isSized()) 5234 return getUnknown(GEP); 5235 5236 SmallVector<const SCEV *, 4> IndexExprs; 5237 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5238 IndexExprs.push_back(getSCEV(*Index)); 5239 return getGEPExpr(GEP, IndexExprs); 5240 } 5241 5242 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5243 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5244 return C->getAPInt().countTrailingZeros(); 5245 5246 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5247 return std::min(GetMinTrailingZeros(T->getOperand()), 5248 (uint32_t)getTypeSizeInBits(T->getType())); 5249 5250 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5251 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5252 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5253 ? getTypeSizeInBits(E->getType()) 5254 : OpRes; 5255 } 5256 5257 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5258 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5259 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5260 ? getTypeSizeInBits(E->getType()) 5261 : OpRes; 5262 } 5263 5264 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5265 // The result is the min of all operands results. 5266 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5267 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5268 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5269 return MinOpRes; 5270 } 5271 5272 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5273 // The result is the sum of all operands results. 5274 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5275 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5276 for (unsigned i = 1, e = M->getNumOperands(); 5277 SumOpRes != BitWidth && i != e; ++i) 5278 SumOpRes = 5279 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5280 return SumOpRes; 5281 } 5282 5283 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5284 // The result is the min of all operands results. 5285 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5286 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5287 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5288 return MinOpRes; 5289 } 5290 5291 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5292 // The result is the min of all operands results. 5293 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5294 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5295 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5296 return MinOpRes; 5297 } 5298 5299 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5300 // The result is the min of all operands results. 5301 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5302 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5303 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5304 return MinOpRes; 5305 } 5306 5307 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5308 // For a SCEVUnknown, ask ValueTracking. 5309 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5310 return Known.countMinTrailingZeros(); 5311 } 5312 5313 // SCEVUDivExpr 5314 return 0; 5315 } 5316 5317 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5318 auto I = MinTrailingZerosCache.find(S); 5319 if (I != MinTrailingZerosCache.end()) 5320 return I->second; 5321 5322 uint32_t Result = GetMinTrailingZerosImpl(S); 5323 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5324 assert(InsertPair.second && "Should insert a new key"); 5325 return InsertPair.first->second; 5326 } 5327 5328 /// Helper method to assign a range to V from metadata present in the IR. 5329 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5330 if (Instruction *I = dyn_cast<Instruction>(V)) 5331 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5332 return getConstantRangeFromMetadata(*MD); 5333 5334 return None; 5335 } 5336 5337 /// Determine the range for a particular SCEV. If SignHint is 5338 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5339 /// with a "cleaner" unsigned (resp. signed) representation. 5340 const ConstantRange & 5341 ScalarEvolution::getRangeRef(const SCEV *S, 5342 ScalarEvolution::RangeSignHint SignHint) { 5343 DenseMap<const SCEV *, ConstantRange> &Cache = 5344 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5345 : SignedRanges; 5346 ConstantRange::PreferredRangeType RangeType = 5347 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5348 ? ConstantRange::Unsigned : ConstantRange::Signed; 5349 5350 // See if we've computed this range already. 5351 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5352 if (I != Cache.end()) 5353 return I->second; 5354 5355 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5356 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5357 5358 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5359 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5360 using OBO = OverflowingBinaryOperator; 5361 5362 // If the value has known zeros, the maximum value will have those known zeros 5363 // as well. 5364 uint32_t TZ = GetMinTrailingZeros(S); 5365 if (TZ != 0) { 5366 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5367 ConservativeResult = 5368 ConstantRange(APInt::getMinValue(BitWidth), 5369 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5370 else 5371 ConservativeResult = ConstantRange( 5372 APInt::getSignedMinValue(BitWidth), 5373 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5374 } 5375 5376 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5377 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5378 unsigned WrapType = OBO::AnyWrap; 5379 if (Add->hasNoSignedWrap()) 5380 WrapType |= OBO::NoSignedWrap; 5381 if (Add->hasNoUnsignedWrap()) 5382 WrapType |= OBO::NoUnsignedWrap; 5383 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5384 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5385 WrapType, RangeType); 5386 return setRange(Add, SignHint, 5387 ConservativeResult.intersectWith(X, RangeType)); 5388 } 5389 5390 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5391 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5392 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5393 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5394 return setRange(Mul, SignHint, 5395 ConservativeResult.intersectWith(X, RangeType)); 5396 } 5397 5398 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5399 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5400 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5401 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5402 return setRange(SMax, SignHint, 5403 ConservativeResult.intersectWith(X, RangeType)); 5404 } 5405 5406 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5407 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5408 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5409 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5410 return setRange(UMax, SignHint, 5411 ConservativeResult.intersectWith(X, RangeType)); 5412 } 5413 5414 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5415 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5416 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5417 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5418 return setRange(SMin, SignHint, 5419 ConservativeResult.intersectWith(X, RangeType)); 5420 } 5421 5422 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5423 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5424 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5425 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5426 return setRange(UMin, SignHint, 5427 ConservativeResult.intersectWith(X, RangeType)); 5428 } 5429 5430 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5431 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5432 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5433 return setRange(UDiv, SignHint, 5434 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5435 } 5436 5437 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5438 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5439 return setRange(ZExt, SignHint, 5440 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5441 RangeType)); 5442 } 5443 5444 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5445 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5446 return setRange(SExt, SignHint, 5447 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5448 RangeType)); 5449 } 5450 5451 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5452 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5453 return setRange(Trunc, SignHint, 5454 ConservativeResult.intersectWith(X.truncate(BitWidth), 5455 RangeType)); 5456 } 5457 5458 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5459 // If there's no unsigned wrap, the value will never be less than its 5460 // initial value. 5461 if (AddRec->hasNoUnsignedWrap()) { 5462 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5463 if (!UnsignedMinValue.isNullValue()) 5464 ConservativeResult = ConservativeResult.intersectWith( 5465 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5466 } 5467 5468 // If there's no signed wrap, and all the operands except initial value have 5469 // the same sign or zero, the value won't ever be: 5470 // 1: smaller than initial value if operands are non negative, 5471 // 2: bigger than initial value if operands are non positive. 5472 // For both cases, value can not cross signed min/max boundary. 5473 if (AddRec->hasNoSignedWrap()) { 5474 bool AllNonNeg = true; 5475 bool AllNonPos = true; 5476 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5477 if (!isKnownNonNegative(AddRec->getOperand(i))) 5478 AllNonNeg = false; 5479 if (!isKnownNonPositive(AddRec->getOperand(i))) 5480 AllNonPos = false; 5481 } 5482 if (AllNonNeg) 5483 ConservativeResult = ConservativeResult.intersectWith( 5484 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5485 APInt::getSignedMinValue(BitWidth)), 5486 RangeType); 5487 else if (AllNonPos) 5488 ConservativeResult = ConservativeResult.intersectWith( 5489 ConstantRange::getNonEmpty( 5490 APInt::getSignedMinValue(BitWidth), 5491 getSignedRangeMax(AddRec->getStart()) + 1), 5492 RangeType); 5493 } 5494 5495 // TODO: non-affine addrec 5496 if (AddRec->isAffine()) { 5497 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5498 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5499 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5500 auto RangeFromAffine = getRangeForAffineAR( 5501 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5502 BitWidth); 5503 ConservativeResult = 5504 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5505 5506 auto RangeFromFactoring = getRangeViaFactoring( 5507 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5508 BitWidth); 5509 ConservativeResult = 5510 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5511 } 5512 } 5513 5514 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5515 } 5516 5517 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5518 // Check if the IR explicitly contains !range metadata. 5519 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5520 if (MDRange.hasValue()) 5521 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5522 RangeType); 5523 5524 // Split here to avoid paying the compile-time cost of calling both 5525 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5526 // if needed. 5527 const DataLayout &DL = getDataLayout(); 5528 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5529 // For a SCEVUnknown, ask ValueTracking. 5530 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5531 if (Known.getBitWidth() != BitWidth) 5532 Known = Known.zextOrTrunc(BitWidth); 5533 // If Known does not result in full-set, intersect with it. 5534 if (Known.getMinValue() != Known.getMaxValue() + 1) 5535 ConservativeResult = ConservativeResult.intersectWith( 5536 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5537 RangeType); 5538 } else { 5539 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5540 "generalize as needed!"); 5541 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5542 // If the pointer size is larger than the index size type, this can cause 5543 // NS to be larger than BitWidth. So compensate for this. 5544 if (U->getType()->isPointerTy()) { 5545 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5546 int ptrIdxDiff = ptrSize - BitWidth; 5547 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5548 NS -= ptrIdxDiff; 5549 } 5550 5551 if (NS > 1) 5552 ConservativeResult = ConservativeResult.intersectWith( 5553 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5554 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5555 RangeType); 5556 } 5557 5558 // A range of Phi is a subset of union of all ranges of its input. 5559 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5560 // Make sure that we do not run over cycled Phis. 5561 if (PendingPhiRanges.insert(Phi).second) { 5562 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5563 for (auto &Op : Phi->operands()) { 5564 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5565 RangeFromOps = RangeFromOps.unionWith(OpRange); 5566 // No point to continue if we already have a full set. 5567 if (RangeFromOps.isFullSet()) 5568 break; 5569 } 5570 ConservativeResult = 5571 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5572 bool Erased = PendingPhiRanges.erase(Phi); 5573 assert(Erased && "Failed to erase Phi properly?"); 5574 (void) Erased; 5575 } 5576 } 5577 5578 return setRange(U, SignHint, std::move(ConservativeResult)); 5579 } 5580 5581 return setRange(S, SignHint, std::move(ConservativeResult)); 5582 } 5583 5584 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5585 // values that the expression can take. Initially, the expression has a value 5586 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5587 // argument defines if we treat Step as signed or unsigned. 5588 static ConstantRange getRangeForAffineARHelper(APInt Step, 5589 const ConstantRange &StartRange, 5590 const APInt &MaxBECount, 5591 unsigned BitWidth, bool Signed) { 5592 // If either Step or MaxBECount is 0, then the expression won't change, and we 5593 // just need to return the initial range. 5594 if (Step == 0 || MaxBECount == 0) 5595 return StartRange; 5596 5597 // If we don't know anything about the initial value (i.e. StartRange is 5598 // FullRange), then we don't know anything about the final range either. 5599 // Return FullRange. 5600 if (StartRange.isFullSet()) 5601 return ConstantRange::getFull(BitWidth); 5602 5603 // If Step is signed and negative, then we use its absolute value, but we also 5604 // note that we're moving in the opposite direction. 5605 bool Descending = Signed && Step.isNegative(); 5606 5607 if (Signed) 5608 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5609 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5610 // This equations hold true due to the well-defined wrap-around behavior of 5611 // APInt. 5612 Step = Step.abs(); 5613 5614 // Check if Offset is more than full span of BitWidth. If it is, the 5615 // expression is guaranteed to overflow. 5616 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5617 return ConstantRange::getFull(BitWidth); 5618 5619 // Offset is by how much the expression can change. Checks above guarantee no 5620 // overflow here. 5621 APInt Offset = Step * MaxBECount; 5622 5623 // Minimum value of the final range will match the minimal value of StartRange 5624 // if the expression is increasing and will be decreased by Offset otherwise. 5625 // Maximum value of the final range will match the maximal value of StartRange 5626 // if the expression is decreasing and will be increased by Offset otherwise. 5627 APInt StartLower = StartRange.getLower(); 5628 APInt StartUpper = StartRange.getUpper() - 1; 5629 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5630 : (StartUpper + std::move(Offset)); 5631 5632 // It's possible that the new minimum/maximum value will fall into the initial 5633 // range (due to wrap around). This means that the expression can take any 5634 // value in this bitwidth, and we have to return full range. 5635 if (StartRange.contains(MovedBoundary)) 5636 return ConstantRange::getFull(BitWidth); 5637 5638 APInt NewLower = 5639 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5640 APInt NewUpper = 5641 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5642 NewUpper += 1; 5643 5644 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5645 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5646 } 5647 5648 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5649 const SCEV *Step, 5650 const SCEV *MaxBECount, 5651 unsigned BitWidth) { 5652 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5653 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5654 "Precondition!"); 5655 5656 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5657 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5658 5659 // First, consider step signed. 5660 ConstantRange StartSRange = getSignedRange(Start); 5661 ConstantRange StepSRange = getSignedRange(Step); 5662 5663 // If Step can be both positive and negative, we need to find ranges for the 5664 // maximum absolute step values in both directions and union them. 5665 ConstantRange SR = 5666 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5667 MaxBECountValue, BitWidth, /* Signed = */ true); 5668 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5669 StartSRange, MaxBECountValue, 5670 BitWidth, /* Signed = */ true)); 5671 5672 // Next, consider step unsigned. 5673 ConstantRange UR = getRangeForAffineARHelper( 5674 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5675 MaxBECountValue, BitWidth, /* Signed = */ false); 5676 5677 // Finally, intersect signed and unsigned ranges. 5678 return SR.intersectWith(UR, ConstantRange::Smallest); 5679 } 5680 5681 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5682 const SCEV *Step, 5683 const SCEV *MaxBECount, 5684 unsigned BitWidth) { 5685 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5686 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5687 5688 struct SelectPattern { 5689 Value *Condition = nullptr; 5690 APInt TrueValue; 5691 APInt FalseValue; 5692 5693 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5694 const SCEV *S) { 5695 Optional<unsigned> CastOp; 5696 APInt Offset(BitWidth, 0); 5697 5698 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5699 "Should be!"); 5700 5701 // Peel off a constant offset: 5702 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5703 // In the future we could consider being smarter here and handle 5704 // {Start+Step,+,Step} too. 5705 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5706 return; 5707 5708 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5709 S = SA->getOperand(1); 5710 } 5711 5712 // Peel off a cast operation 5713 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5714 CastOp = SCast->getSCEVType(); 5715 S = SCast->getOperand(); 5716 } 5717 5718 using namespace llvm::PatternMatch; 5719 5720 auto *SU = dyn_cast<SCEVUnknown>(S); 5721 const APInt *TrueVal, *FalseVal; 5722 if (!SU || 5723 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5724 m_APInt(FalseVal)))) { 5725 Condition = nullptr; 5726 return; 5727 } 5728 5729 TrueValue = *TrueVal; 5730 FalseValue = *FalseVal; 5731 5732 // Re-apply the cast we peeled off earlier 5733 if (CastOp.hasValue()) 5734 switch (*CastOp) { 5735 default: 5736 llvm_unreachable("Unknown SCEV cast type!"); 5737 5738 case scTruncate: 5739 TrueValue = TrueValue.trunc(BitWidth); 5740 FalseValue = FalseValue.trunc(BitWidth); 5741 break; 5742 case scZeroExtend: 5743 TrueValue = TrueValue.zext(BitWidth); 5744 FalseValue = FalseValue.zext(BitWidth); 5745 break; 5746 case scSignExtend: 5747 TrueValue = TrueValue.sext(BitWidth); 5748 FalseValue = FalseValue.sext(BitWidth); 5749 break; 5750 } 5751 5752 // Re-apply the constant offset we peeled off earlier 5753 TrueValue += Offset; 5754 FalseValue += Offset; 5755 } 5756 5757 bool isRecognized() { return Condition != nullptr; } 5758 }; 5759 5760 SelectPattern StartPattern(*this, BitWidth, Start); 5761 if (!StartPattern.isRecognized()) 5762 return ConstantRange::getFull(BitWidth); 5763 5764 SelectPattern StepPattern(*this, BitWidth, Step); 5765 if (!StepPattern.isRecognized()) 5766 return ConstantRange::getFull(BitWidth); 5767 5768 if (StartPattern.Condition != StepPattern.Condition) { 5769 // We don't handle this case today; but we could, by considering four 5770 // possibilities below instead of two. I'm not sure if there are cases where 5771 // that will help over what getRange already does, though. 5772 return ConstantRange::getFull(BitWidth); 5773 } 5774 5775 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5776 // construct arbitrary general SCEV expressions here. This function is called 5777 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5778 // say) can end up caching a suboptimal value. 5779 5780 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5781 // C2352 and C2512 (otherwise it isn't needed). 5782 5783 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5784 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5785 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5786 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5787 5788 ConstantRange TrueRange = 5789 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5790 ConstantRange FalseRange = 5791 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5792 5793 return TrueRange.unionWith(FalseRange); 5794 } 5795 5796 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5797 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5798 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5799 5800 // Return early if there are no flags to propagate to the SCEV. 5801 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5802 if (BinOp->hasNoUnsignedWrap()) 5803 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5804 if (BinOp->hasNoSignedWrap()) 5805 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5806 if (Flags == SCEV::FlagAnyWrap) 5807 return SCEV::FlagAnyWrap; 5808 5809 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5810 } 5811 5812 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5813 // Here we check that I is in the header of the innermost loop containing I, 5814 // since we only deal with instructions in the loop header. The actual loop we 5815 // need to check later will come from an add recurrence, but getting that 5816 // requires computing the SCEV of the operands, which can be expensive. This 5817 // check we can do cheaply to rule out some cases early. 5818 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5819 if (InnermostContainingLoop == nullptr || 5820 InnermostContainingLoop->getHeader() != I->getParent()) 5821 return false; 5822 5823 // Only proceed if we can prove that I does not yield poison. 5824 if (!programUndefinedIfPoison(I)) 5825 return false; 5826 5827 // At this point we know that if I is executed, then it does not wrap 5828 // according to at least one of NSW or NUW. If I is not executed, then we do 5829 // not know if the calculation that I represents would wrap. Multiple 5830 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5831 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5832 // derived from other instructions that map to the same SCEV. We cannot make 5833 // that guarantee for cases where I is not executed. So we need to find the 5834 // loop that I is considered in relation to and prove that I is executed for 5835 // every iteration of that loop. That implies that the value that I 5836 // calculates does not wrap anywhere in the loop, so then we can apply the 5837 // flags to the SCEV. 5838 // 5839 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5840 // from different loops, so that we know which loop to prove that I is 5841 // executed in. 5842 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5843 // I could be an extractvalue from a call to an overflow intrinsic. 5844 // TODO: We can do better here in some cases. 5845 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5846 return false; 5847 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5848 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5849 bool AllOtherOpsLoopInvariant = true; 5850 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5851 ++OtherOpIndex) { 5852 if (OtherOpIndex != OpIndex) { 5853 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5854 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5855 AllOtherOpsLoopInvariant = false; 5856 break; 5857 } 5858 } 5859 } 5860 if (AllOtherOpsLoopInvariant && 5861 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5862 return true; 5863 } 5864 } 5865 return false; 5866 } 5867 5868 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5869 // If we know that \c I can never be poison period, then that's enough. 5870 if (isSCEVExprNeverPoison(I)) 5871 return true; 5872 5873 // For an add recurrence specifically, we assume that infinite loops without 5874 // side effects are undefined behavior, and then reason as follows: 5875 // 5876 // If the add recurrence is poison in any iteration, it is poison on all 5877 // future iterations (since incrementing poison yields poison). If the result 5878 // of the add recurrence is fed into the loop latch condition and the loop 5879 // does not contain any throws or exiting blocks other than the latch, we now 5880 // have the ability to "choose" whether the backedge is taken or not (by 5881 // choosing a sufficiently evil value for the poison feeding into the branch) 5882 // for every iteration including and after the one in which \p I first became 5883 // poison. There are two possibilities (let's call the iteration in which \p 5884 // I first became poison as K): 5885 // 5886 // 1. In the set of iterations including and after K, the loop body executes 5887 // no side effects. In this case executing the backege an infinte number 5888 // of times will yield undefined behavior. 5889 // 5890 // 2. In the set of iterations including and after K, the loop body executes 5891 // at least one side effect. In this case, that specific instance of side 5892 // effect is control dependent on poison, which also yields undefined 5893 // behavior. 5894 5895 auto *ExitingBB = L->getExitingBlock(); 5896 auto *LatchBB = L->getLoopLatch(); 5897 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5898 return false; 5899 5900 SmallPtrSet<const Instruction *, 16> Pushed; 5901 SmallVector<const Instruction *, 8> PoisonStack; 5902 5903 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5904 // things that are known to be poison under that assumption go on the 5905 // PoisonStack. 5906 Pushed.insert(I); 5907 PoisonStack.push_back(I); 5908 5909 bool LatchControlDependentOnPoison = false; 5910 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5911 const Instruction *Poison = PoisonStack.pop_back_val(); 5912 5913 for (auto *PoisonUser : Poison->users()) { 5914 if (propagatesPoison(cast<Operator>(PoisonUser))) { 5915 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5916 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5917 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5918 assert(BI->isConditional() && "Only possibility!"); 5919 if (BI->getParent() == LatchBB) { 5920 LatchControlDependentOnPoison = true; 5921 break; 5922 } 5923 } 5924 } 5925 } 5926 5927 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5928 } 5929 5930 ScalarEvolution::LoopProperties 5931 ScalarEvolution::getLoopProperties(const Loop *L) { 5932 using LoopProperties = ScalarEvolution::LoopProperties; 5933 5934 auto Itr = LoopPropertiesCache.find(L); 5935 if (Itr == LoopPropertiesCache.end()) { 5936 auto HasSideEffects = [](Instruction *I) { 5937 if (auto *SI = dyn_cast<StoreInst>(I)) 5938 return !SI->isSimple(); 5939 5940 return I->mayHaveSideEffects(); 5941 }; 5942 5943 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5944 /*HasNoSideEffects*/ true}; 5945 5946 for (auto *BB : L->getBlocks()) 5947 for (auto &I : *BB) { 5948 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5949 LP.HasNoAbnormalExits = false; 5950 if (HasSideEffects(&I)) 5951 LP.HasNoSideEffects = false; 5952 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5953 break; // We're already as pessimistic as we can get. 5954 } 5955 5956 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5957 assert(InsertPair.second && "We just checked!"); 5958 Itr = InsertPair.first; 5959 } 5960 5961 return Itr->second; 5962 } 5963 5964 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5965 if (!isSCEVable(V->getType())) 5966 return getUnknown(V); 5967 5968 if (Instruction *I = dyn_cast<Instruction>(V)) { 5969 // Don't attempt to analyze instructions in blocks that aren't 5970 // reachable. Such instructions don't matter, and they aren't required 5971 // to obey basic rules for definitions dominating uses which this 5972 // analysis depends on. 5973 if (!DT.isReachableFromEntry(I->getParent())) 5974 return getUnknown(UndefValue::get(V->getType())); 5975 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5976 return getConstant(CI); 5977 else if (isa<ConstantPointerNull>(V)) 5978 return getZero(V->getType()); 5979 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5980 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5981 else if (!isa<ConstantExpr>(V)) 5982 return getUnknown(V); 5983 5984 Operator *U = cast<Operator>(V); 5985 if (auto BO = MatchBinaryOp(U, DT)) { 5986 switch (BO->Opcode) { 5987 case Instruction::Add: { 5988 // The simple thing to do would be to just call getSCEV on both operands 5989 // and call getAddExpr with the result. However if we're looking at a 5990 // bunch of things all added together, this can be quite inefficient, 5991 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5992 // Instead, gather up all the operands and make a single getAddExpr call. 5993 // LLVM IR canonical form means we need only traverse the left operands. 5994 SmallVector<const SCEV *, 4> AddOps; 5995 do { 5996 if (BO->Op) { 5997 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5998 AddOps.push_back(OpSCEV); 5999 break; 6000 } 6001 6002 // If a NUW or NSW flag can be applied to the SCEV for this 6003 // addition, then compute the SCEV for this addition by itself 6004 // with a separate call to getAddExpr. We need to do that 6005 // instead of pushing the operands of the addition onto AddOps, 6006 // since the flags are only known to apply to this particular 6007 // addition - they may not apply to other additions that can be 6008 // formed with operands from AddOps. 6009 const SCEV *RHS = getSCEV(BO->RHS); 6010 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6011 if (Flags != SCEV::FlagAnyWrap) { 6012 const SCEV *LHS = getSCEV(BO->LHS); 6013 if (BO->Opcode == Instruction::Sub) 6014 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6015 else 6016 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6017 break; 6018 } 6019 } 6020 6021 if (BO->Opcode == Instruction::Sub) 6022 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6023 else 6024 AddOps.push_back(getSCEV(BO->RHS)); 6025 6026 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6027 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6028 NewBO->Opcode != Instruction::Sub)) { 6029 AddOps.push_back(getSCEV(BO->LHS)); 6030 break; 6031 } 6032 BO = NewBO; 6033 } while (true); 6034 6035 return getAddExpr(AddOps); 6036 } 6037 6038 case Instruction::Mul: { 6039 SmallVector<const SCEV *, 4> MulOps; 6040 do { 6041 if (BO->Op) { 6042 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6043 MulOps.push_back(OpSCEV); 6044 break; 6045 } 6046 6047 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6048 if (Flags != SCEV::FlagAnyWrap) { 6049 MulOps.push_back( 6050 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6051 break; 6052 } 6053 } 6054 6055 MulOps.push_back(getSCEV(BO->RHS)); 6056 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6057 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6058 MulOps.push_back(getSCEV(BO->LHS)); 6059 break; 6060 } 6061 BO = NewBO; 6062 } while (true); 6063 6064 return getMulExpr(MulOps); 6065 } 6066 case Instruction::UDiv: 6067 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6068 case Instruction::URem: 6069 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6070 case Instruction::Sub: { 6071 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6072 if (BO->Op) 6073 Flags = getNoWrapFlagsFromUB(BO->Op); 6074 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6075 } 6076 case Instruction::And: 6077 // For an expression like x&255 that merely masks off the high bits, 6078 // use zext(trunc(x)) as the SCEV expression. 6079 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6080 if (CI->isZero()) 6081 return getSCEV(BO->RHS); 6082 if (CI->isMinusOne()) 6083 return getSCEV(BO->LHS); 6084 const APInt &A = CI->getValue(); 6085 6086 // Instcombine's ShrinkDemandedConstant may strip bits out of 6087 // constants, obscuring what would otherwise be a low-bits mask. 6088 // Use computeKnownBits to compute what ShrinkDemandedConstant 6089 // knew about to reconstruct a low-bits mask value. 6090 unsigned LZ = A.countLeadingZeros(); 6091 unsigned TZ = A.countTrailingZeros(); 6092 unsigned BitWidth = A.getBitWidth(); 6093 KnownBits Known(BitWidth); 6094 computeKnownBits(BO->LHS, Known, getDataLayout(), 6095 0, &AC, nullptr, &DT); 6096 6097 APInt EffectiveMask = 6098 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6099 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6100 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6101 const SCEV *LHS = getSCEV(BO->LHS); 6102 const SCEV *ShiftedLHS = nullptr; 6103 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6104 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6105 // For an expression like (x * 8) & 8, simplify the multiply. 6106 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6107 unsigned GCD = std::min(MulZeros, TZ); 6108 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6109 SmallVector<const SCEV*, 4> MulOps; 6110 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6111 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6112 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6113 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6114 } 6115 } 6116 if (!ShiftedLHS) 6117 ShiftedLHS = getUDivExpr(LHS, MulCount); 6118 return getMulExpr( 6119 getZeroExtendExpr( 6120 getTruncateExpr(ShiftedLHS, 6121 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6122 BO->LHS->getType()), 6123 MulCount); 6124 } 6125 } 6126 break; 6127 6128 case Instruction::Or: 6129 // If the RHS of the Or is a constant, we may have something like: 6130 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6131 // optimizations will transparently handle this case. 6132 // 6133 // In order for this transformation to be safe, the LHS must be of the 6134 // form X*(2^n) and the Or constant must be less than 2^n. 6135 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6136 const SCEV *LHS = getSCEV(BO->LHS); 6137 const APInt &CIVal = CI->getValue(); 6138 if (GetMinTrailingZeros(LHS) >= 6139 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6140 // Build a plain add SCEV. 6141 return getAddExpr(LHS, getSCEV(CI), 6142 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6143 } 6144 } 6145 break; 6146 6147 case Instruction::Xor: 6148 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6149 // If the RHS of xor is -1, then this is a not operation. 6150 if (CI->isMinusOne()) 6151 return getNotSCEV(getSCEV(BO->LHS)); 6152 6153 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6154 // This is a variant of the check for xor with -1, and it handles 6155 // the case where instcombine has trimmed non-demanded bits out 6156 // of an xor with -1. 6157 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6158 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6159 if (LBO->getOpcode() == Instruction::And && 6160 LCI->getValue() == CI->getValue()) 6161 if (const SCEVZeroExtendExpr *Z = 6162 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6163 Type *UTy = BO->LHS->getType(); 6164 const SCEV *Z0 = Z->getOperand(); 6165 Type *Z0Ty = Z0->getType(); 6166 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6167 6168 // If C is a low-bits mask, the zero extend is serving to 6169 // mask off the high bits. Complement the operand and 6170 // re-apply the zext. 6171 if (CI->getValue().isMask(Z0TySize)) 6172 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6173 6174 // If C is a single bit, it may be in the sign-bit position 6175 // before the zero-extend. In this case, represent the xor 6176 // using an add, which is equivalent, and re-apply the zext. 6177 APInt Trunc = CI->getValue().trunc(Z0TySize); 6178 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6179 Trunc.isSignMask()) 6180 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6181 UTy); 6182 } 6183 } 6184 break; 6185 6186 case Instruction::Shl: 6187 // Turn shift left of a constant amount into a multiply. 6188 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6189 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6190 6191 // If the shift count is not less than the bitwidth, the result of 6192 // the shift is undefined. Don't try to analyze it, because the 6193 // resolution chosen here may differ from the resolution chosen in 6194 // other parts of the compiler. 6195 if (SA->getValue().uge(BitWidth)) 6196 break; 6197 6198 // We can safely preserve the nuw flag in all cases. It's also safe to 6199 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6200 // requires special handling. It can be preserved as long as we're not 6201 // left shifting by bitwidth - 1. 6202 auto Flags = SCEV::FlagAnyWrap; 6203 if (BO->Op) { 6204 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6205 if ((MulFlags & SCEV::FlagNSW) && 6206 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6207 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6208 if (MulFlags & SCEV::FlagNUW) 6209 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6210 } 6211 6212 Constant *X = ConstantInt::get( 6213 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6214 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6215 } 6216 break; 6217 6218 case Instruction::AShr: { 6219 // AShr X, C, where C is a constant. 6220 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6221 if (!CI) 6222 break; 6223 6224 Type *OuterTy = BO->LHS->getType(); 6225 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6226 // If the shift count is not less than the bitwidth, the result of 6227 // the shift is undefined. Don't try to analyze it, because the 6228 // resolution chosen here may differ from the resolution chosen in 6229 // other parts of the compiler. 6230 if (CI->getValue().uge(BitWidth)) 6231 break; 6232 6233 if (CI->isZero()) 6234 return getSCEV(BO->LHS); // shift by zero --> noop 6235 6236 uint64_t AShrAmt = CI->getZExtValue(); 6237 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6238 6239 Operator *L = dyn_cast<Operator>(BO->LHS); 6240 if (L && L->getOpcode() == Instruction::Shl) { 6241 // X = Shl A, n 6242 // Y = AShr X, m 6243 // Both n and m are constant. 6244 6245 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6246 if (L->getOperand(1) == BO->RHS) 6247 // For a two-shift sext-inreg, i.e. n = m, 6248 // use sext(trunc(x)) as the SCEV expression. 6249 return getSignExtendExpr( 6250 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6251 6252 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6253 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6254 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6255 if (ShlAmt > AShrAmt) { 6256 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6257 // expression. We already checked that ShlAmt < BitWidth, so 6258 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6259 // ShlAmt - AShrAmt < Amt. 6260 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6261 ShlAmt - AShrAmt); 6262 return getSignExtendExpr( 6263 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6264 getConstant(Mul)), OuterTy); 6265 } 6266 } 6267 } 6268 break; 6269 } 6270 } 6271 } 6272 6273 switch (U->getOpcode()) { 6274 case Instruction::Trunc: 6275 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6276 6277 case Instruction::ZExt: 6278 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6279 6280 case Instruction::SExt: 6281 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6282 // The NSW flag of a subtract does not always survive the conversion to 6283 // A + (-1)*B. By pushing sign extension onto its operands we are much 6284 // more likely to preserve NSW and allow later AddRec optimisations. 6285 // 6286 // NOTE: This is effectively duplicating this logic from getSignExtend: 6287 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6288 // but by that point the NSW information has potentially been lost. 6289 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6290 Type *Ty = U->getType(); 6291 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6292 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6293 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6294 } 6295 } 6296 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6297 6298 case Instruction::BitCast: 6299 // BitCasts are no-op casts so we just eliminate the cast. 6300 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6301 return getSCEV(U->getOperand(0)); 6302 break; 6303 6304 case Instruction::PtrToInt: { 6305 // It's tempting to handle inttoptr and ptrtoint as no-ops, 6306 // however this can lead to pointer expressions which cannot safely be 6307 // expanded to GEPs because ScalarEvolution doesn't respect 6308 // the GEP aliasing rules when simplifying integer expressions. 6309 // 6310 // However, given 6311 // %x = ??? 6312 // %y = ptrtoint %x 6313 // %z = ptrtoint %x 6314 // it is safe to say that %y and %z are the same thing. 6315 // 6316 // So instead of modelling the cast itself as unknown, 6317 // since the casts are transparent within SCEV, 6318 // we can at least model the casts original value as unknow instead. 6319 6320 // BUT, there's caveat. If we simply model %x as unknown, unrelated uses 6321 // of %x will also see it as unknown, which is obviously bad. 6322 // So we can only do this iff %x would be modelled as unknown anyways. 6323 auto *OpSCEV = getSCEV(U->getOperand(0)); 6324 if (isa<SCEVUnknown>(OpSCEV)) 6325 return getTruncateOrZeroExtend(OpSCEV, U->getType()); 6326 // If we can model the operand, however, we must fallback to modelling 6327 // the whole cast as unknown instead. 6328 LLVM_FALLTHROUGH; 6329 } 6330 case Instruction::IntToPtr: 6331 // We can't do this for inttoptr at all, however. 6332 return getUnknown(V); 6333 6334 case Instruction::SDiv: 6335 // If both operands are non-negative, this is just an udiv. 6336 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6337 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6338 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6339 break; 6340 6341 case Instruction::SRem: 6342 // If both operands are non-negative, this is just an urem. 6343 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6344 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6345 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6346 break; 6347 6348 case Instruction::GetElementPtr: 6349 return createNodeForGEP(cast<GEPOperator>(U)); 6350 6351 case Instruction::PHI: 6352 return createNodeForPHI(cast<PHINode>(U)); 6353 6354 case Instruction::Select: 6355 // U can also be a select constant expr, which let fall through. Since 6356 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6357 // constant expressions cannot have instructions as operands, we'd have 6358 // returned getUnknown for a select constant expressions anyway. 6359 if (isa<Instruction>(U)) 6360 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6361 U->getOperand(1), U->getOperand(2)); 6362 break; 6363 6364 case Instruction::Call: 6365 case Instruction::Invoke: 6366 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6367 return getSCEV(RV); 6368 6369 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6370 switch (II->getIntrinsicID()) { 6371 case Intrinsic::abs: { 6372 const SCEV *Op = getSCEV(II->getArgOperand(0)); 6373 SCEV::NoWrapFlags Flags = 6374 cast<ConstantInt>(II->getArgOperand(1))->isOne() 6375 ? SCEV::FlagNSW 6376 : SCEV::FlagAnyWrap; 6377 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 6378 } 6379 case Intrinsic::umax: 6380 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6381 getSCEV(II->getArgOperand(1))); 6382 case Intrinsic::umin: 6383 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6384 getSCEV(II->getArgOperand(1))); 6385 case Intrinsic::smax: 6386 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6387 getSCEV(II->getArgOperand(1))); 6388 case Intrinsic::smin: 6389 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6390 getSCEV(II->getArgOperand(1))); 6391 case Intrinsic::usub_sat: { 6392 const SCEV *X = getSCEV(II->getArgOperand(0)); 6393 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6394 const SCEV *ClampedY = getUMinExpr(X, Y); 6395 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6396 } 6397 case Intrinsic::uadd_sat: { 6398 const SCEV *X = getSCEV(II->getArgOperand(0)); 6399 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6400 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6401 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6402 } 6403 default: 6404 break; 6405 } 6406 } 6407 break; 6408 } 6409 6410 return getUnknown(V); 6411 } 6412 6413 //===----------------------------------------------------------------------===// 6414 // Iteration Count Computation Code 6415 // 6416 6417 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6418 if (!ExitCount) 6419 return 0; 6420 6421 ConstantInt *ExitConst = ExitCount->getValue(); 6422 6423 // Guard against huge trip counts. 6424 if (ExitConst->getValue().getActiveBits() > 32) 6425 return 0; 6426 6427 // In case of integer overflow, this returns 0, which is correct. 6428 return ((unsigned)ExitConst->getZExtValue()) + 1; 6429 } 6430 6431 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6432 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6433 return getSmallConstantTripCount(L, ExitingBB); 6434 6435 // No trip count information for multiple exits. 6436 return 0; 6437 } 6438 6439 unsigned 6440 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6441 const BasicBlock *ExitingBlock) { 6442 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6443 assert(L->isLoopExiting(ExitingBlock) && 6444 "Exiting block must actually branch out of the loop!"); 6445 const SCEVConstant *ExitCount = 6446 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6447 return getConstantTripCount(ExitCount); 6448 } 6449 6450 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6451 const auto *MaxExitCount = 6452 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6453 return getConstantTripCount(MaxExitCount); 6454 } 6455 6456 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6457 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6458 return getSmallConstantTripMultiple(L, ExitingBB); 6459 6460 // No trip multiple information for multiple exits. 6461 return 0; 6462 } 6463 6464 /// Returns the largest constant divisor of the trip count of this loop as a 6465 /// normal unsigned value, if possible. This means that the actual trip count is 6466 /// always a multiple of the returned value (don't forget the trip count could 6467 /// very well be zero as well!). 6468 /// 6469 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6470 /// multiple of a constant (which is also the case if the trip count is simply 6471 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6472 /// if the trip count is very large (>= 2^32). 6473 /// 6474 /// As explained in the comments for getSmallConstantTripCount, this assumes 6475 /// that control exits the loop via ExitingBlock. 6476 unsigned 6477 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6478 const BasicBlock *ExitingBlock) { 6479 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6480 assert(L->isLoopExiting(ExitingBlock) && 6481 "Exiting block must actually branch out of the loop!"); 6482 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6483 if (ExitCount == getCouldNotCompute()) 6484 return 1; 6485 6486 // Get the trip count from the BE count by adding 1. 6487 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6488 6489 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6490 if (!TC) 6491 // Attempt to factor more general cases. Returns the greatest power of 6492 // two divisor. If overflow happens, the trip count expression is still 6493 // divisible by the greatest power of 2 divisor returned. 6494 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6495 6496 ConstantInt *Result = TC->getValue(); 6497 6498 // Guard against huge trip counts (this requires checking 6499 // for zero to handle the case where the trip count == -1 and the 6500 // addition wraps). 6501 if (!Result || Result->getValue().getActiveBits() > 32 || 6502 Result->getValue().getActiveBits() == 0) 6503 return 1; 6504 6505 return (unsigned)Result->getZExtValue(); 6506 } 6507 6508 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6509 const BasicBlock *ExitingBlock, 6510 ExitCountKind Kind) { 6511 switch (Kind) { 6512 case Exact: 6513 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6514 case ConstantMaximum: 6515 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6516 }; 6517 llvm_unreachable("Invalid ExitCountKind!"); 6518 } 6519 6520 const SCEV * 6521 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6522 SCEVUnionPredicate &Preds) { 6523 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6524 } 6525 6526 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6527 ExitCountKind Kind) { 6528 switch (Kind) { 6529 case Exact: 6530 return getBackedgeTakenInfo(L).getExact(L, this); 6531 case ConstantMaximum: 6532 return getBackedgeTakenInfo(L).getMax(this); 6533 }; 6534 llvm_unreachable("Invalid ExitCountKind!"); 6535 } 6536 6537 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6538 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6539 } 6540 6541 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6542 static void 6543 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6544 BasicBlock *Header = L->getHeader(); 6545 6546 // Push all Loop-header PHIs onto the Worklist stack. 6547 for (PHINode &PN : Header->phis()) 6548 Worklist.push_back(&PN); 6549 } 6550 6551 const ScalarEvolution::BackedgeTakenInfo & 6552 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6553 auto &BTI = getBackedgeTakenInfo(L); 6554 if (BTI.hasFullInfo()) 6555 return BTI; 6556 6557 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6558 6559 if (!Pair.second) 6560 return Pair.first->second; 6561 6562 BackedgeTakenInfo Result = 6563 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6564 6565 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6566 } 6567 6568 const ScalarEvolution::BackedgeTakenInfo & 6569 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6570 // Initially insert an invalid entry for this loop. If the insertion 6571 // succeeds, proceed to actually compute a backedge-taken count and 6572 // update the value. The temporary CouldNotCompute value tells SCEV 6573 // code elsewhere that it shouldn't attempt to request a new 6574 // backedge-taken count, which could result in infinite recursion. 6575 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6576 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6577 if (!Pair.second) 6578 return Pair.first->second; 6579 6580 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6581 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6582 // must be cleared in this scope. 6583 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6584 6585 // In product build, there are no usage of statistic. 6586 (void)NumTripCountsComputed; 6587 (void)NumTripCountsNotComputed; 6588 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6589 const SCEV *BEExact = Result.getExact(L, this); 6590 if (BEExact != getCouldNotCompute()) { 6591 assert(isLoopInvariant(BEExact, L) && 6592 isLoopInvariant(Result.getMax(this), L) && 6593 "Computed backedge-taken count isn't loop invariant for loop!"); 6594 ++NumTripCountsComputed; 6595 } 6596 else if (Result.getMax(this) == getCouldNotCompute() && 6597 isa<PHINode>(L->getHeader()->begin())) { 6598 // Only count loops that have phi nodes as not being computable. 6599 ++NumTripCountsNotComputed; 6600 } 6601 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6602 6603 // Now that we know more about the trip count for this loop, forget any 6604 // existing SCEV values for PHI nodes in this loop since they are only 6605 // conservative estimates made without the benefit of trip count 6606 // information. This is similar to the code in forgetLoop, except that 6607 // it handles SCEVUnknown PHI nodes specially. 6608 if (Result.hasAnyInfo()) { 6609 SmallVector<Instruction *, 16> Worklist; 6610 PushLoopPHIs(L, Worklist); 6611 6612 SmallPtrSet<Instruction *, 8> Discovered; 6613 while (!Worklist.empty()) { 6614 Instruction *I = Worklist.pop_back_val(); 6615 6616 ValueExprMapType::iterator It = 6617 ValueExprMap.find_as(static_cast<Value *>(I)); 6618 if (It != ValueExprMap.end()) { 6619 const SCEV *Old = It->second; 6620 6621 // SCEVUnknown for a PHI either means that it has an unrecognized 6622 // structure, or it's a PHI that's in the progress of being computed 6623 // by createNodeForPHI. In the former case, additional loop trip 6624 // count information isn't going to change anything. In the later 6625 // case, createNodeForPHI will perform the necessary updates on its 6626 // own when it gets to that point. 6627 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6628 eraseValueFromMap(It->first); 6629 forgetMemoizedResults(Old); 6630 } 6631 if (PHINode *PN = dyn_cast<PHINode>(I)) 6632 ConstantEvolutionLoopExitValue.erase(PN); 6633 } 6634 6635 // Since we don't need to invalidate anything for correctness and we're 6636 // only invalidating to make SCEV's results more precise, we get to stop 6637 // early to avoid invalidating too much. This is especially important in 6638 // cases like: 6639 // 6640 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6641 // loop0: 6642 // %pn0 = phi 6643 // ... 6644 // loop1: 6645 // %pn1 = phi 6646 // ... 6647 // 6648 // where both loop0 and loop1's backedge taken count uses the SCEV 6649 // expression for %v. If we don't have the early stop below then in cases 6650 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6651 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6652 // count for loop1, effectively nullifying SCEV's trip count cache. 6653 for (auto *U : I->users()) 6654 if (auto *I = dyn_cast<Instruction>(U)) { 6655 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6656 if (LoopForUser && L->contains(LoopForUser) && 6657 Discovered.insert(I).second) 6658 Worklist.push_back(I); 6659 } 6660 } 6661 } 6662 6663 // Re-lookup the insert position, since the call to 6664 // computeBackedgeTakenCount above could result in a 6665 // recusive call to getBackedgeTakenInfo (on a different 6666 // loop), which would invalidate the iterator computed 6667 // earlier. 6668 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6669 } 6670 6671 void ScalarEvolution::forgetAllLoops() { 6672 // This method is intended to forget all info about loops. It should 6673 // invalidate caches as if the following happened: 6674 // - The trip counts of all loops have changed arbitrarily 6675 // - Every llvm::Value has been updated in place to produce a different 6676 // result. 6677 BackedgeTakenCounts.clear(); 6678 PredicatedBackedgeTakenCounts.clear(); 6679 LoopPropertiesCache.clear(); 6680 ConstantEvolutionLoopExitValue.clear(); 6681 ValueExprMap.clear(); 6682 ValuesAtScopes.clear(); 6683 LoopDispositions.clear(); 6684 BlockDispositions.clear(); 6685 UnsignedRanges.clear(); 6686 SignedRanges.clear(); 6687 ExprValueMap.clear(); 6688 HasRecMap.clear(); 6689 MinTrailingZerosCache.clear(); 6690 PredicatedSCEVRewrites.clear(); 6691 } 6692 6693 void ScalarEvolution::forgetLoop(const Loop *L) { 6694 // Drop any stored trip count value. 6695 auto RemoveLoopFromBackedgeMap = 6696 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6697 auto BTCPos = Map.find(L); 6698 if (BTCPos != Map.end()) { 6699 BTCPos->second.clear(); 6700 Map.erase(BTCPos); 6701 } 6702 }; 6703 6704 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6705 SmallVector<Instruction *, 32> Worklist; 6706 SmallPtrSet<Instruction *, 16> Visited; 6707 6708 // Iterate over all the loops and sub-loops to drop SCEV information. 6709 while (!LoopWorklist.empty()) { 6710 auto *CurrL = LoopWorklist.pop_back_val(); 6711 6712 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6713 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6714 6715 // Drop information about predicated SCEV rewrites for this loop. 6716 for (auto I = PredicatedSCEVRewrites.begin(); 6717 I != PredicatedSCEVRewrites.end();) { 6718 std::pair<const SCEV *, const Loop *> Entry = I->first; 6719 if (Entry.second == CurrL) 6720 PredicatedSCEVRewrites.erase(I++); 6721 else 6722 ++I; 6723 } 6724 6725 auto LoopUsersItr = LoopUsers.find(CurrL); 6726 if (LoopUsersItr != LoopUsers.end()) { 6727 for (auto *S : LoopUsersItr->second) 6728 forgetMemoizedResults(S); 6729 LoopUsers.erase(LoopUsersItr); 6730 } 6731 6732 // Drop information about expressions based on loop-header PHIs. 6733 PushLoopPHIs(CurrL, Worklist); 6734 6735 while (!Worklist.empty()) { 6736 Instruction *I = Worklist.pop_back_val(); 6737 if (!Visited.insert(I).second) 6738 continue; 6739 6740 ValueExprMapType::iterator It = 6741 ValueExprMap.find_as(static_cast<Value *>(I)); 6742 if (It != ValueExprMap.end()) { 6743 eraseValueFromMap(It->first); 6744 forgetMemoizedResults(It->second); 6745 if (PHINode *PN = dyn_cast<PHINode>(I)) 6746 ConstantEvolutionLoopExitValue.erase(PN); 6747 } 6748 6749 PushDefUseChildren(I, Worklist); 6750 } 6751 6752 LoopPropertiesCache.erase(CurrL); 6753 // Forget all contained loops too, to avoid dangling entries in the 6754 // ValuesAtScopes map. 6755 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6756 } 6757 } 6758 6759 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6760 while (Loop *Parent = L->getParentLoop()) 6761 L = Parent; 6762 forgetLoop(L); 6763 } 6764 6765 void ScalarEvolution::forgetValue(Value *V) { 6766 Instruction *I = dyn_cast<Instruction>(V); 6767 if (!I) return; 6768 6769 // Drop information about expressions based on loop-header PHIs. 6770 SmallVector<Instruction *, 16> Worklist; 6771 Worklist.push_back(I); 6772 6773 SmallPtrSet<Instruction *, 8> Visited; 6774 while (!Worklist.empty()) { 6775 I = Worklist.pop_back_val(); 6776 if (!Visited.insert(I).second) 6777 continue; 6778 6779 ValueExprMapType::iterator It = 6780 ValueExprMap.find_as(static_cast<Value *>(I)); 6781 if (It != ValueExprMap.end()) { 6782 eraseValueFromMap(It->first); 6783 forgetMemoizedResults(It->second); 6784 if (PHINode *PN = dyn_cast<PHINode>(I)) 6785 ConstantEvolutionLoopExitValue.erase(PN); 6786 } 6787 6788 PushDefUseChildren(I, Worklist); 6789 } 6790 } 6791 6792 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 6793 LoopDispositions.clear(); 6794 } 6795 6796 /// Get the exact loop backedge taken count considering all loop exits. A 6797 /// computable result can only be returned for loops with all exiting blocks 6798 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6799 /// is never skipped. This is a valid assumption as long as the loop exits via 6800 /// that test. For precise results, it is the caller's responsibility to specify 6801 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6802 const SCEV * 6803 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6804 SCEVUnionPredicate *Preds) const { 6805 // If any exits were not computable, the loop is not computable. 6806 if (!isComplete() || ExitNotTaken.empty()) 6807 return SE->getCouldNotCompute(); 6808 6809 const BasicBlock *Latch = L->getLoopLatch(); 6810 // All exiting blocks we have collected must dominate the only backedge. 6811 if (!Latch) 6812 return SE->getCouldNotCompute(); 6813 6814 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6815 // count is simply a minimum out of all these calculated exit counts. 6816 SmallVector<const SCEV *, 2> Ops; 6817 for (auto &ENT : ExitNotTaken) { 6818 const SCEV *BECount = ENT.ExactNotTaken; 6819 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6820 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6821 "We should only have known counts for exiting blocks that dominate " 6822 "latch!"); 6823 6824 Ops.push_back(BECount); 6825 6826 if (Preds && !ENT.hasAlwaysTruePredicate()) 6827 Preds->add(ENT.Predicate.get()); 6828 6829 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6830 "Predicate should be always true!"); 6831 } 6832 6833 return SE->getUMinFromMismatchedTypes(Ops); 6834 } 6835 6836 /// Get the exact not taken count for this loop exit. 6837 const SCEV * 6838 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 6839 ScalarEvolution *SE) const { 6840 for (auto &ENT : ExitNotTaken) 6841 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6842 return ENT.ExactNotTaken; 6843 6844 return SE->getCouldNotCompute(); 6845 } 6846 6847 const SCEV * 6848 ScalarEvolution::BackedgeTakenInfo::getMax(const BasicBlock *ExitingBlock, 6849 ScalarEvolution *SE) const { 6850 for (auto &ENT : ExitNotTaken) 6851 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6852 return ENT.MaxNotTaken; 6853 6854 return SE->getCouldNotCompute(); 6855 } 6856 6857 /// getMax - Get the max backedge taken count for the loop. 6858 const SCEV * 6859 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6860 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6861 return !ENT.hasAlwaysTruePredicate(); 6862 }; 6863 6864 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6865 return SE->getCouldNotCompute(); 6866 6867 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6868 "No point in having a non-constant max backedge taken count!"); 6869 return getMax(); 6870 } 6871 6872 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6873 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6874 return !ENT.hasAlwaysTruePredicate(); 6875 }; 6876 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6877 } 6878 6879 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6880 ScalarEvolution *SE) const { 6881 if (getMax() && getMax() != SE->getCouldNotCompute() && 6882 SE->hasOperand(getMax(), S)) 6883 return true; 6884 6885 for (auto &ENT : ExitNotTaken) 6886 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6887 SE->hasOperand(ENT.ExactNotTaken, S)) 6888 return true; 6889 6890 return false; 6891 } 6892 6893 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6894 : ExactNotTaken(E), MaxNotTaken(E) { 6895 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6896 isa<SCEVConstant>(MaxNotTaken)) && 6897 "No point in having a non-constant max backedge taken count!"); 6898 } 6899 6900 ScalarEvolution::ExitLimit::ExitLimit( 6901 const SCEV *E, const SCEV *M, bool MaxOrZero, 6902 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6903 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6904 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6905 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6906 "Exact is not allowed to be less precise than Max"); 6907 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6908 isa<SCEVConstant>(MaxNotTaken)) && 6909 "No point in having a non-constant max backedge taken count!"); 6910 for (auto *PredSet : PredSetList) 6911 for (auto *P : *PredSet) 6912 addPredicate(P); 6913 } 6914 6915 ScalarEvolution::ExitLimit::ExitLimit( 6916 const SCEV *E, const SCEV *M, bool MaxOrZero, 6917 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6918 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6919 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6920 isa<SCEVConstant>(MaxNotTaken)) && 6921 "No point in having a non-constant max backedge taken count!"); 6922 } 6923 6924 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6925 bool MaxOrZero) 6926 : ExitLimit(E, M, MaxOrZero, None) { 6927 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6928 isa<SCEVConstant>(MaxNotTaken)) && 6929 "No point in having a non-constant max backedge taken count!"); 6930 } 6931 6932 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6933 /// computable exit into a persistent ExitNotTakenInfo array. 6934 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6935 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6936 ExitCounts, 6937 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6938 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6939 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6940 6941 ExitNotTaken.reserve(ExitCounts.size()); 6942 std::transform( 6943 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6944 [&](const EdgeExitInfo &EEI) { 6945 BasicBlock *ExitBB = EEI.first; 6946 const ExitLimit &EL = EEI.second; 6947 if (EL.Predicates.empty()) 6948 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6949 nullptr); 6950 6951 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6952 for (auto *Pred : EL.Predicates) 6953 Predicate->add(Pred); 6954 6955 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6956 std::move(Predicate)); 6957 }); 6958 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6959 "No point in having a non-constant max backedge taken count!"); 6960 } 6961 6962 /// Invalidate this result and free the ExitNotTakenInfo array. 6963 void ScalarEvolution::BackedgeTakenInfo::clear() { 6964 ExitNotTaken.clear(); 6965 } 6966 6967 /// Compute the number of times the backedge of the specified loop will execute. 6968 ScalarEvolution::BackedgeTakenInfo 6969 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6970 bool AllowPredicates) { 6971 SmallVector<BasicBlock *, 8> ExitingBlocks; 6972 L->getExitingBlocks(ExitingBlocks); 6973 6974 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6975 6976 SmallVector<EdgeExitInfo, 4> ExitCounts; 6977 bool CouldComputeBECount = true; 6978 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6979 const SCEV *MustExitMaxBECount = nullptr; 6980 const SCEV *MayExitMaxBECount = nullptr; 6981 bool MustExitMaxOrZero = false; 6982 6983 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6984 // and compute maxBECount. 6985 // Do a union of all the predicates here. 6986 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6987 BasicBlock *ExitBB = ExitingBlocks[i]; 6988 6989 // We canonicalize untaken exits to br (constant), ignore them so that 6990 // proving an exit untaken doesn't negatively impact our ability to reason 6991 // about the loop as whole. 6992 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 6993 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 6994 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6995 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 6996 continue; 6997 } 6998 6999 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7000 7001 assert((AllowPredicates || EL.Predicates.empty()) && 7002 "Predicated exit limit when predicates are not allowed!"); 7003 7004 // 1. For each exit that can be computed, add an entry to ExitCounts. 7005 // CouldComputeBECount is true only if all exits can be computed. 7006 if (EL.ExactNotTaken == getCouldNotCompute()) 7007 // We couldn't compute an exact value for this exit, so 7008 // we won't be able to compute an exact value for the loop. 7009 CouldComputeBECount = false; 7010 else 7011 ExitCounts.emplace_back(ExitBB, EL); 7012 7013 // 2. Derive the loop's MaxBECount from each exit's max number of 7014 // non-exiting iterations. Partition the loop exits into two kinds: 7015 // LoopMustExits and LoopMayExits. 7016 // 7017 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7018 // is a LoopMayExit. If any computable LoopMustExit is found, then 7019 // MaxBECount is the minimum EL.MaxNotTaken of computable 7020 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7021 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7022 // computable EL.MaxNotTaken. 7023 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7024 DT.dominates(ExitBB, Latch)) { 7025 if (!MustExitMaxBECount) { 7026 MustExitMaxBECount = EL.MaxNotTaken; 7027 MustExitMaxOrZero = EL.MaxOrZero; 7028 } else { 7029 MustExitMaxBECount = 7030 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7031 } 7032 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7033 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7034 MayExitMaxBECount = EL.MaxNotTaken; 7035 else { 7036 MayExitMaxBECount = 7037 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7038 } 7039 } 7040 } 7041 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7042 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7043 // The loop backedge will be taken the maximum or zero times if there's 7044 // a single exit that must be taken the maximum or zero times. 7045 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7046 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7047 MaxBECount, MaxOrZero); 7048 } 7049 7050 ScalarEvolution::ExitLimit 7051 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7052 bool AllowPredicates) { 7053 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7054 // If our exiting block does not dominate the latch, then its connection with 7055 // loop's exit limit may be far from trivial. 7056 const BasicBlock *Latch = L->getLoopLatch(); 7057 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7058 return getCouldNotCompute(); 7059 7060 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7061 Instruction *Term = ExitingBlock->getTerminator(); 7062 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7063 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7064 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7065 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7066 "It should have one successor in loop and one exit block!"); 7067 // Proceed to the next level to examine the exit condition expression. 7068 return computeExitLimitFromCond( 7069 L, BI->getCondition(), ExitIfTrue, 7070 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7071 } 7072 7073 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7074 // For switch, make sure that there is a single exit from the loop. 7075 BasicBlock *Exit = nullptr; 7076 for (auto *SBB : successors(ExitingBlock)) 7077 if (!L->contains(SBB)) { 7078 if (Exit) // Multiple exit successors. 7079 return getCouldNotCompute(); 7080 Exit = SBB; 7081 } 7082 assert(Exit && "Exiting block must have at least one exit"); 7083 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7084 /*ControlsExit=*/IsOnlyExit); 7085 } 7086 7087 return getCouldNotCompute(); 7088 } 7089 7090 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7091 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7092 bool ControlsExit, bool AllowPredicates) { 7093 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7094 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7095 ControlsExit, AllowPredicates); 7096 } 7097 7098 Optional<ScalarEvolution::ExitLimit> 7099 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7100 bool ExitIfTrue, bool ControlsExit, 7101 bool AllowPredicates) { 7102 (void)this->L; 7103 (void)this->ExitIfTrue; 7104 (void)this->AllowPredicates; 7105 7106 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7107 this->AllowPredicates == AllowPredicates && 7108 "Variance in assumed invariant key components!"); 7109 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7110 if (Itr == TripCountMap.end()) 7111 return None; 7112 return Itr->second; 7113 } 7114 7115 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7116 bool ExitIfTrue, 7117 bool ControlsExit, 7118 bool AllowPredicates, 7119 const ExitLimit &EL) { 7120 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7121 this->AllowPredicates == AllowPredicates && 7122 "Variance in assumed invariant key components!"); 7123 7124 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7125 assert(InsertResult.second && "Expected successful insertion!"); 7126 (void)InsertResult; 7127 (void)ExitIfTrue; 7128 } 7129 7130 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7131 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7132 bool ControlsExit, bool AllowPredicates) { 7133 7134 if (auto MaybeEL = 7135 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7136 return *MaybeEL; 7137 7138 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7139 ControlsExit, AllowPredicates); 7140 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7141 return EL; 7142 } 7143 7144 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7145 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7146 bool ControlsExit, bool AllowPredicates) { 7147 // Check if the controlling expression for this loop is an And or Or. 7148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7149 if (BO->getOpcode() == Instruction::And) { 7150 // Recurse on the operands of the and. 7151 bool EitherMayExit = !ExitIfTrue; 7152 ExitLimit EL0 = computeExitLimitFromCondCached( 7153 Cache, L, BO->getOperand(0), ExitIfTrue, 7154 ControlsExit && !EitherMayExit, AllowPredicates); 7155 ExitLimit EL1 = computeExitLimitFromCondCached( 7156 Cache, L, BO->getOperand(1), ExitIfTrue, 7157 ControlsExit && !EitherMayExit, AllowPredicates); 7158 // Be robust against unsimplified IR for the form "and i1 X, true" 7159 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7160 return CI->isOne() ? EL0 : EL1; 7161 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7162 return CI->isOne() ? EL1 : EL0; 7163 const SCEV *BECount = getCouldNotCompute(); 7164 const SCEV *MaxBECount = getCouldNotCompute(); 7165 if (EitherMayExit) { 7166 // Both conditions must be true for the loop to continue executing. 7167 // Choose the less conservative count. 7168 if (EL0.ExactNotTaken == getCouldNotCompute() || 7169 EL1.ExactNotTaken == getCouldNotCompute()) 7170 BECount = getCouldNotCompute(); 7171 else 7172 BECount = 7173 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7174 if (EL0.MaxNotTaken == getCouldNotCompute()) 7175 MaxBECount = EL1.MaxNotTaken; 7176 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7177 MaxBECount = EL0.MaxNotTaken; 7178 else 7179 MaxBECount = 7180 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7181 } else { 7182 // Both conditions must be true at the same time for the loop to exit. 7183 // For now, be conservative. 7184 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7185 MaxBECount = EL0.MaxNotTaken; 7186 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7187 BECount = EL0.ExactNotTaken; 7188 } 7189 7190 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7191 // to be more aggressive when computing BECount than when computing 7192 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7193 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7194 // to not. 7195 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7196 !isa<SCEVCouldNotCompute>(BECount)) 7197 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7198 7199 return ExitLimit(BECount, MaxBECount, false, 7200 {&EL0.Predicates, &EL1.Predicates}); 7201 } 7202 if (BO->getOpcode() == Instruction::Or) { 7203 // Recurse on the operands of the or. 7204 bool EitherMayExit = ExitIfTrue; 7205 ExitLimit EL0 = computeExitLimitFromCondCached( 7206 Cache, L, BO->getOperand(0), ExitIfTrue, 7207 ControlsExit && !EitherMayExit, AllowPredicates); 7208 ExitLimit EL1 = computeExitLimitFromCondCached( 7209 Cache, L, BO->getOperand(1), ExitIfTrue, 7210 ControlsExit && !EitherMayExit, AllowPredicates); 7211 // Be robust against unsimplified IR for the form "or i1 X, true" 7212 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7213 return CI->isZero() ? EL0 : EL1; 7214 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7215 return CI->isZero() ? EL1 : EL0; 7216 const SCEV *BECount = getCouldNotCompute(); 7217 const SCEV *MaxBECount = getCouldNotCompute(); 7218 if (EitherMayExit) { 7219 // Both conditions must be false for the loop to continue executing. 7220 // Choose the less conservative count. 7221 if (EL0.ExactNotTaken == getCouldNotCompute() || 7222 EL1.ExactNotTaken == getCouldNotCompute()) 7223 BECount = getCouldNotCompute(); 7224 else 7225 BECount = 7226 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7227 if (EL0.MaxNotTaken == getCouldNotCompute()) 7228 MaxBECount = EL1.MaxNotTaken; 7229 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7230 MaxBECount = EL0.MaxNotTaken; 7231 else 7232 MaxBECount = 7233 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7234 } else { 7235 // Both conditions must be false at the same time for the loop to exit. 7236 // For now, be conservative. 7237 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7238 MaxBECount = EL0.MaxNotTaken; 7239 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7240 BECount = EL0.ExactNotTaken; 7241 } 7242 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7243 // to be more aggressive when computing BECount than when computing 7244 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7245 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7246 // to not. 7247 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7248 !isa<SCEVCouldNotCompute>(BECount)) 7249 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7250 7251 return ExitLimit(BECount, MaxBECount, false, 7252 {&EL0.Predicates, &EL1.Predicates}); 7253 } 7254 } 7255 7256 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7257 // Proceed to the next level to examine the icmp. 7258 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7259 ExitLimit EL = 7260 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7261 if (EL.hasFullInfo() || !AllowPredicates) 7262 return EL; 7263 7264 // Try again, but use SCEV predicates this time. 7265 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7266 /*AllowPredicates=*/true); 7267 } 7268 7269 // Check for a constant condition. These are normally stripped out by 7270 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7271 // preserve the CFG and is temporarily leaving constant conditions 7272 // in place. 7273 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7274 if (ExitIfTrue == !CI->getZExtValue()) 7275 // The backedge is always taken. 7276 return getCouldNotCompute(); 7277 else 7278 // The backedge is never taken. 7279 return getZero(CI->getType()); 7280 } 7281 7282 // If it's not an integer or pointer comparison then compute it the hard way. 7283 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7284 } 7285 7286 ScalarEvolution::ExitLimit 7287 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7288 ICmpInst *ExitCond, 7289 bool ExitIfTrue, 7290 bool ControlsExit, 7291 bool AllowPredicates) { 7292 // If the condition was exit on true, convert the condition to exit on false 7293 ICmpInst::Predicate Pred; 7294 if (!ExitIfTrue) 7295 Pred = ExitCond->getPredicate(); 7296 else 7297 Pred = ExitCond->getInversePredicate(); 7298 const ICmpInst::Predicate OriginalPred = Pred; 7299 7300 // Handle common loops like: for (X = "string"; *X; ++X) 7301 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7302 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7303 ExitLimit ItCnt = 7304 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7305 if (ItCnt.hasAnyInfo()) 7306 return ItCnt; 7307 } 7308 7309 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7310 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7311 7312 // Try to evaluate any dependencies out of the loop. 7313 LHS = getSCEVAtScope(LHS, L); 7314 RHS = getSCEVAtScope(RHS, L); 7315 7316 // At this point, we would like to compute how many iterations of the 7317 // loop the predicate will return true for these inputs. 7318 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7319 // If there is a loop-invariant, force it into the RHS. 7320 std::swap(LHS, RHS); 7321 Pred = ICmpInst::getSwappedPredicate(Pred); 7322 } 7323 7324 // Simplify the operands before analyzing them. 7325 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7326 7327 // If we have a comparison of a chrec against a constant, try to use value 7328 // ranges to answer this query. 7329 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7330 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7331 if (AddRec->getLoop() == L) { 7332 // Form the constant range. 7333 ConstantRange CompRange = 7334 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7335 7336 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7337 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7338 } 7339 7340 switch (Pred) { 7341 case ICmpInst::ICMP_NE: { // while (X != Y) 7342 // Convert to: while (X-Y != 0) 7343 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7344 AllowPredicates); 7345 if (EL.hasAnyInfo()) return EL; 7346 break; 7347 } 7348 case ICmpInst::ICMP_EQ: { // while (X == Y) 7349 // Convert to: while (X-Y == 0) 7350 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7351 if (EL.hasAnyInfo()) return EL; 7352 break; 7353 } 7354 case ICmpInst::ICMP_SLT: 7355 case ICmpInst::ICMP_ULT: { // while (X < Y) 7356 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7357 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7358 AllowPredicates); 7359 if (EL.hasAnyInfo()) return EL; 7360 break; 7361 } 7362 case ICmpInst::ICMP_SGT: 7363 case ICmpInst::ICMP_UGT: { // while (X > Y) 7364 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7365 ExitLimit EL = 7366 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7367 AllowPredicates); 7368 if (EL.hasAnyInfo()) return EL; 7369 break; 7370 } 7371 default: 7372 break; 7373 } 7374 7375 auto *ExhaustiveCount = 7376 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7377 7378 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7379 return ExhaustiveCount; 7380 7381 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7382 ExitCond->getOperand(1), L, OriginalPred); 7383 } 7384 7385 ScalarEvolution::ExitLimit 7386 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7387 SwitchInst *Switch, 7388 BasicBlock *ExitingBlock, 7389 bool ControlsExit) { 7390 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7391 7392 // Give up if the exit is the default dest of a switch. 7393 if (Switch->getDefaultDest() == ExitingBlock) 7394 return getCouldNotCompute(); 7395 7396 assert(L->contains(Switch->getDefaultDest()) && 7397 "Default case must not exit the loop!"); 7398 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7399 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7400 7401 // while (X != Y) --> while (X-Y != 0) 7402 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7403 if (EL.hasAnyInfo()) 7404 return EL; 7405 7406 return getCouldNotCompute(); 7407 } 7408 7409 static ConstantInt * 7410 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7411 ScalarEvolution &SE) { 7412 const SCEV *InVal = SE.getConstant(C); 7413 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7414 assert(isa<SCEVConstant>(Val) && 7415 "Evaluation of SCEV at constant didn't fold correctly?"); 7416 return cast<SCEVConstant>(Val)->getValue(); 7417 } 7418 7419 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7420 /// compute the backedge execution count. 7421 ScalarEvolution::ExitLimit 7422 ScalarEvolution::computeLoadConstantCompareExitLimit( 7423 LoadInst *LI, 7424 Constant *RHS, 7425 const Loop *L, 7426 ICmpInst::Predicate predicate) { 7427 if (LI->isVolatile()) return getCouldNotCompute(); 7428 7429 // Check to see if the loaded pointer is a getelementptr of a global. 7430 // TODO: Use SCEV instead of manually grubbing with GEPs. 7431 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7432 if (!GEP) return getCouldNotCompute(); 7433 7434 // Make sure that it is really a constant global we are gepping, with an 7435 // initializer, and make sure the first IDX is really 0. 7436 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7437 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7438 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7439 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7440 return getCouldNotCompute(); 7441 7442 // Okay, we allow one non-constant index into the GEP instruction. 7443 Value *VarIdx = nullptr; 7444 std::vector<Constant*> Indexes; 7445 unsigned VarIdxNum = 0; 7446 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7447 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7448 Indexes.push_back(CI); 7449 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7450 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7451 VarIdx = GEP->getOperand(i); 7452 VarIdxNum = i-2; 7453 Indexes.push_back(nullptr); 7454 } 7455 7456 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7457 if (!VarIdx) 7458 return getCouldNotCompute(); 7459 7460 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7461 // Check to see if X is a loop variant variable value now. 7462 const SCEV *Idx = getSCEV(VarIdx); 7463 Idx = getSCEVAtScope(Idx, L); 7464 7465 // We can only recognize very limited forms of loop index expressions, in 7466 // particular, only affine AddRec's like {C1,+,C2}. 7467 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7468 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7469 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7470 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7471 return getCouldNotCompute(); 7472 7473 unsigned MaxSteps = MaxBruteForceIterations; 7474 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7475 ConstantInt *ItCst = ConstantInt::get( 7476 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7477 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7478 7479 // Form the GEP offset. 7480 Indexes[VarIdxNum] = Val; 7481 7482 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7483 Indexes); 7484 if (!Result) break; // Cannot compute! 7485 7486 // Evaluate the condition for this iteration. 7487 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7488 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7489 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7490 ++NumArrayLenItCounts; 7491 return getConstant(ItCst); // Found terminating iteration! 7492 } 7493 } 7494 return getCouldNotCompute(); 7495 } 7496 7497 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7498 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7499 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7500 if (!RHS) 7501 return getCouldNotCompute(); 7502 7503 const BasicBlock *Latch = L->getLoopLatch(); 7504 if (!Latch) 7505 return getCouldNotCompute(); 7506 7507 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7508 if (!Predecessor) 7509 return getCouldNotCompute(); 7510 7511 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7512 // Return LHS in OutLHS and shift_opt in OutOpCode. 7513 auto MatchPositiveShift = 7514 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7515 7516 using namespace PatternMatch; 7517 7518 ConstantInt *ShiftAmt; 7519 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7520 OutOpCode = Instruction::LShr; 7521 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7522 OutOpCode = Instruction::AShr; 7523 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7524 OutOpCode = Instruction::Shl; 7525 else 7526 return false; 7527 7528 return ShiftAmt->getValue().isStrictlyPositive(); 7529 }; 7530 7531 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7532 // 7533 // loop: 7534 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7535 // %iv.shifted = lshr i32 %iv, <positive constant> 7536 // 7537 // Return true on a successful match. Return the corresponding PHI node (%iv 7538 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7539 auto MatchShiftRecurrence = 7540 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7541 Optional<Instruction::BinaryOps> PostShiftOpCode; 7542 7543 { 7544 Instruction::BinaryOps OpC; 7545 Value *V; 7546 7547 // If we encounter a shift instruction, "peel off" the shift operation, 7548 // and remember that we did so. Later when we inspect %iv's backedge 7549 // value, we will make sure that the backedge value uses the same 7550 // operation. 7551 // 7552 // Note: the peeled shift operation does not have to be the same 7553 // instruction as the one feeding into the PHI's backedge value. We only 7554 // really care about it being the same *kind* of shift instruction -- 7555 // that's all that is required for our later inferences to hold. 7556 if (MatchPositiveShift(LHS, V, OpC)) { 7557 PostShiftOpCode = OpC; 7558 LHS = V; 7559 } 7560 } 7561 7562 PNOut = dyn_cast<PHINode>(LHS); 7563 if (!PNOut || PNOut->getParent() != L->getHeader()) 7564 return false; 7565 7566 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7567 Value *OpLHS; 7568 7569 return 7570 // The backedge value for the PHI node must be a shift by a positive 7571 // amount 7572 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7573 7574 // of the PHI node itself 7575 OpLHS == PNOut && 7576 7577 // and the kind of shift should be match the kind of shift we peeled 7578 // off, if any. 7579 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7580 }; 7581 7582 PHINode *PN; 7583 Instruction::BinaryOps OpCode; 7584 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7585 return getCouldNotCompute(); 7586 7587 const DataLayout &DL = getDataLayout(); 7588 7589 // The key rationale for this optimization is that for some kinds of shift 7590 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7591 // within a finite number of iterations. If the condition guarding the 7592 // backedge (in the sense that the backedge is taken if the condition is true) 7593 // is false for the value the shift recurrence stabilizes to, then we know 7594 // that the backedge is taken only a finite number of times. 7595 7596 ConstantInt *StableValue = nullptr; 7597 switch (OpCode) { 7598 default: 7599 llvm_unreachable("Impossible case!"); 7600 7601 case Instruction::AShr: { 7602 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7603 // bitwidth(K) iterations. 7604 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7605 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7606 Predecessor->getTerminator(), &DT); 7607 auto *Ty = cast<IntegerType>(RHS->getType()); 7608 if (Known.isNonNegative()) 7609 StableValue = ConstantInt::get(Ty, 0); 7610 else if (Known.isNegative()) 7611 StableValue = ConstantInt::get(Ty, -1, true); 7612 else 7613 return getCouldNotCompute(); 7614 7615 break; 7616 } 7617 case Instruction::LShr: 7618 case Instruction::Shl: 7619 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7620 // stabilize to 0 in at most bitwidth(K) iterations. 7621 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7622 break; 7623 } 7624 7625 auto *Result = 7626 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7627 assert(Result->getType()->isIntegerTy(1) && 7628 "Otherwise cannot be an operand to a branch instruction"); 7629 7630 if (Result->isZeroValue()) { 7631 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7632 const SCEV *UpperBound = 7633 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7634 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7635 } 7636 7637 return getCouldNotCompute(); 7638 } 7639 7640 /// Return true if we can constant fold an instruction of the specified type, 7641 /// assuming that all operands were constants. 7642 static bool CanConstantFold(const Instruction *I) { 7643 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7644 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7645 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7646 return true; 7647 7648 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7649 if (const Function *F = CI->getCalledFunction()) 7650 return canConstantFoldCallTo(CI, F); 7651 return false; 7652 } 7653 7654 /// Determine whether this instruction can constant evolve within this loop 7655 /// assuming its operands can all constant evolve. 7656 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7657 // An instruction outside of the loop can't be derived from a loop PHI. 7658 if (!L->contains(I)) return false; 7659 7660 if (isa<PHINode>(I)) { 7661 // We don't currently keep track of the control flow needed to evaluate 7662 // PHIs, so we cannot handle PHIs inside of loops. 7663 return L->getHeader() == I->getParent(); 7664 } 7665 7666 // If we won't be able to constant fold this expression even if the operands 7667 // are constants, bail early. 7668 return CanConstantFold(I); 7669 } 7670 7671 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7672 /// recursing through each instruction operand until reaching a loop header phi. 7673 static PHINode * 7674 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7675 DenseMap<Instruction *, PHINode *> &PHIMap, 7676 unsigned Depth) { 7677 if (Depth > MaxConstantEvolvingDepth) 7678 return nullptr; 7679 7680 // Otherwise, we can evaluate this instruction if all of its operands are 7681 // constant or derived from a PHI node themselves. 7682 PHINode *PHI = nullptr; 7683 for (Value *Op : UseInst->operands()) { 7684 if (isa<Constant>(Op)) continue; 7685 7686 Instruction *OpInst = dyn_cast<Instruction>(Op); 7687 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7688 7689 PHINode *P = dyn_cast<PHINode>(OpInst); 7690 if (!P) 7691 // If this operand is already visited, reuse the prior result. 7692 // We may have P != PHI if this is the deepest point at which the 7693 // inconsistent paths meet. 7694 P = PHIMap.lookup(OpInst); 7695 if (!P) { 7696 // Recurse and memoize the results, whether a phi is found or not. 7697 // This recursive call invalidates pointers into PHIMap. 7698 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7699 PHIMap[OpInst] = P; 7700 } 7701 if (!P) 7702 return nullptr; // Not evolving from PHI 7703 if (PHI && PHI != P) 7704 return nullptr; // Evolving from multiple different PHIs. 7705 PHI = P; 7706 } 7707 // This is a expression evolving from a constant PHI! 7708 return PHI; 7709 } 7710 7711 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7712 /// in the loop that V is derived from. We allow arbitrary operations along the 7713 /// way, but the operands of an operation must either be constants or a value 7714 /// derived from a constant PHI. If this expression does not fit with these 7715 /// constraints, return null. 7716 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7717 Instruction *I = dyn_cast<Instruction>(V); 7718 if (!I || !canConstantEvolve(I, L)) return nullptr; 7719 7720 if (PHINode *PN = dyn_cast<PHINode>(I)) 7721 return PN; 7722 7723 // Record non-constant instructions contained by the loop. 7724 DenseMap<Instruction *, PHINode *> PHIMap; 7725 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7726 } 7727 7728 /// EvaluateExpression - Given an expression that passes the 7729 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7730 /// in the loop has the value PHIVal. If we can't fold this expression for some 7731 /// reason, return null. 7732 static Constant *EvaluateExpression(Value *V, const Loop *L, 7733 DenseMap<Instruction *, Constant *> &Vals, 7734 const DataLayout &DL, 7735 const TargetLibraryInfo *TLI) { 7736 // Convenient constant check, but redundant for recursive calls. 7737 if (Constant *C = dyn_cast<Constant>(V)) return C; 7738 Instruction *I = dyn_cast<Instruction>(V); 7739 if (!I) return nullptr; 7740 7741 if (Constant *C = Vals.lookup(I)) return C; 7742 7743 // An instruction inside the loop depends on a value outside the loop that we 7744 // weren't given a mapping for, or a value such as a call inside the loop. 7745 if (!canConstantEvolve(I, L)) return nullptr; 7746 7747 // An unmapped PHI can be due to a branch or another loop inside this loop, 7748 // or due to this not being the initial iteration through a loop where we 7749 // couldn't compute the evolution of this particular PHI last time. 7750 if (isa<PHINode>(I)) return nullptr; 7751 7752 std::vector<Constant*> Operands(I->getNumOperands()); 7753 7754 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7755 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7756 if (!Operand) { 7757 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7758 if (!Operands[i]) return nullptr; 7759 continue; 7760 } 7761 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7762 Vals[Operand] = C; 7763 if (!C) return nullptr; 7764 Operands[i] = C; 7765 } 7766 7767 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7768 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7769 Operands[1], DL, TLI); 7770 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7771 if (!LI->isVolatile()) 7772 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7773 } 7774 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7775 } 7776 7777 7778 // If every incoming value to PN except the one for BB is a specific Constant, 7779 // return that, else return nullptr. 7780 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7781 Constant *IncomingVal = nullptr; 7782 7783 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7784 if (PN->getIncomingBlock(i) == BB) 7785 continue; 7786 7787 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7788 if (!CurrentVal) 7789 return nullptr; 7790 7791 if (IncomingVal != CurrentVal) { 7792 if (IncomingVal) 7793 return nullptr; 7794 IncomingVal = CurrentVal; 7795 } 7796 } 7797 7798 return IncomingVal; 7799 } 7800 7801 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7802 /// in the header of its containing loop, we know the loop executes a 7803 /// constant number of times, and the PHI node is just a recurrence 7804 /// involving constants, fold it. 7805 Constant * 7806 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7807 const APInt &BEs, 7808 const Loop *L) { 7809 auto I = ConstantEvolutionLoopExitValue.find(PN); 7810 if (I != ConstantEvolutionLoopExitValue.end()) 7811 return I->second; 7812 7813 if (BEs.ugt(MaxBruteForceIterations)) 7814 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7815 7816 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7817 7818 DenseMap<Instruction *, Constant *> CurrentIterVals; 7819 BasicBlock *Header = L->getHeader(); 7820 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7821 7822 BasicBlock *Latch = L->getLoopLatch(); 7823 if (!Latch) 7824 return nullptr; 7825 7826 for (PHINode &PHI : Header->phis()) { 7827 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7828 CurrentIterVals[&PHI] = StartCST; 7829 } 7830 if (!CurrentIterVals.count(PN)) 7831 return RetVal = nullptr; 7832 7833 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7834 7835 // Execute the loop symbolically to determine the exit value. 7836 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7837 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7838 7839 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7840 unsigned IterationNum = 0; 7841 const DataLayout &DL = getDataLayout(); 7842 for (; ; ++IterationNum) { 7843 if (IterationNum == NumIterations) 7844 return RetVal = CurrentIterVals[PN]; // Got exit value! 7845 7846 // Compute the value of the PHIs for the next iteration. 7847 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7848 DenseMap<Instruction *, Constant *> NextIterVals; 7849 Constant *NextPHI = 7850 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7851 if (!NextPHI) 7852 return nullptr; // Couldn't evaluate! 7853 NextIterVals[PN] = NextPHI; 7854 7855 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7856 7857 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7858 // cease to be able to evaluate one of them or if they stop evolving, 7859 // because that doesn't necessarily prevent us from computing PN. 7860 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7861 for (const auto &I : CurrentIterVals) { 7862 PHINode *PHI = dyn_cast<PHINode>(I.first); 7863 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7864 PHIsToCompute.emplace_back(PHI, I.second); 7865 } 7866 // We use two distinct loops because EvaluateExpression may invalidate any 7867 // iterators into CurrentIterVals. 7868 for (const auto &I : PHIsToCompute) { 7869 PHINode *PHI = I.first; 7870 Constant *&NextPHI = NextIterVals[PHI]; 7871 if (!NextPHI) { // Not already computed. 7872 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7873 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7874 } 7875 if (NextPHI != I.second) 7876 StoppedEvolving = false; 7877 } 7878 7879 // If all entries in CurrentIterVals == NextIterVals then we can stop 7880 // iterating, the loop can't continue to change. 7881 if (StoppedEvolving) 7882 return RetVal = CurrentIterVals[PN]; 7883 7884 CurrentIterVals.swap(NextIterVals); 7885 } 7886 } 7887 7888 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7889 Value *Cond, 7890 bool ExitWhen) { 7891 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7892 if (!PN) return getCouldNotCompute(); 7893 7894 // If the loop is canonicalized, the PHI will have exactly two entries. 7895 // That's the only form we support here. 7896 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7897 7898 DenseMap<Instruction *, Constant *> CurrentIterVals; 7899 BasicBlock *Header = L->getHeader(); 7900 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7901 7902 BasicBlock *Latch = L->getLoopLatch(); 7903 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7904 7905 for (PHINode &PHI : Header->phis()) { 7906 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7907 CurrentIterVals[&PHI] = StartCST; 7908 } 7909 if (!CurrentIterVals.count(PN)) 7910 return getCouldNotCompute(); 7911 7912 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7913 // the loop symbolically to determine when the condition gets a value of 7914 // "ExitWhen". 7915 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7916 const DataLayout &DL = getDataLayout(); 7917 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7918 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7919 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7920 7921 // Couldn't symbolically evaluate. 7922 if (!CondVal) return getCouldNotCompute(); 7923 7924 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7925 ++NumBruteForceTripCountsComputed; 7926 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7927 } 7928 7929 // Update all the PHI nodes for the next iteration. 7930 DenseMap<Instruction *, Constant *> NextIterVals; 7931 7932 // Create a list of which PHIs we need to compute. We want to do this before 7933 // calling EvaluateExpression on them because that may invalidate iterators 7934 // into CurrentIterVals. 7935 SmallVector<PHINode *, 8> PHIsToCompute; 7936 for (const auto &I : CurrentIterVals) { 7937 PHINode *PHI = dyn_cast<PHINode>(I.first); 7938 if (!PHI || PHI->getParent() != Header) continue; 7939 PHIsToCompute.push_back(PHI); 7940 } 7941 for (PHINode *PHI : PHIsToCompute) { 7942 Constant *&NextPHI = NextIterVals[PHI]; 7943 if (NextPHI) continue; // Already computed! 7944 7945 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7946 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7947 } 7948 CurrentIterVals.swap(NextIterVals); 7949 } 7950 7951 // Too many iterations were needed to evaluate. 7952 return getCouldNotCompute(); 7953 } 7954 7955 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7956 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7957 ValuesAtScopes[V]; 7958 // Check to see if we've folded this expression at this loop before. 7959 for (auto &LS : Values) 7960 if (LS.first == L) 7961 return LS.second ? LS.second : V; 7962 7963 Values.emplace_back(L, nullptr); 7964 7965 // Otherwise compute it. 7966 const SCEV *C = computeSCEVAtScope(V, L); 7967 for (auto &LS : reverse(ValuesAtScopes[V])) 7968 if (LS.first == L) { 7969 LS.second = C; 7970 break; 7971 } 7972 return C; 7973 } 7974 7975 /// This builds up a Constant using the ConstantExpr interface. That way, we 7976 /// will return Constants for objects which aren't represented by a 7977 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7978 /// Returns NULL if the SCEV isn't representable as a Constant. 7979 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7980 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7981 case scCouldNotCompute: 7982 case scAddRecExpr: 7983 break; 7984 case scConstant: 7985 return cast<SCEVConstant>(V)->getValue(); 7986 case scUnknown: 7987 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7988 case scSignExtend: { 7989 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7990 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7991 return ConstantExpr::getSExt(CastOp, SS->getType()); 7992 break; 7993 } 7994 case scZeroExtend: { 7995 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7996 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7997 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7998 break; 7999 } 8000 case scTruncate: { 8001 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8002 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) { 8003 if (!CastOp->getType()->isPointerTy()) 8004 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8005 return ConstantExpr::getPtrToInt(CastOp, ST->getType()); 8006 } 8007 break; 8008 } 8009 case scAddExpr: { 8010 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8011 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8012 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8013 unsigned AS = PTy->getAddressSpace(); 8014 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8015 C = ConstantExpr::getBitCast(C, DestPtrTy); 8016 } 8017 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8018 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8019 if (!C2) return nullptr; 8020 8021 // First pointer! 8022 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8023 unsigned AS = C2->getType()->getPointerAddressSpace(); 8024 std::swap(C, C2); 8025 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8026 // The offsets have been converted to bytes. We can add bytes to an 8027 // i8* by GEP with the byte count in the first index. 8028 C = ConstantExpr::getBitCast(C, DestPtrTy); 8029 } 8030 8031 // Don't bother trying to sum two pointers. We probably can't 8032 // statically compute a load that results from it anyway. 8033 if (C2->getType()->isPointerTy()) 8034 return nullptr; 8035 8036 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8037 if (PTy->getElementType()->isStructTy()) 8038 C2 = ConstantExpr::getIntegerCast( 8039 C2, Type::getInt32Ty(C->getContext()), true); 8040 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8041 } else 8042 C = ConstantExpr::getAdd(C, C2); 8043 } 8044 return C; 8045 } 8046 break; 8047 } 8048 case scMulExpr: { 8049 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8050 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8051 // Don't bother with pointers at all. 8052 if (C->getType()->isPointerTy()) return nullptr; 8053 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8054 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8055 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8056 C = ConstantExpr::getMul(C, C2); 8057 } 8058 return C; 8059 } 8060 break; 8061 } 8062 case scUDivExpr: { 8063 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8064 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8065 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8066 if (LHS->getType() == RHS->getType()) 8067 return ConstantExpr::getUDiv(LHS, RHS); 8068 break; 8069 } 8070 case scSMaxExpr: 8071 case scUMaxExpr: 8072 case scSMinExpr: 8073 case scUMinExpr: 8074 break; // TODO: smax, umax, smin, umax. 8075 } 8076 return nullptr; 8077 } 8078 8079 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8080 if (isa<SCEVConstant>(V)) return V; 8081 8082 // If this instruction is evolved from a constant-evolving PHI, compute the 8083 // exit value from the loop without using SCEVs. 8084 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8085 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8086 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8087 const Loop *CurrLoop = this->LI[I->getParent()]; 8088 // Looking for loop exit value. 8089 if (CurrLoop && CurrLoop->getParentLoop() == L && 8090 PN->getParent() == CurrLoop->getHeader()) { 8091 // Okay, there is no closed form solution for the PHI node. Check 8092 // to see if the loop that contains it has a known backedge-taken 8093 // count. If so, we may be able to force computation of the exit 8094 // value. 8095 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8096 // This trivial case can show up in some degenerate cases where 8097 // the incoming IR has not yet been fully simplified. 8098 if (BackedgeTakenCount->isZero()) { 8099 Value *InitValue = nullptr; 8100 bool MultipleInitValues = false; 8101 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8102 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8103 if (!InitValue) 8104 InitValue = PN->getIncomingValue(i); 8105 else if (InitValue != PN->getIncomingValue(i)) { 8106 MultipleInitValues = true; 8107 break; 8108 } 8109 } 8110 } 8111 if (!MultipleInitValues && InitValue) 8112 return getSCEV(InitValue); 8113 } 8114 // Do we have a loop invariant value flowing around the backedge 8115 // for a loop which must execute the backedge? 8116 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8117 isKnownPositive(BackedgeTakenCount) && 8118 PN->getNumIncomingValues() == 2) { 8119 8120 unsigned InLoopPred = 8121 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8122 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8123 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8124 return getSCEV(BackedgeVal); 8125 } 8126 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8127 // Okay, we know how many times the containing loop executes. If 8128 // this is a constant evolving PHI node, get the final value at 8129 // the specified iteration number. 8130 Constant *RV = getConstantEvolutionLoopExitValue( 8131 PN, BTCC->getAPInt(), CurrLoop); 8132 if (RV) return getSCEV(RV); 8133 } 8134 } 8135 8136 // If there is a single-input Phi, evaluate it at our scope. If we can 8137 // prove that this replacement does not break LCSSA form, use new value. 8138 if (PN->getNumOperands() == 1) { 8139 const SCEV *Input = getSCEV(PN->getOperand(0)); 8140 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8141 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8142 // for the simplest case just support constants. 8143 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8144 } 8145 } 8146 8147 // Okay, this is an expression that we cannot symbolically evaluate 8148 // into a SCEV. Check to see if it's possible to symbolically evaluate 8149 // the arguments into constants, and if so, try to constant propagate the 8150 // result. This is particularly useful for computing loop exit values. 8151 if (CanConstantFold(I)) { 8152 SmallVector<Constant *, 4> Operands; 8153 bool MadeImprovement = false; 8154 for (Value *Op : I->operands()) { 8155 if (Constant *C = dyn_cast<Constant>(Op)) { 8156 Operands.push_back(C); 8157 continue; 8158 } 8159 8160 // If any of the operands is non-constant and if they are 8161 // non-integer and non-pointer, don't even try to analyze them 8162 // with scev techniques. 8163 if (!isSCEVable(Op->getType())) 8164 return V; 8165 8166 const SCEV *OrigV = getSCEV(Op); 8167 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8168 MadeImprovement |= OrigV != OpV; 8169 8170 Constant *C = BuildConstantFromSCEV(OpV); 8171 if (!C) return V; 8172 if (C->getType() != Op->getType()) 8173 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8174 Op->getType(), 8175 false), 8176 C, Op->getType()); 8177 Operands.push_back(C); 8178 } 8179 8180 // Check to see if getSCEVAtScope actually made an improvement. 8181 if (MadeImprovement) { 8182 Constant *C = nullptr; 8183 const DataLayout &DL = getDataLayout(); 8184 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8185 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8186 Operands[1], DL, &TLI); 8187 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8188 if (!Load->isVolatile()) 8189 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8190 DL); 8191 } else 8192 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8193 if (!C) return V; 8194 return getSCEV(C); 8195 } 8196 } 8197 } 8198 8199 // This is some other type of SCEVUnknown, just return it. 8200 return V; 8201 } 8202 8203 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8204 // Avoid performing the look-up in the common case where the specified 8205 // expression has no loop-variant portions. 8206 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8207 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8208 if (OpAtScope != Comm->getOperand(i)) { 8209 // Okay, at least one of these operands is loop variant but might be 8210 // foldable. Build a new instance of the folded commutative expression. 8211 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8212 Comm->op_begin()+i); 8213 NewOps.push_back(OpAtScope); 8214 8215 for (++i; i != e; ++i) { 8216 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8217 NewOps.push_back(OpAtScope); 8218 } 8219 if (isa<SCEVAddExpr>(Comm)) 8220 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8221 if (isa<SCEVMulExpr>(Comm)) 8222 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8223 if (isa<SCEVMinMaxExpr>(Comm)) 8224 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8225 llvm_unreachable("Unknown commutative SCEV type!"); 8226 } 8227 } 8228 // If we got here, all operands are loop invariant. 8229 return Comm; 8230 } 8231 8232 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8233 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8234 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8235 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8236 return Div; // must be loop invariant 8237 return getUDivExpr(LHS, RHS); 8238 } 8239 8240 // If this is a loop recurrence for a loop that does not contain L, then we 8241 // are dealing with the final value computed by the loop. 8242 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8243 // First, attempt to evaluate each operand. 8244 // Avoid performing the look-up in the common case where the specified 8245 // expression has no loop-variant portions. 8246 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8247 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8248 if (OpAtScope == AddRec->getOperand(i)) 8249 continue; 8250 8251 // Okay, at least one of these operands is loop variant but might be 8252 // foldable. Build a new instance of the folded commutative expression. 8253 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8254 AddRec->op_begin()+i); 8255 NewOps.push_back(OpAtScope); 8256 for (++i; i != e; ++i) 8257 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8258 8259 const SCEV *FoldedRec = 8260 getAddRecExpr(NewOps, AddRec->getLoop(), 8261 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8262 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8263 // The addrec may be folded to a nonrecurrence, for example, if the 8264 // induction variable is multiplied by zero after constant folding. Go 8265 // ahead and return the folded value. 8266 if (!AddRec) 8267 return FoldedRec; 8268 break; 8269 } 8270 8271 // If the scope is outside the addrec's loop, evaluate it by using the 8272 // loop exit value of the addrec. 8273 if (!AddRec->getLoop()->contains(L)) { 8274 // To evaluate this recurrence, we need to know how many times the AddRec 8275 // loop iterates. Compute this now. 8276 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8277 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8278 8279 // Then, evaluate the AddRec. 8280 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8281 } 8282 8283 return AddRec; 8284 } 8285 8286 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8287 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8288 if (Op == Cast->getOperand()) 8289 return Cast; // must be loop invariant 8290 return getZeroExtendExpr(Op, Cast->getType()); 8291 } 8292 8293 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8294 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8295 if (Op == Cast->getOperand()) 8296 return Cast; // must be loop invariant 8297 return getSignExtendExpr(Op, Cast->getType()); 8298 } 8299 8300 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8301 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8302 if (Op == Cast->getOperand()) 8303 return Cast; // must be loop invariant 8304 return getTruncateExpr(Op, Cast->getType()); 8305 } 8306 8307 llvm_unreachable("Unknown SCEV type!"); 8308 } 8309 8310 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8311 return getSCEVAtScope(getSCEV(V), L); 8312 } 8313 8314 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8315 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8316 return stripInjectiveFunctions(ZExt->getOperand()); 8317 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8318 return stripInjectiveFunctions(SExt->getOperand()); 8319 return S; 8320 } 8321 8322 /// Finds the minimum unsigned root of the following equation: 8323 /// 8324 /// A * X = B (mod N) 8325 /// 8326 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8327 /// A and B isn't important. 8328 /// 8329 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8330 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8331 ScalarEvolution &SE) { 8332 uint32_t BW = A.getBitWidth(); 8333 assert(BW == SE.getTypeSizeInBits(B->getType())); 8334 assert(A != 0 && "A must be non-zero."); 8335 8336 // 1. D = gcd(A, N) 8337 // 8338 // The gcd of A and N may have only one prime factor: 2. The number of 8339 // trailing zeros in A is its multiplicity 8340 uint32_t Mult2 = A.countTrailingZeros(); 8341 // D = 2^Mult2 8342 8343 // 2. Check if B is divisible by D. 8344 // 8345 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8346 // is not less than multiplicity of this prime factor for D. 8347 if (SE.GetMinTrailingZeros(B) < Mult2) 8348 return SE.getCouldNotCompute(); 8349 8350 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8351 // modulo (N / D). 8352 // 8353 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8354 // (N / D) in general. The inverse itself always fits into BW bits, though, 8355 // so we immediately truncate it. 8356 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8357 APInt Mod(BW + 1, 0); 8358 Mod.setBit(BW - Mult2); // Mod = N / D 8359 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8360 8361 // 4. Compute the minimum unsigned root of the equation: 8362 // I * (B / D) mod (N / D) 8363 // To simplify the computation, we factor out the divide by D: 8364 // (I * B mod N) / D 8365 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8366 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8367 } 8368 8369 /// For a given quadratic addrec, generate coefficients of the corresponding 8370 /// quadratic equation, multiplied by a common value to ensure that they are 8371 /// integers. 8372 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8373 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8374 /// were multiplied by, and BitWidth is the bit width of the original addrec 8375 /// coefficients. 8376 /// This function returns None if the addrec coefficients are not compile- 8377 /// time constants. 8378 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8379 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8380 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8381 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8382 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8383 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8384 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8385 << *AddRec << '\n'); 8386 8387 // We currently can only solve this if the coefficients are constants. 8388 if (!LC || !MC || !NC) { 8389 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8390 return None; 8391 } 8392 8393 APInt L = LC->getAPInt(); 8394 APInt M = MC->getAPInt(); 8395 APInt N = NC->getAPInt(); 8396 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8397 8398 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8399 unsigned NewWidth = BitWidth + 1; 8400 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8401 << BitWidth << '\n'); 8402 // The sign-extension (as opposed to a zero-extension) here matches the 8403 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8404 N = N.sext(NewWidth); 8405 M = M.sext(NewWidth); 8406 L = L.sext(NewWidth); 8407 8408 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8409 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8410 // L+M, L+2M+N, L+3M+3N, ... 8411 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8412 // 8413 // The equation Acc = 0 is then 8414 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8415 // In a quadratic form it becomes: 8416 // N n^2 + (2M-N) n + 2L = 0. 8417 8418 APInt A = N; 8419 APInt B = 2 * M - A; 8420 APInt C = 2 * L; 8421 APInt T = APInt(NewWidth, 2); 8422 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8423 << "x + " << C << ", coeff bw: " << NewWidth 8424 << ", multiplied by " << T << '\n'); 8425 return std::make_tuple(A, B, C, T, BitWidth); 8426 } 8427 8428 /// Helper function to compare optional APInts: 8429 /// (a) if X and Y both exist, return min(X, Y), 8430 /// (b) if neither X nor Y exist, return None, 8431 /// (c) if exactly one of X and Y exists, return that value. 8432 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8433 if (X.hasValue() && Y.hasValue()) { 8434 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8435 APInt XW = X->sextOrSelf(W); 8436 APInt YW = Y->sextOrSelf(W); 8437 return XW.slt(YW) ? *X : *Y; 8438 } 8439 if (!X.hasValue() && !Y.hasValue()) 8440 return None; 8441 return X.hasValue() ? *X : *Y; 8442 } 8443 8444 /// Helper function to truncate an optional APInt to a given BitWidth. 8445 /// When solving addrec-related equations, it is preferable to return a value 8446 /// that has the same bit width as the original addrec's coefficients. If the 8447 /// solution fits in the original bit width, truncate it (except for i1). 8448 /// Returning a value of a different bit width may inhibit some optimizations. 8449 /// 8450 /// In general, a solution to a quadratic equation generated from an addrec 8451 /// may require BW+1 bits, where BW is the bit width of the addrec's 8452 /// coefficients. The reason is that the coefficients of the quadratic 8453 /// equation are BW+1 bits wide (to avoid truncation when converting from 8454 /// the addrec to the equation). 8455 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8456 if (!X.hasValue()) 8457 return None; 8458 unsigned W = X->getBitWidth(); 8459 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8460 return X->trunc(BitWidth); 8461 return X; 8462 } 8463 8464 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8465 /// iterations. The values L, M, N are assumed to be signed, and they 8466 /// should all have the same bit widths. 8467 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8468 /// where BW is the bit width of the addrec's coefficients. 8469 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8470 /// returned as such, otherwise the bit width of the returned value may 8471 /// be greater than BW. 8472 /// 8473 /// This function returns None if 8474 /// (a) the addrec coefficients are not constant, or 8475 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8476 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8477 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8478 static Optional<APInt> 8479 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8480 APInt A, B, C, M; 8481 unsigned BitWidth; 8482 auto T = GetQuadraticEquation(AddRec); 8483 if (!T.hasValue()) 8484 return None; 8485 8486 std::tie(A, B, C, M, BitWidth) = *T; 8487 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8488 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8489 if (!X.hasValue()) 8490 return None; 8491 8492 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8493 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8494 if (!V->isZero()) 8495 return None; 8496 8497 return TruncIfPossible(X, BitWidth); 8498 } 8499 8500 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8501 /// iterations. The values M, N are assumed to be signed, and they 8502 /// should all have the same bit widths. 8503 /// Find the least n such that c(n) does not belong to the given range, 8504 /// while c(n-1) does. 8505 /// 8506 /// This function returns None if 8507 /// (a) the addrec coefficients are not constant, or 8508 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8509 /// bounds of the range. 8510 static Optional<APInt> 8511 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8512 const ConstantRange &Range, ScalarEvolution &SE) { 8513 assert(AddRec->getOperand(0)->isZero() && 8514 "Starting value of addrec should be 0"); 8515 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8516 << Range << ", addrec " << *AddRec << '\n'); 8517 // This case is handled in getNumIterationsInRange. Here we can assume that 8518 // we start in the range. 8519 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8520 "Addrec's initial value should be in range"); 8521 8522 APInt A, B, C, M; 8523 unsigned BitWidth; 8524 auto T = GetQuadraticEquation(AddRec); 8525 if (!T.hasValue()) 8526 return None; 8527 8528 // Be careful about the return value: there can be two reasons for not 8529 // returning an actual number. First, if no solutions to the equations 8530 // were found, and second, if the solutions don't leave the given range. 8531 // The first case means that the actual solution is "unknown", the second 8532 // means that it's known, but not valid. If the solution is unknown, we 8533 // cannot make any conclusions. 8534 // Return a pair: the optional solution and a flag indicating if the 8535 // solution was found. 8536 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8537 // Solve for signed overflow and unsigned overflow, pick the lower 8538 // solution. 8539 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8540 << Bound << " (before multiplying by " << M << ")\n"); 8541 Bound *= M; // The quadratic equation multiplier. 8542 8543 Optional<APInt> SO = None; 8544 if (BitWidth > 1) { 8545 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8546 "signed overflow\n"); 8547 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8548 } 8549 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8550 "unsigned overflow\n"); 8551 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8552 BitWidth+1); 8553 8554 auto LeavesRange = [&] (const APInt &X) { 8555 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8556 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8557 if (Range.contains(V0->getValue())) 8558 return false; 8559 // X should be at least 1, so X-1 is non-negative. 8560 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8561 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8562 if (Range.contains(V1->getValue())) 8563 return true; 8564 return false; 8565 }; 8566 8567 // If SolveQuadraticEquationWrap returns None, it means that there can 8568 // be a solution, but the function failed to find it. We cannot treat it 8569 // as "no solution". 8570 if (!SO.hasValue() || !UO.hasValue()) 8571 return { None, false }; 8572 8573 // Check the smaller value first to see if it leaves the range. 8574 // At this point, both SO and UO must have values. 8575 Optional<APInt> Min = MinOptional(SO, UO); 8576 if (LeavesRange(*Min)) 8577 return { Min, true }; 8578 Optional<APInt> Max = Min == SO ? UO : SO; 8579 if (LeavesRange(*Max)) 8580 return { Max, true }; 8581 8582 // Solutions were found, but were eliminated, hence the "true". 8583 return { None, true }; 8584 }; 8585 8586 std::tie(A, B, C, M, BitWidth) = *T; 8587 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8588 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8589 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8590 auto SL = SolveForBoundary(Lower); 8591 auto SU = SolveForBoundary(Upper); 8592 // If any of the solutions was unknown, no meaninigful conclusions can 8593 // be made. 8594 if (!SL.second || !SU.second) 8595 return None; 8596 8597 // Claim: The correct solution is not some value between Min and Max. 8598 // 8599 // Justification: Assuming that Min and Max are different values, one of 8600 // them is when the first signed overflow happens, the other is when the 8601 // first unsigned overflow happens. Crossing the range boundary is only 8602 // possible via an overflow (treating 0 as a special case of it, modeling 8603 // an overflow as crossing k*2^W for some k). 8604 // 8605 // The interesting case here is when Min was eliminated as an invalid 8606 // solution, but Max was not. The argument is that if there was another 8607 // overflow between Min and Max, it would also have been eliminated if 8608 // it was considered. 8609 // 8610 // For a given boundary, it is possible to have two overflows of the same 8611 // type (signed/unsigned) without having the other type in between: this 8612 // can happen when the vertex of the parabola is between the iterations 8613 // corresponding to the overflows. This is only possible when the two 8614 // overflows cross k*2^W for the same k. In such case, if the second one 8615 // left the range (and was the first one to do so), the first overflow 8616 // would have to enter the range, which would mean that either we had left 8617 // the range before or that we started outside of it. Both of these cases 8618 // are contradictions. 8619 // 8620 // Claim: In the case where SolveForBoundary returns None, the correct 8621 // solution is not some value between the Max for this boundary and the 8622 // Min of the other boundary. 8623 // 8624 // Justification: Assume that we had such Max_A and Min_B corresponding 8625 // to range boundaries A and B and such that Max_A < Min_B. If there was 8626 // a solution between Max_A and Min_B, it would have to be caused by an 8627 // overflow corresponding to either A or B. It cannot correspond to B, 8628 // since Min_B is the first occurrence of such an overflow. If it 8629 // corresponded to A, it would have to be either a signed or an unsigned 8630 // overflow that is larger than both eliminated overflows for A. But 8631 // between the eliminated overflows and this overflow, the values would 8632 // cover the entire value space, thus crossing the other boundary, which 8633 // is a contradiction. 8634 8635 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8636 } 8637 8638 ScalarEvolution::ExitLimit 8639 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8640 bool AllowPredicates) { 8641 8642 // This is only used for loops with a "x != y" exit test. The exit condition 8643 // is now expressed as a single expression, V = x-y. So the exit test is 8644 // effectively V != 0. We know and take advantage of the fact that this 8645 // expression only being used in a comparison by zero context. 8646 8647 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8648 // If the value is a constant 8649 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8650 // If the value is already zero, the branch will execute zero times. 8651 if (C->getValue()->isZero()) return C; 8652 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8653 } 8654 8655 const SCEVAddRecExpr *AddRec = 8656 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8657 8658 if (!AddRec && AllowPredicates) 8659 // Try to make this an AddRec using runtime tests, in the first X 8660 // iterations of this loop, where X is the SCEV expression found by the 8661 // algorithm below. 8662 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8663 8664 if (!AddRec || AddRec->getLoop() != L) 8665 return getCouldNotCompute(); 8666 8667 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8668 // the quadratic equation to solve it. 8669 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8670 // We can only use this value if the chrec ends up with an exact zero 8671 // value at this index. When solving for "X*X != 5", for example, we 8672 // should not accept a root of 2. 8673 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8674 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8675 return ExitLimit(R, R, false, Predicates); 8676 } 8677 return getCouldNotCompute(); 8678 } 8679 8680 // Otherwise we can only handle this if it is affine. 8681 if (!AddRec->isAffine()) 8682 return getCouldNotCompute(); 8683 8684 // If this is an affine expression, the execution count of this branch is 8685 // the minimum unsigned root of the following equation: 8686 // 8687 // Start + Step*N = 0 (mod 2^BW) 8688 // 8689 // equivalent to: 8690 // 8691 // Step*N = -Start (mod 2^BW) 8692 // 8693 // where BW is the common bit width of Start and Step. 8694 8695 // Get the initial value for the loop. 8696 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8697 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8698 8699 // For now we handle only constant steps. 8700 // 8701 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8702 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8703 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8704 // We have not yet seen any such cases. 8705 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8706 if (!StepC || StepC->getValue()->isZero()) 8707 return getCouldNotCompute(); 8708 8709 // For positive steps (counting up until unsigned overflow): 8710 // N = -Start/Step (as unsigned) 8711 // For negative steps (counting down to zero): 8712 // N = Start/-Step 8713 // First compute the unsigned distance from zero in the direction of Step. 8714 bool CountDown = StepC->getAPInt().isNegative(); 8715 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8716 8717 // Handle unitary steps, which cannot wraparound. 8718 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8719 // N = Distance (as unsigned) 8720 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8721 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 8722 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 8723 if (MaxBECountBase.ult(MaxBECount)) 8724 MaxBECount = MaxBECountBase; 8725 8726 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8727 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8728 // case, and see if we can improve the bound. 8729 // 8730 // Explicitly handling this here is necessary because getUnsignedRange 8731 // isn't context-sensitive; it doesn't know that we only care about the 8732 // range inside the loop. 8733 const SCEV *Zero = getZero(Distance->getType()); 8734 const SCEV *One = getOne(Distance->getType()); 8735 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8736 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8737 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8738 // as "unsigned_max(Distance + 1) - 1". 8739 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8740 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8741 } 8742 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8743 } 8744 8745 // If the condition controls loop exit (the loop exits only if the expression 8746 // is true) and the addition is no-wrap we can use unsigned divide to 8747 // compute the backedge count. In this case, the step may not divide the 8748 // distance, but we don't care because if the condition is "missed" the loop 8749 // will have undefined behavior due to wrapping. 8750 if (ControlsExit && AddRec->hasNoSelfWrap() && 8751 loopHasNoAbnormalExits(AddRec->getLoop())) { 8752 const SCEV *Exact = 8753 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8754 const SCEV *Max = 8755 Exact == getCouldNotCompute() 8756 ? Exact 8757 : getConstant(getUnsignedRangeMax(Exact)); 8758 return ExitLimit(Exact, Max, false, Predicates); 8759 } 8760 8761 // Solve the general equation. 8762 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8763 getNegativeSCEV(Start), *this); 8764 const SCEV *M = E == getCouldNotCompute() 8765 ? E 8766 : getConstant(getUnsignedRangeMax(E)); 8767 return ExitLimit(E, M, false, Predicates); 8768 } 8769 8770 ScalarEvolution::ExitLimit 8771 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8772 // Loops that look like: while (X == 0) are very strange indeed. We don't 8773 // handle them yet except for the trivial case. This could be expanded in the 8774 // future as needed. 8775 8776 // If the value is a constant, check to see if it is known to be non-zero 8777 // already. If so, the backedge will execute zero times. 8778 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8779 if (!C->getValue()->isZero()) 8780 return getZero(C->getType()); 8781 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8782 } 8783 8784 // We could implement others, but I really doubt anyone writes loops like 8785 // this, and if they did, they would already be constant folded. 8786 return getCouldNotCompute(); 8787 } 8788 8789 std::pair<const BasicBlock *, const BasicBlock *> 8790 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 8791 const { 8792 // If the block has a unique predecessor, then there is no path from the 8793 // predecessor to the block that does not go through the direct edge 8794 // from the predecessor to the block. 8795 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 8796 return {Pred, BB}; 8797 8798 // A loop's header is defined to be a block that dominates the loop. 8799 // If the header has a unique predecessor outside the loop, it must be 8800 // a block that has exactly one successor that can reach the loop. 8801 if (const Loop *L = LI.getLoopFor(BB)) 8802 return {L->getLoopPredecessor(), L->getHeader()}; 8803 8804 return {nullptr, nullptr}; 8805 } 8806 8807 /// SCEV structural equivalence is usually sufficient for testing whether two 8808 /// expressions are equal, however for the purposes of looking for a condition 8809 /// guarding a loop, it can be useful to be a little more general, since a 8810 /// front-end may have replicated the controlling expression. 8811 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8812 // Quick check to see if they are the same SCEV. 8813 if (A == B) return true; 8814 8815 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8816 // Not all instructions that are "identical" compute the same value. For 8817 // instance, two distinct alloca instructions allocating the same type are 8818 // identical and do not read memory; but compute distinct values. 8819 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8820 }; 8821 8822 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8823 // two different instructions with the same value. Check for this case. 8824 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8825 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8826 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8827 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8828 if (ComputesEqualValues(AI, BI)) 8829 return true; 8830 8831 // Otherwise assume they may have a different value. 8832 return false; 8833 } 8834 8835 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8836 const SCEV *&LHS, const SCEV *&RHS, 8837 unsigned Depth) { 8838 bool Changed = false; 8839 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8840 // '0 != 0'. 8841 auto TrivialCase = [&](bool TriviallyTrue) { 8842 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8843 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8844 return true; 8845 }; 8846 // If we hit the max recursion limit bail out. 8847 if (Depth >= 3) 8848 return false; 8849 8850 // Canonicalize a constant to the right side. 8851 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8852 // Check for both operands constant. 8853 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8854 if (ConstantExpr::getICmp(Pred, 8855 LHSC->getValue(), 8856 RHSC->getValue())->isNullValue()) 8857 return TrivialCase(false); 8858 else 8859 return TrivialCase(true); 8860 } 8861 // Otherwise swap the operands to put the constant on the right. 8862 std::swap(LHS, RHS); 8863 Pred = ICmpInst::getSwappedPredicate(Pred); 8864 Changed = true; 8865 } 8866 8867 // If we're comparing an addrec with a value which is loop-invariant in the 8868 // addrec's loop, put the addrec on the left. Also make a dominance check, 8869 // as both operands could be addrecs loop-invariant in each other's loop. 8870 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8871 const Loop *L = AR->getLoop(); 8872 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8873 std::swap(LHS, RHS); 8874 Pred = ICmpInst::getSwappedPredicate(Pred); 8875 Changed = true; 8876 } 8877 } 8878 8879 // If there's a constant operand, canonicalize comparisons with boundary 8880 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8881 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8882 const APInt &RA = RC->getAPInt(); 8883 8884 bool SimplifiedByConstantRange = false; 8885 8886 if (!ICmpInst::isEquality(Pred)) { 8887 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8888 if (ExactCR.isFullSet()) 8889 return TrivialCase(true); 8890 else if (ExactCR.isEmptySet()) 8891 return TrivialCase(false); 8892 8893 APInt NewRHS; 8894 CmpInst::Predicate NewPred; 8895 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8896 ICmpInst::isEquality(NewPred)) { 8897 // We were able to convert an inequality to an equality. 8898 Pred = NewPred; 8899 RHS = getConstant(NewRHS); 8900 Changed = SimplifiedByConstantRange = true; 8901 } 8902 } 8903 8904 if (!SimplifiedByConstantRange) { 8905 switch (Pred) { 8906 default: 8907 break; 8908 case ICmpInst::ICMP_EQ: 8909 case ICmpInst::ICMP_NE: 8910 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8911 if (!RA) 8912 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8913 if (const SCEVMulExpr *ME = 8914 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8915 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8916 ME->getOperand(0)->isAllOnesValue()) { 8917 RHS = AE->getOperand(1); 8918 LHS = ME->getOperand(1); 8919 Changed = true; 8920 } 8921 break; 8922 8923 8924 // The "Should have been caught earlier!" messages refer to the fact 8925 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8926 // should have fired on the corresponding cases, and canonicalized the 8927 // check to trivial case. 8928 8929 case ICmpInst::ICMP_UGE: 8930 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8931 Pred = ICmpInst::ICMP_UGT; 8932 RHS = getConstant(RA - 1); 8933 Changed = true; 8934 break; 8935 case ICmpInst::ICMP_ULE: 8936 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8937 Pred = ICmpInst::ICMP_ULT; 8938 RHS = getConstant(RA + 1); 8939 Changed = true; 8940 break; 8941 case ICmpInst::ICMP_SGE: 8942 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8943 Pred = ICmpInst::ICMP_SGT; 8944 RHS = getConstant(RA - 1); 8945 Changed = true; 8946 break; 8947 case ICmpInst::ICMP_SLE: 8948 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8949 Pred = ICmpInst::ICMP_SLT; 8950 RHS = getConstant(RA + 1); 8951 Changed = true; 8952 break; 8953 } 8954 } 8955 } 8956 8957 // Check for obvious equality. 8958 if (HasSameValue(LHS, RHS)) { 8959 if (ICmpInst::isTrueWhenEqual(Pred)) 8960 return TrivialCase(true); 8961 if (ICmpInst::isFalseWhenEqual(Pred)) 8962 return TrivialCase(false); 8963 } 8964 8965 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8966 // adding or subtracting 1 from one of the operands. 8967 switch (Pred) { 8968 case ICmpInst::ICMP_SLE: 8969 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8970 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8971 SCEV::FlagNSW); 8972 Pred = ICmpInst::ICMP_SLT; 8973 Changed = true; 8974 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8975 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8976 SCEV::FlagNSW); 8977 Pred = ICmpInst::ICMP_SLT; 8978 Changed = true; 8979 } 8980 break; 8981 case ICmpInst::ICMP_SGE: 8982 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8983 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8984 SCEV::FlagNSW); 8985 Pred = ICmpInst::ICMP_SGT; 8986 Changed = true; 8987 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8988 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8989 SCEV::FlagNSW); 8990 Pred = ICmpInst::ICMP_SGT; 8991 Changed = true; 8992 } 8993 break; 8994 case ICmpInst::ICMP_ULE: 8995 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8996 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8997 SCEV::FlagNUW); 8998 Pred = ICmpInst::ICMP_ULT; 8999 Changed = true; 9000 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9001 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9002 Pred = ICmpInst::ICMP_ULT; 9003 Changed = true; 9004 } 9005 break; 9006 case ICmpInst::ICMP_UGE: 9007 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9008 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9009 Pred = ICmpInst::ICMP_UGT; 9010 Changed = true; 9011 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9012 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9013 SCEV::FlagNUW); 9014 Pred = ICmpInst::ICMP_UGT; 9015 Changed = true; 9016 } 9017 break; 9018 default: 9019 break; 9020 } 9021 9022 // TODO: More simplifications are possible here. 9023 9024 // Recursively simplify until we either hit a recursion limit or nothing 9025 // changes. 9026 if (Changed) 9027 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9028 9029 return Changed; 9030 } 9031 9032 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9033 return getSignedRangeMax(S).isNegative(); 9034 } 9035 9036 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9037 return getSignedRangeMin(S).isStrictlyPositive(); 9038 } 9039 9040 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9041 return !getSignedRangeMin(S).isNegative(); 9042 } 9043 9044 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9045 return !getSignedRangeMax(S).isStrictlyPositive(); 9046 } 9047 9048 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9049 return isKnownNegative(S) || isKnownPositive(S); 9050 } 9051 9052 std::pair<const SCEV *, const SCEV *> 9053 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9054 // Compute SCEV on entry of loop L. 9055 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9056 if (Start == getCouldNotCompute()) 9057 return { Start, Start }; 9058 // Compute post increment SCEV for loop L. 9059 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9060 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9061 return { Start, PostInc }; 9062 } 9063 9064 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9065 const SCEV *LHS, const SCEV *RHS) { 9066 // First collect all loops. 9067 SmallPtrSet<const Loop *, 8> LoopsUsed; 9068 getUsedLoops(LHS, LoopsUsed); 9069 getUsedLoops(RHS, LoopsUsed); 9070 9071 if (LoopsUsed.empty()) 9072 return false; 9073 9074 // Domination relationship must be a linear order on collected loops. 9075 #ifndef NDEBUG 9076 for (auto *L1 : LoopsUsed) 9077 for (auto *L2 : LoopsUsed) 9078 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9079 DT.dominates(L2->getHeader(), L1->getHeader())) && 9080 "Domination relationship is not a linear order"); 9081 #endif 9082 9083 const Loop *MDL = 9084 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9085 [&](const Loop *L1, const Loop *L2) { 9086 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9087 }); 9088 9089 // Get init and post increment value for LHS. 9090 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9091 // if LHS contains unknown non-invariant SCEV then bail out. 9092 if (SplitLHS.first == getCouldNotCompute()) 9093 return false; 9094 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9095 // Get init and post increment value for RHS. 9096 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9097 // if RHS contains unknown non-invariant SCEV then bail out. 9098 if (SplitRHS.first == getCouldNotCompute()) 9099 return false; 9100 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9101 // It is possible that init SCEV contains an invariant load but it does 9102 // not dominate MDL and is not available at MDL loop entry, so we should 9103 // check it here. 9104 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9105 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9106 return false; 9107 9108 // It seems backedge guard check is faster than entry one so in some cases 9109 // it can speed up whole estimation by short circuit 9110 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9111 SplitRHS.second) && 9112 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9113 } 9114 9115 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9116 const SCEV *LHS, const SCEV *RHS) { 9117 // Canonicalize the inputs first. 9118 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9119 9120 if (isKnownViaInduction(Pred, LHS, RHS)) 9121 return true; 9122 9123 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9124 return true; 9125 9126 // Otherwise see what can be done with some simple reasoning. 9127 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9128 } 9129 9130 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9131 const SCEV *LHS, const SCEV *RHS, 9132 const Instruction *Context) { 9133 // TODO: Analyze guards and assumes from Context's block. 9134 return isKnownPredicate(Pred, LHS, RHS) || 9135 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9136 } 9137 9138 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9139 const SCEVAddRecExpr *LHS, 9140 const SCEV *RHS) { 9141 const Loop *L = LHS->getLoop(); 9142 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9143 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9144 } 9145 9146 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9147 ICmpInst::Predicate Pred, 9148 bool &Increasing) { 9149 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9150 9151 #ifndef NDEBUG 9152 // Verify an invariant: inverting the predicate should turn a monotonically 9153 // increasing change to a monotonically decreasing one, and vice versa. 9154 bool IncreasingSwapped; 9155 bool ResultSwapped = isMonotonicPredicateImpl( 9156 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9157 9158 assert(Result == ResultSwapped && "should be able to analyze both!"); 9159 if (ResultSwapped) 9160 assert(Increasing == !IncreasingSwapped && 9161 "monotonicity should flip as we flip the predicate"); 9162 #endif 9163 9164 return Result; 9165 } 9166 9167 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9168 ICmpInst::Predicate Pred, 9169 bool &Increasing) { 9170 9171 // A zero step value for LHS means the induction variable is essentially a 9172 // loop invariant value. We don't really depend on the predicate actually 9173 // flipping from false to true (for increasing predicates, and the other way 9174 // around for decreasing predicates), all we care about is that *if* the 9175 // predicate changes then it only changes from false to true. 9176 // 9177 // A zero step value in itself is not very useful, but there may be places 9178 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9179 // as general as possible. 9180 9181 switch (Pred) { 9182 default: 9183 return false; // Conservative answer 9184 9185 case ICmpInst::ICMP_UGT: 9186 case ICmpInst::ICMP_UGE: 9187 case ICmpInst::ICMP_ULT: 9188 case ICmpInst::ICMP_ULE: 9189 if (!LHS->hasNoUnsignedWrap()) 9190 return false; 9191 9192 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9193 return true; 9194 9195 case ICmpInst::ICMP_SGT: 9196 case ICmpInst::ICMP_SGE: 9197 case ICmpInst::ICMP_SLT: 9198 case ICmpInst::ICMP_SLE: { 9199 if (!LHS->hasNoSignedWrap()) 9200 return false; 9201 9202 const SCEV *Step = LHS->getStepRecurrence(*this); 9203 9204 if (isKnownNonNegative(Step)) { 9205 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9206 return true; 9207 } 9208 9209 if (isKnownNonPositive(Step)) { 9210 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9211 return true; 9212 } 9213 9214 return false; 9215 } 9216 9217 } 9218 9219 llvm_unreachable("switch has default clause!"); 9220 } 9221 9222 bool ScalarEvolution::isLoopInvariantPredicate( 9223 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9224 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9225 const SCEV *&InvariantRHS) { 9226 9227 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9228 if (!isLoopInvariant(RHS, L)) { 9229 if (!isLoopInvariant(LHS, L)) 9230 return false; 9231 9232 std::swap(LHS, RHS); 9233 Pred = ICmpInst::getSwappedPredicate(Pred); 9234 } 9235 9236 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9237 if (!ArLHS || ArLHS->getLoop() != L) 9238 return false; 9239 9240 bool Increasing; 9241 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9242 return false; 9243 9244 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9245 // true as the loop iterates, and the backedge is control dependent on 9246 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9247 // 9248 // * if the predicate was false in the first iteration then the predicate 9249 // is never evaluated again, since the loop exits without taking the 9250 // backedge. 9251 // * if the predicate was true in the first iteration then it will 9252 // continue to be true for all future iterations since it is 9253 // monotonically increasing. 9254 // 9255 // For both the above possibilities, we can replace the loop varying 9256 // predicate with its value on the first iteration of the loop (which is 9257 // loop invariant). 9258 // 9259 // A similar reasoning applies for a monotonically decreasing predicate, by 9260 // replacing true with false and false with true in the above two bullets. 9261 9262 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9263 9264 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9265 return false; 9266 9267 InvariantPred = Pred; 9268 InvariantLHS = ArLHS->getStart(); 9269 InvariantRHS = RHS; 9270 return true; 9271 } 9272 9273 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9274 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9275 if (HasSameValue(LHS, RHS)) 9276 return ICmpInst::isTrueWhenEqual(Pred); 9277 9278 // This code is split out from isKnownPredicate because it is called from 9279 // within isLoopEntryGuardedByCond. 9280 9281 auto CheckRanges = 9282 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9283 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9284 .contains(RangeLHS); 9285 }; 9286 9287 // The check at the top of the function catches the case where the values are 9288 // known to be equal. 9289 if (Pred == CmpInst::ICMP_EQ) 9290 return false; 9291 9292 if (Pred == CmpInst::ICMP_NE) 9293 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9294 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9295 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9296 9297 if (CmpInst::isSigned(Pred)) 9298 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9299 9300 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9301 } 9302 9303 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9304 const SCEV *LHS, 9305 const SCEV *RHS) { 9306 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9307 // Return Y via OutY. 9308 auto MatchBinaryAddToConst = 9309 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9310 SCEV::NoWrapFlags ExpectedFlags) { 9311 const SCEV *NonConstOp, *ConstOp; 9312 SCEV::NoWrapFlags FlagsPresent; 9313 9314 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9315 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9316 return false; 9317 9318 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9319 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9320 }; 9321 9322 APInt C; 9323 9324 switch (Pred) { 9325 default: 9326 break; 9327 9328 case ICmpInst::ICMP_SGE: 9329 std::swap(LHS, RHS); 9330 LLVM_FALLTHROUGH; 9331 case ICmpInst::ICMP_SLE: 9332 // X s<= (X + C)<nsw> if C >= 0 9333 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9334 return true; 9335 9336 // (X + C)<nsw> s<= X if C <= 0 9337 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9338 !C.isStrictlyPositive()) 9339 return true; 9340 break; 9341 9342 case ICmpInst::ICMP_SGT: 9343 std::swap(LHS, RHS); 9344 LLVM_FALLTHROUGH; 9345 case ICmpInst::ICMP_SLT: 9346 // X s< (X + C)<nsw> if C > 0 9347 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9348 C.isStrictlyPositive()) 9349 return true; 9350 9351 // (X + C)<nsw> s< X if C < 0 9352 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9353 return true; 9354 break; 9355 9356 case ICmpInst::ICMP_UGE: 9357 std::swap(LHS, RHS); 9358 LLVM_FALLTHROUGH; 9359 case ICmpInst::ICMP_ULE: 9360 // X u<= (X + C)<nuw> for any C 9361 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9362 return true; 9363 break; 9364 9365 case ICmpInst::ICMP_UGT: 9366 std::swap(LHS, RHS); 9367 LLVM_FALLTHROUGH; 9368 case ICmpInst::ICMP_ULT: 9369 // X u< (X + C)<nuw> if C != 0 9370 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9371 return true; 9372 break; 9373 } 9374 9375 return false; 9376 } 9377 9378 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9379 const SCEV *LHS, 9380 const SCEV *RHS) { 9381 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9382 return false; 9383 9384 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9385 // the stack can result in exponential time complexity. 9386 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9387 9388 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9389 // 9390 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9391 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9392 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9393 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9394 // use isKnownPredicate later if needed. 9395 return isKnownNonNegative(RHS) && 9396 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9397 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9398 } 9399 9400 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9401 ICmpInst::Predicate Pred, 9402 const SCEV *LHS, const SCEV *RHS) { 9403 // No need to even try if we know the module has no guards. 9404 if (!HasGuards) 9405 return false; 9406 9407 return any_of(*BB, [&](const Instruction &I) { 9408 using namespace llvm::PatternMatch; 9409 9410 Value *Condition; 9411 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9412 m_Value(Condition))) && 9413 isImpliedCond(Pred, LHS, RHS, Condition, false); 9414 }); 9415 } 9416 9417 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9418 /// protected by a conditional between LHS and RHS. This is used to 9419 /// to eliminate casts. 9420 bool 9421 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9422 ICmpInst::Predicate Pred, 9423 const SCEV *LHS, const SCEV *RHS) { 9424 // Interpret a null as meaning no loop, where there is obviously no guard 9425 // (interprocedural conditions notwithstanding). 9426 if (!L) return true; 9427 9428 if (VerifyIR) 9429 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9430 "This cannot be done on broken IR!"); 9431 9432 9433 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9434 return true; 9435 9436 BasicBlock *Latch = L->getLoopLatch(); 9437 if (!Latch) 9438 return false; 9439 9440 BranchInst *LoopContinuePredicate = 9441 dyn_cast<BranchInst>(Latch->getTerminator()); 9442 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9443 isImpliedCond(Pred, LHS, RHS, 9444 LoopContinuePredicate->getCondition(), 9445 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9446 return true; 9447 9448 // We don't want more than one activation of the following loops on the stack 9449 // -- that can lead to O(n!) time complexity. 9450 if (WalkingBEDominatingConds) 9451 return false; 9452 9453 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9454 9455 // See if we can exploit a trip count to prove the predicate. 9456 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9457 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9458 if (LatchBECount != getCouldNotCompute()) { 9459 // We know that Latch branches back to the loop header exactly 9460 // LatchBECount times. This means the backdege condition at Latch is 9461 // equivalent to "{0,+,1} u< LatchBECount". 9462 Type *Ty = LatchBECount->getType(); 9463 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9464 const SCEV *LoopCounter = 9465 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9466 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9467 LatchBECount)) 9468 return true; 9469 } 9470 9471 // Check conditions due to any @llvm.assume intrinsics. 9472 for (auto &AssumeVH : AC.assumptions()) { 9473 if (!AssumeVH) 9474 continue; 9475 auto *CI = cast<CallInst>(AssumeVH); 9476 if (!DT.dominates(CI, Latch->getTerminator())) 9477 continue; 9478 9479 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9480 return true; 9481 } 9482 9483 // If the loop is not reachable from the entry block, we risk running into an 9484 // infinite loop as we walk up into the dom tree. These loops do not matter 9485 // anyway, so we just return a conservative answer when we see them. 9486 if (!DT.isReachableFromEntry(L->getHeader())) 9487 return false; 9488 9489 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9490 return true; 9491 9492 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9493 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9494 assert(DTN && "should reach the loop header before reaching the root!"); 9495 9496 BasicBlock *BB = DTN->getBlock(); 9497 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9498 return true; 9499 9500 BasicBlock *PBB = BB->getSinglePredecessor(); 9501 if (!PBB) 9502 continue; 9503 9504 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9505 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9506 continue; 9507 9508 Value *Condition = ContinuePredicate->getCondition(); 9509 9510 // If we have an edge `E` within the loop body that dominates the only 9511 // latch, the condition guarding `E` also guards the backedge. This 9512 // reasoning works only for loops with a single latch. 9513 9514 BasicBlockEdge DominatingEdge(PBB, BB); 9515 if (DominatingEdge.isSingleEdge()) { 9516 // We're constructively (and conservatively) enumerating edges within the 9517 // loop body that dominate the latch. The dominator tree better agree 9518 // with us on this: 9519 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9520 9521 if (isImpliedCond(Pred, LHS, RHS, Condition, 9522 BB != ContinuePredicate->getSuccessor(0))) 9523 return true; 9524 } 9525 } 9526 9527 return false; 9528 } 9529 9530 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9531 ICmpInst::Predicate Pred, 9532 const SCEV *LHS, 9533 const SCEV *RHS) { 9534 if (VerifyIR) 9535 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9536 "This cannot be done on broken IR!"); 9537 9538 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9539 return true; 9540 9541 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9542 // the facts (a >= b && a != b) separately. A typical situation is when the 9543 // non-strict comparison is known from ranges and non-equality is known from 9544 // dominating predicates. If we are proving strict comparison, we always try 9545 // to prove non-equality and non-strict comparison separately. 9546 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9547 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9548 bool ProvedNonStrictComparison = false; 9549 bool ProvedNonEquality = false; 9550 9551 if (ProvingStrictComparison) { 9552 ProvedNonStrictComparison = 9553 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9554 ProvedNonEquality = 9555 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9556 if (ProvedNonStrictComparison && ProvedNonEquality) 9557 return true; 9558 } 9559 9560 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9561 auto ProveViaGuard = [&](const BasicBlock *Block) { 9562 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9563 return true; 9564 if (ProvingStrictComparison) { 9565 if (!ProvedNonStrictComparison) 9566 ProvedNonStrictComparison = 9567 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9568 if (!ProvedNonEquality) 9569 ProvedNonEquality = 9570 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9571 if (ProvedNonStrictComparison && ProvedNonEquality) 9572 return true; 9573 } 9574 return false; 9575 }; 9576 9577 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9578 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9579 const Instruction *Context = &BB->front(); 9580 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9581 return true; 9582 if (ProvingStrictComparison) { 9583 if (!ProvedNonStrictComparison) 9584 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9585 Condition, Inverse, Context); 9586 if (!ProvedNonEquality) 9587 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9588 Condition, Inverse, Context); 9589 if (ProvedNonStrictComparison && ProvedNonEquality) 9590 return true; 9591 } 9592 return false; 9593 }; 9594 9595 // Starting at the block's predecessor, climb up the predecessor chain, as long 9596 // as there are predecessors that can be found that have unique successors 9597 // leading to the original block. 9598 const Loop *ContainingLoop = LI.getLoopFor(BB); 9599 const BasicBlock *PredBB; 9600 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9601 PredBB = ContainingLoop->getLoopPredecessor(); 9602 else 9603 PredBB = BB->getSinglePredecessor(); 9604 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9605 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9606 if (ProveViaGuard(Pair.first)) 9607 return true; 9608 9609 const BranchInst *LoopEntryPredicate = 9610 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9611 if (!LoopEntryPredicate || 9612 LoopEntryPredicate->isUnconditional()) 9613 continue; 9614 9615 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9616 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9617 return true; 9618 } 9619 9620 // Check conditions due to any @llvm.assume intrinsics. 9621 for (auto &AssumeVH : AC.assumptions()) { 9622 if (!AssumeVH) 9623 continue; 9624 auto *CI = cast<CallInst>(AssumeVH); 9625 if (!DT.dominates(CI, BB)) 9626 continue; 9627 9628 if (ProveViaCond(CI->getArgOperand(0), false)) 9629 return true; 9630 } 9631 9632 return false; 9633 } 9634 9635 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9636 ICmpInst::Predicate Pred, 9637 const SCEV *LHS, 9638 const SCEV *RHS) { 9639 // Interpret a null as meaning no loop, where there is obviously no guard 9640 // (interprocedural conditions notwithstanding). 9641 if (!L) 9642 return false; 9643 9644 // Both LHS and RHS must be available at loop entry. 9645 assert(isAvailableAtLoopEntry(LHS, L) && 9646 "LHS is not available at Loop Entry"); 9647 assert(isAvailableAtLoopEntry(RHS, L) && 9648 "RHS is not available at Loop Entry"); 9649 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 9650 } 9651 9652 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9653 const SCEV *RHS, 9654 const Value *FoundCondValue, bool Inverse, 9655 const Instruction *Context) { 9656 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9657 return false; 9658 9659 auto ClearOnExit = 9660 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9661 9662 // Recursively handle And and Or conditions. 9663 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9664 if (BO->getOpcode() == Instruction::And) { 9665 if (!Inverse) 9666 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9667 Context) || 9668 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9669 Context); 9670 } else if (BO->getOpcode() == Instruction::Or) { 9671 if (Inverse) 9672 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9673 Context) || 9674 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9675 Context); 9676 } 9677 } 9678 9679 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9680 if (!ICI) return false; 9681 9682 // Now that we found a conditional branch that dominates the loop or controls 9683 // the loop latch. Check to see if it is the comparison we are looking for. 9684 ICmpInst::Predicate FoundPred; 9685 if (Inverse) 9686 FoundPred = ICI->getInversePredicate(); 9687 else 9688 FoundPred = ICI->getPredicate(); 9689 9690 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9691 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9692 9693 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 9694 } 9695 9696 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9697 const SCEV *RHS, 9698 ICmpInst::Predicate FoundPred, 9699 const SCEV *FoundLHS, const SCEV *FoundRHS, 9700 const Instruction *Context) { 9701 // Balance the types. 9702 if (getTypeSizeInBits(LHS->getType()) < 9703 getTypeSizeInBits(FoundLHS->getType())) { 9704 if (CmpInst::isSigned(Pred)) { 9705 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9706 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9707 } else { 9708 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9709 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9710 } 9711 } else if (getTypeSizeInBits(LHS->getType()) > 9712 getTypeSizeInBits(FoundLHS->getType())) { 9713 if (CmpInst::isSigned(FoundPred)) { 9714 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9715 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9716 } else { 9717 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9718 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9719 } 9720 } 9721 9722 // Canonicalize the query to match the way instcombine will have 9723 // canonicalized the comparison. 9724 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9725 if (LHS == RHS) 9726 return CmpInst::isTrueWhenEqual(Pred); 9727 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9728 if (FoundLHS == FoundRHS) 9729 return CmpInst::isFalseWhenEqual(FoundPred); 9730 9731 // Check to see if we can make the LHS or RHS match. 9732 if (LHS == FoundRHS || RHS == FoundLHS) { 9733 if (isa<SCEVConstant>(RHS)) { 9734 std::swap(FoundLHS, FoundRHS); 9735 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9736 } else { 9737 std::swap(LHS, RHS); 9738 Pred = ICmpInst::getSwappedPredicate(Pred); 9739 } 9740 } 9741 9742 // Check whether the found predicate is the same as the desired predicate. 9743 if (FoundPred == Pred) 9744 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9745 9746 // Check whether swapping the found predicate makes it the same as the 9747 // desired predicate. 9748 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9749 if (isa<SCEVConstant>(RHS)) 9750 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 9751 else 9752 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 9753 LHS, FoundLHS, FoundRHS, Context); 9754 } 9755 9756 // Unsigned comparison is the same as signed comparison when both the operands 9757 // are non-negative. 9758 if (CmpInst::isUnsigned(FoundPred) && 9759 CmpInst::getSignedPredicate(FoundPred) == Pred && 9760 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9761 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9762 9763 // Check if we can make progress by sharpening ranges. 9764 if (FoundPred == ICmpInst::ICMP_NE && 9765 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9766 9767 const SCEVConstant *C = nullptr; 9768 const SCEV *V = nullptr; 9769 9770 if (isa<SCEVConstant>(FoundLHS)) { 9771 C = cast<SCEVConstant>(FoundLHS); 9772 V = FoundRHS; 9773 } else { 9774 C = cast<SCEVConstant>(FoundRHS); 9775 V = FoundLHS; 9776 } 9777 9778 // The guarding predicate tells us that C != V. If the known range 9779 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9780 // range we consider has to correspond to same signedness as the 9781 // predicate we're interested in folding. 9782 9783 APInt Min = ICmpInst::isSigned(Pred) ? 9784 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9785 9786 if (Min == C->getAPInt()) { 9787 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9788 // This is true even if (Min + 1) wraps around -- in case of 9789 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9790 9791 APInt SharperMin = Min + 1; 9792 9793 switch (Pred) { 9794 case ICmpInst::ICMP_SGE: 9795 case ICmpInst::ICMP_UGE: 9796 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9797 // RHS, we're done. 9798 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 9799 Context)) 9800 return true; 9801 LLVM_FALLTHROUGH; 9802 9803 case ICmpInst::ICMP_SGT: 9804 case ICmpInst::ICMP_UGT: 9805 // We know from the range information that (V `Pred` Min || 9806 // V == Min). We know from the guarding condition that !(V 9807 // == Min). This gives us 9808 // 9809 // V `Pred` Min || V == Min && !(V == Min) 9810 // => V `Pred` Min 9811 // 9812 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9813 9814 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 9815 Context)) 9816 return true; 9817 break; 9818 9819 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 9820 case ICmpInst::ICMP_SLE: 9821 case ICmpInst::ICMP_ULE: 9822 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9823 LHS, V, getConstant(SharperMin), Context)) 9824 return true; 9825 LLVM_FALLTHROUGH; 9826 9827 case ICmpInst::ICMP_SLT: 9828 case ICmpInst::ICMP_ULT: 9829 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9830 LHS, V, getConstant(Min), Context)) 9831 return true; 9832 break; 9833 9834 default: 9835 // No change 9836 break; 9837 } 9838 } 9839 } 9840 9841 // Check whether the actual condition is beyond sufficient. 9842 if (FoundPred == ICmpInst::ICMP_EQ) 9843 if (ICmpInst::isTrueWhenEqual(Pred)) 9844 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 9845 return true; 9846 if (Pred == ICmpInst::ICMP_NE) 9847 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9848 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 9849 Context)) 9850 return true; 9851 9852 // Otherwise assume the worst. 9853 return false; 9854 } 9855 9856 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9857 const SCEV *&L, const SCEV *&R, 9858 SCEV::NoWrapFlags &Flags) { 9859 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9860 if (!AE || AE->getNumOperands() != 2) 9861 return false; 9862 9863 L = AE->getOperand(0); 9864 R = AE->getOperand(1); 9865 Flags = AE->getNoWrapFlags(); 9866 return true; 9867 } 9868 9869 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9870 const SCEV *Less) { 9871 // We avoid subtracting expressions here because this function is usually 9872 // fairly deep in the call stack (i.e. is called many times). 9873 9874 // X - X = 0. 9875 if (More == Less) 9876 return APInt(getTypeSizeInBits(More->getType()), 0); 9877 9878 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9879 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9880 const auto *MAR = cast<SCEVAddRecExpr>(More); 9881 9882 if (LAR->getLoop() != MAR->getLoop()) 9883 return None; 9884 9885 // We look at affine expressions only; not for correctness but to keep 9886 // getStepRecurrence cheap. 9887 if (!LAR->isAffine() || !MAR->isAffine()) 9888 return None; 9889 9890 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9891 return None; 9892 9893 Less = LAR->getStart(); 9894 More = MAR->getStart(); 9895 9896 // fall through 9897 } 9898 9899 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9900 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9901 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9902 return M - L; 9903 } 9904 9905 SCEV::NoWrapFlags Flags; 9906 const SCEV *LLess = nullptr, *RLess = nullptr; 9907 const SCEV *LMore = nullptr, *RMore = nullptr; 9908 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9909 // Compare (X + C1) vs X. 9910 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9911 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9912 if (RLess == More) 9913 return -(C1->getAPInt()); 9914 9915 // Compare X vs (X + C2). 9916 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9917 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9918 if (RMore == Less) 9919 return C2->getAPInt(); 9920 9921 // Compare (X + C1) vs (X + C2). 9922 if (C1 && C2 && RLess == RMore) 9923 return C2->getAPInt() - C1->getAPInt(); 9924 9925 return None; 9926 } 9927 9928 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 9929 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9930 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 9931 // Try to recognize the following pattern: 9932 // 9933 // FoundRHS = ... 9934 // ... 9935 // loop: 9936 // FoundLHS = {Start,+,W} 9937 // context_bb: // Basic block from the same loop 9938 // known(Pred, FoundLHS, FoundRHS) 9939 // 9940 // If some predicate is known in the context of a loop, it is also known on 9941 // each iteration of this loop, including the first iteration. Therefore, in 9942 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 9943 // prove the original pred using this fact. 9944 if (!Context) 9945 return false; 9946 const BasicBlock *ContextBB = Context->getParent(); 9947 // Make sure AR varies in the context block. 9948 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 9949 const Loop *L = AR->getLoop(); 9950 // Make sure that context belongs to the loop and executes on 1st iteration 9951 // (if it ever executes at all). 9952 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9953 return false; 9954 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 9955 return false; 9956 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 9957 } 9958 9959 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 9960 const Loop *L = AR->getLoop(); 9961 // Make sure that context belongs to the loop and executes on 1st iteration 9962 // (if it ever executes at all). 9963 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9964 return false; 9965 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 9966 return false; 9967 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 9968 } 9969 9970 return false; 9971 } 9972 9973 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9974 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9975 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9976 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9977 return false; 9978 9979 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9980 if (!AddRecLHS) 9981 return false; 9982 9983 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9984 if (!AddRecFoundLHS) 9985 return false; 9986 9987 // We'd like to let SCEV reason about control dependencies, so we constrain 9988 // both the inequalities to be about add recurrences on the same loop. This 9989 // way we can use isLoopEntryGuardedByCond later. 9990 9991 const Loop *L = AddRecFoundLHS->getLoop(); 9992 if (L != AddRecLHS->getLoop()) 9993 return false; 9994 9995 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9996 // 9997 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9998 // ... (2) 9999 // 10000 // Informal proof for (2), assuming (1) [*]: 10001 // 10002 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10003 // 10004 // Then 10005 // 10006 // FoundLHS s< FoundRHS s< INT_MIN - C 10007 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10008 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10009 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10010 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10011 // <=> FoundLHS + C s< FoundRHS + C 10012 // 10013 // [*]: (1) can be proved by ruling out overflow. 10014 // 10015 // [**]: This can be proved by analyzing all the four possibilities: 10016 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10017 // (A s>= 0, B s>= 0). 10018 // 10019 // Note: 10020 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10021 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10022 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10023 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10024 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10025 // C)". 10026 10027 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10028 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10029 if (!LDiff || !RDiff || *LDiff != *RDiff) 10030 return false; 10031 10032 if (LDiff->isMinValue()) 10033 return true; 10034 10035 APInt FoundRHSLimit; 10036 10037 if (Pred == CmpInst::ICMP_ULT) { 10038 FoundRHSLimit = -(*RDiff); 10039 } else { 10040 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10041 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10042 } 10043 10044 // Try to prove (1) or (2), as needed. 10045 return isAvailableAtLoopEntry(FoundRHS, L) && 10046 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10047 getConstant(FoundRHSLimit)); 10048 } 10049 10050 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10051 const SCEV *LHS, const SCEV *RHS, 10052 const SCEV *FoundLHS, 10053 const SCEV *FoundRHS, unsigned Depth) { 10054 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10055 10056 auto ClearOnExit = make_scope_exit([&]() { 10057 if (LPhi) { 10058 bool Erased = PendingMerges.erase(LPhi); 10059 assert(Erased && "Failed to erase LPhi!"); 10060 (void)Erased; 10061 } 10062 if (RPhi) { 10063 bool Erased = PendingMerges.erase(RPhi); 10064 assert(Erased && "Failed to erase RPhi!"); 10065 (void)Erased; 10066 } 10067 }); 10068 10069 // Find respective Phis and check that they are not being pending. 10070 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10071 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10072 if (!PendingMerges.insert(Phi).second) 10073 return false; 10074 LPhi = Phi; 10075 } 10076 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10077 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10078 // If we detect a loop of Phi nodes being processed by this method, for 10079 // example: 10080 // 10081 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10082 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10083 // 10084 // we don't want to deal with a case that complex, so return conservative 10085 // answer false. 10086 if (!PendingMerges.insert(Phi).second) 10087 return false; 10088 RPhi = Phi; 10089 } 10090 10091 // If none of LHS, RHS is a Phi, nothing to do here. 10092 if (!LPhi && !RPhi) 10093 return false; 10094 10095 // If there is a SCEVUnknown Phi we are interested in, make it left. 10096 if (!LPhi) { 10097 std::swap(LHS, RHS); 10098 std::swap(FoundLHS, FoundRHS); 10099 std::swap(LPhi, RPhi); 10100 Pred = ICmpInst::getSwappedPredicate(Pred); 10101 } 10102 10103 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10104 const BasicBlock *LBB = LPhi->getParent(); 10105 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10106 10107 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10108 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10109 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10110 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10111 }; 10112 10113 if (RPhi && RPhi->getParent() == LBB) { 10114 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10115 // If we compare two Phis from the same block, and for each entry block 10116 // the predicate is true for incoming values from this block, then the 10117 // predicate is also true for the Phis. 10118 for (const BasicBlock *IncBB : predecessors(LBB)) { 10119 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10120 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10121 if (!ProvedEasily(L, R)) 10122 return false; 10123 } 10124 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10125 // Case two: RHS is also a Phi from the same basic block, and it is an 10126 // AddRec. It means that there is a loop which has both AddRec and Unknown 10127 // PHIs, for it we can compare incoming values of AddRec from above the loop 10128 // and latch with their respective incoming values of LPhi. 10129 // TODO: Generalize to handle loops with many inputs in a header. 10130 if (LPhi->getNumIncomingValues() != 2) return false; 10131 10132 auto *RLoop = RAR->getLoop(); 10133 auto *Predecessor = RLoop->getLoopPredecessor(); 10134 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10135 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10136 if (!ProvedEasily(L1, RAR->getStart())) 10137 return false; 10138 auto *Latch = RLoop->getLoopLatch(); 10139 assert(Latch && "Loop with AddRec with no latch?"); 10140 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10141 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10142 return false; 10143 } else { 10144 // In all other cases go over inputs of LHS and compare each of them to RHS, 10145 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10146 // At this point RHS is either a non-Phi, or it is a Phi from some block 10147 // different from LBB. 10148 for (const BasicBlock *IncBB : predecessors(LBB)) { 10149 // Check that RHS is available in this block. 10150 if (!dominates(RHS, IncBB)) 10151 return false; 10152 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10153 if (!ProvedEasily(L, RHS)) 10154 return false; 10155 } 10156 } 10157 return true; 10158 } 10159 10160 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10161 const SCEV *LHS, const SCEV *RHS, 10162 const SCEV *FoundLHS, 10163 const SCEV *FoundRHS, 10164 const Instruction *Context) { 10165 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10166 return true; 10167 10168 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10169 return true; 10170 10171 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10172 Context)) 10173 return true; 10174 10175 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10176 FoundLHS, FoundRHS) || 10177 // ~x < ~y --> x > y 10178 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10179 getNotSCEV(FoundRHS), 10180 getNotSCEV(FoundLHS)); 10181 } 10182 10183 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10184 template <typename MinMaxExprType> 10185 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10186 const SCEV *Candidate) { 10187 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10188 if (!MinMaxExpr) 10189 return false; 10190 10191 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10192 } 10193 10194 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10195 ICmpInst::Predicate Pred, 10196 const SCEV *LHS, const SCEV *RHS) { 10197 // If both sides are affine addrecs for the same loop, with equal 10198 // steps, and we know the recurrences don't wrap, then we only 10199 // need to check the predicate on the starting values. 10200 10201 if (!ICmpInst::isRelational(Pred)) 10202 return false; 10203 10204 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10205 if (!LAR) 10206 return false; 10207 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10208 if (!RAR) 10209 return false; 10210 if (LAR->getLoop() != RAR->getLoop()) 10211 return false; 10212 if (!LAR->isAffine() || !RAR->isAffine()) 10213 return false; 10214 10215 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10216 return false; 10217 10218 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10219 SCEV::FlagNSW : SCEV::FlagNUW; 10220 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10221 return false; 10222 10223 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10224 } 10225 10226 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10227 /// expression? 10228 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10229 ICmpInst::Predicate Pred, 10230 const SCEV *LHS, const SCEV *RHS) { 10231 switch (Pred) { 10232 default: 10233 return false; 10234 10235 case ICmpInst::ICMP_SGE: 10236 std::swap(LHS, RHS); 10237 LLVM_FALLTHROUGH; 10238 case ICmpInst::ICMP_SLE: 10239 return 10240 // min(A, ...) <= A 10241 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10242 // A <= max(A, ...) 10243 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10244 10245 case ICmpInst::ICMP_UGE: 10246 std::swap(LHS, RHS); 10247 LLVM_FALLTHROUGH; 10248 case ICmpInst::ICMP_ULE: 10249 return 10250 // min(A, ...) <= A 10251 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10252 // A <= max(A, ...) 10253 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10254 } 10255 10256 llvm_unreachable("covered switch fell through?!"); 10257 } 10258 10259 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10260 const SCEV *LHS, const SCEV *RHS, 10261 const SCEV *FoundLHS, 10262 const SCEV *FoundRHS, 10263 unsigned Depth) { 10264 assert(getTypeSizeInBits(LHS->getType()) == 10265 getTypeSizeInBits(RHS->getType()) && 10266 "LHS and RHS have different sizes?"); 10267 assert(getTypeSizeInBits(FoundLHS->getType()) == 10268 getTypeSizeInBits(FoundRHS->getType()) && 10269 "FoundLHS and FoundRHS have different sizes?"); 10270 // We want to avoid hurting the compile time with analysis of too big trees. 10271 if (Depth > MaxSCEVOperationsImplicationDepth) 10272 return false; 10273 10274 // We only want to work with GT comparison so far. 10275 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10276 Pred = CmpInst::getSwappedPredicate(Pred); 10277 std::swap(LHS, RHS); 10278 std::swap(FoundLHS, FoundRHS); 10279 } 10280 10281 // For unsigned, try to reduce it to corresponding signed comparison. 10282 if (Pred == ICmpInst::ICMP_UGT) 10283 // We can replace unsigned predicate with its signed counterpart if all 10284 // involved values are non-negative. 10285 // TODO: We could have better support for unsigned. 10286 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10287 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10288 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10289 // use this fact to prove that LHS and RHS are non-negative. 10290 const SCEV *MinusOne = getNegativeSCEV(getOne(LHS->getType())); 10291 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10292 FoundRHS) && 10293 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10294 FoundRHS)) 10295 Pred = ICmpInst::ICMP_SGT; 10296 } 10297 10298 if (Pred != ICmpInst::ICMP_SGT) 10299 return false; 10300 10301 auto GetOpFromSExt = [&](const SCEV *S) { 10302 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10303 return Ext->getOperand(); 10304 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10305 // the constant in some cases. 10306 return S; 10307 }; 10308 10309 // Acquire values from extensions. 10310 auto *OrigLHS = LHS; 10311 auto *OrigFoundLHS = FoundLHS; 10312 LHS = GetOpFromSExt(LHS); 10313 FoundLHS = GetOpFromSExt(FoundLHS); 10314 10315 // Is the SGT predicate can be proved trivially or using the found context. 10316 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10317 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10318 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10319 FoundRHS, Depth + 1); 10320 }; 10321 10322 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10323 // We want to avoid creation of any new non-constant SCEV. Since we are 10324 // going to compare the operands to RHS, we should be certain that we don't 10325 // need any size extensions for this. So let's decline all cases when the 10326 // sizes of types of LHS and RHS do not match. 10327 // TODO: Maybe try to get RHS from sext to catch more cases? 10328 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10329 return false; 10330 10331 // Should not overflow. 10332 if (!LHSAddExpr->hasNoSignedWrap()) 10333 return false; 10334 10335 auto *LL = LHSAddExpr->getOperand(0); 10336 auto *LR = LHSAddExpr->getOperand(1); 10337 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10338 10339 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10340 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10341 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10342 }; 10343 // Try to prove the following rule: 10344 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10345 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10346 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10347 return true; 10348 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10349 Value *LL, *LR; 10350 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10351 10352 using namespace llvm::PatternMatch; 10353 10354 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10355 // Rules for division. 10356 // We are going to perform some comparisons with Denominator and its 10357 // derivative expressions. In general case, creating a SCEV for it may 10358 // lead to a complex analysis of the entire graph, and in particular it 10359 // can request trip count recalculation for the same loop. This would 10360 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10361 // this, we only want to create SCEVs that are constants in this section. 10362 // So we bail if Denominator is not a constant. 10363 if (!isa<ConstantInt>(LR)) 10364 return false; 10365 10366 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10367 10368 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10369 // then a SCEV for the numerator already exists and matches with FoundLHS. 10370 auto *Numerator = getExistingSCEV(LL); 10371 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10372 return false; 10373 10374 // Make sure that the numerator matches with FoundLHS and the denominator 10375 // is positive. 10376 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10377 return false; 10378 10379 auto *DTy = Denominator->getType(); 10380 auto *FRHSTy = FoundRHS->getType(); 10381 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10382 // One of types is a pointer and another one is not. We cannot extend 10383 // them properly to a wider type, so let us just reject this case. 10384 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10385 // to avoid this check. 10386 return false; 10387 10388 // Given that: 10389 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10390 auto *WTy = getWiderType(DTy, FRHSTy); 10391 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10392 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10393 10394 // Try to prove the following rule: 10395 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10396 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10397 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10398 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10399 if (isKnownNonPositive(RHS) && 10400 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10401 return true; 10402 10403 // Try to prove the following rule: 10404 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10405 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10406 // If we divide it by Denominator > 2, then: 10407 // 1. If FoundLHS is negative, then the result is 0. 10408 // 2. If FoundLHS is non-negative, then the result is non-negative. 10409 // Anyways, the result is non-negative. 10410 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10411 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10412 if (isKnownNegative(RHS) && 10413 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10414 return true; 10415 } 10416 } 10417 10418 // If our expression contained SCEVUnknown Phis, and we split it down and now 10419 // need to prove something for them, try to prove the predicate for every 10420 // possible incoming values of those Phis. 10421 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10422 return true; 10423 10424 return false; 10425 } 10426 10427 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10428 const SCEV *LHS, const SCEV *RHS) { 10429 // zext x u<= sext x, sext x s<= zext x 10430 switch (Pred) { 10431 case ICmpInst::ICMP_SGE: 10432 std::swap(LHS, RHS); 10433 LLVM_FALLTHROUGH; 10434 case ICmpInst::ICMP_SLE: { 10435 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10436 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10437 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10438 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10439 return true; 10440 break; 10441 } 10442 case ICmpInst::ICMP_UGE: 10443 std::swap(LHS, RHS); 10444 LLVM_FALLTHROUGH; 10445 case ICmpInst::ICMP_ULE: { 10446 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10447 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10448 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10449 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10450 return true; 10451 break; 10452 } 10453 default: 10454 break; 10455 }; 10456 return false; 10457 } 10458 10459 bool 10460 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10461 const SCEV *LHS, const SCEV *RHS) { 10462 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10463 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10464 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10465 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10466 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10467 } 10468 10469 bool 10470 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10471 const SCEV *LHS, const SCEV *RHS, 10472 const SCEV *FoundLHS, 10473 const SCEV *FoundRHS) { 10474 switch (Pred) { 10475 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10476 case ICmpInst::ICMP_EQ: 10477 case ICmpInst::ICMP_NE: 10478 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10479 return true; 10480 break; 10481 case ICmpInst::ICMP_SLT: 10482 case ICmpInst::ICMP_SLE: 10483 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10484 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10485 return true; 10486 break; 10487 case ICmpInst::ICMP_SGT: 10488 case ICmpInst::ICMP_SGE: 10489 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10490 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10491 return true; 10492 break; 10493 case ICmpInst::ICMP_ULT: 10494 case ICmpInst::ICMP_ULE: 10495 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10496 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10497 return true; 10498 break; 10499 case ICmpInst::ICMP_UGT: 10500 case ICmpInst::ICMP_UGE: 10501 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10502 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10503 return true; 10504 break; 10505 } 10506 10507 // Maybe it can be proved via operations? 10508 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10509 return true; 10510 10511 return false; 10512 } 10513 10514 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10515 const SCEV *LHS, 10516 const SCEV *RHS, 10517 const SCEV *FoundLHS, 10518 const SCEV *FoundRHS) { 10519 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10520 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10521 // reduce the compile time impact of this optimization. 10522 return false; 10523 10524 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10525 if (!Addend) 10526 return false; 10527 10528 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10529 10530 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10531 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10532 ConstantRange FoundLHSRange = 10533 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10534 10535 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10536 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10537 10538 // We can also compute the range of values for `LHS` that satisfy the 10539 // consequent, "`LHS` `Pred` `RHS`": 10540 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10541 ConstantRange SatisfyingLHSRange = 10542 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10543 10544 // The antecedent implies the consequent if every value of `LHS` that 10545 // satisfies the antecedent also satisfies the consequent. 10546 return SatisfyingLHSRange.contains(LHSRange); 10547 } 10548 10549 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10550 bool IsSigned, bool NoWrap) { 10551 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10552 10553 if (NoWrap) return false; 10554 10555 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10556 const SCEV *One = getOne(Stride->getType()); 10557 10558 if (IsSigned) { 10559 APInt MaxRHS = getSignedRangeMax(RHS); 10560 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10561 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10562 10563 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10564 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10565 } 10566 10567 APInt MaxRHS = getUnsignedRangeMax(RHS); 10568 APInt MaxValue = APInt::getMaxValue(BitWidth); 10569 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10570 10571 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10572 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10573 } 10574 10575 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10576 bool IsSigned, bool NoWrap) { 10577 if (NoWrap) return false; 10578 10579 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10580 const SCEV *One = getOne(Stride->getType()); 10581 10582 if (IsSigned) { 10583 APInt MinRHS = getSignedRangeMin(RHS); 10584 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10585 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10586 10587 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10588 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10589 } 10590 10591 APInt MinRHS = getUnsignedRangeMin(RHS); 10592 APInt MinValue = APInt::getMinValue(BitWidth); 10593 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10594 10595 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10596 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10597 } 10598 10599 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10600 bool Equality) { 10601 const SCEV *One = getOne(Step->getType()); 10602 Delta = Equality ? getAddExpr(Delta, Step) 10603 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10604 return getUDivExpr(Delta, Step); 10605 } 10606 10607 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10608 const SCEV *Stride, 10609 const SCEV *End, 10610 unsigned BitWidth, 10611 bool IsSigned) { 10612 10613 assert(!isKnownNonPositive(Stride) && 10614 "Stride is expected strictly positive!"); 10615 // Calculate the maximum backedge count based on the range of values 10616 // permitted by Start, End, and Stride. 10617 const SCEV *MaxBECount; 10618 APInt MinStart = 10619 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10620 10621 APInt StrideForMaxBECount = 10622 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10623 10624 // We already know that the stride is positive, so we paper over conservatism 10625 // in our range computation by forcing StrideForMaxBECount to be at least one. 10626 // In theory this is unnecessary, but we expect MaxBECount to be a 10627 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10628 // is nothing to constant fold it to). 10629 APInt One(BitWidth, 1, IsSigned); 10630 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10631 10632 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10633 : APInt::getMaxValue(BitWidth); 10634 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10635 10636 // Although End can be a MAX expression we estimate MaxEnd considering only 10637 // the case End = RHS of the loop termination condition. This is safe because 10638 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10639 // taken count. 10640 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10641 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10642 10643 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10644 getConstant(StrideForMaxBECount) /* Step */, 10645 false /* Equality */); 10646 10647 return MaxBECount; 10648 } 10649 10650 ScalarEvolution::ExitLimit 10651 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10652 const Loop *L, bool IsSigned, 10653 bool ControlsExit, bool AllowPredicates) { 10654 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10655 10656 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10657 bool PredicatedIV = false; 10658 10659 if (!IV && AllowPredicates) { 10660 // Try to make this an AddRec using runtime tests, in the first X 10661 // iterations of this loop, where X is the SCEV expression found by the 10662 // algorithm below. 10663 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10664 PredicatedIV = true; 10665 } 10666 10667 // Avoid weird loops 10668 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10669 return getCouldNotCompute(); 10670 10671 bool NoWrap = ControlsExit && 10672 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10673 10674 const SCEV *Stride = IV->getStepRecurrence(*this); 10675 10676 bool PositiveStride = isKnownPositive(Stride); 10677 10678 // Avoid negative or zero stride values. 10679 if (!PositiveStride) { 10680 // We can compute the correct backedge taken count for loops with unknown 10681 // strides if we can prove that the loop is not an infinite loop with side 10682 // effects. Here's the loop structure we are trying to handle - 10683 // 10684 // i = start 10685 // do { 10686 // A[i] = i; 10687 // i += s; 10688 // } while (i < end); 10689 // 10690 // The backedge taken count for such loops is evaluated as - 10691 // (max(end, start + stride) - start - 1) /u stride 10692 // 10693 // The additional preconditions that we need to check to prove correctness 10694 // of the above formula is as follows - 10695 // 10696 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10697 // NoWrap flag). 10698 // b) loop is single exit with no side effects. 10699 // 10700 // 10701 // Precondition a) implies that if the stride is negative, this is a single 10702 // trip loop. The backedge taken count formula reduces to zero in this case. 10703 // 10704 // Precondition b) implies that the unknown stride cannot be zero otherwise 10705 // we have UB. 10706 // 10707 // The positive stride case is the same as isKnownPositive(Stride) returning 10708 // true (original behavior of the function). 10709 // 10710 // We want to make sure that the stride is truly unknown as there are edge 10711 // cases where ScalarEvolution propagates no wrap flags to the 10712 // post-increment/decrement IV even though the increment/decrement operation 10713 // itself is wrapping. The computed backedge taken count may be wrong in 10714 // such cases. This is prevented by checking that the stride is not known to 10715 // be either positive or non-positive. For example, no wrap flags are 10716 // propagated to the post-increment IV of this loop with a trip count of 2 - 10717 // 10718 // unsigned char i; 10719 // for(i=127; i<128; i+=129) 10720 // A[i] = i; 10721 // 10722 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10723 !loopHasNoSideEffects(L)) 10724 return getCouldNotCompute(); 10725 } else if (!Stride->isOne() && 10726 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10727 // Avoid proven overflow cases: this will ensure that the backedge taken 10728 // count will not generate any unsigned overflow. Relaxed no-overflow 10729 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10730 // undefined behaviors like the case of C language. 10731 return getCouldNotCompute(); 10732 10733 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10734 : ICmpInst::ICMP_ULT; 10735 const SCEV *Start = IV->getStart(); 10736 const SCEV *End = RHS; 10737 // When the RHS is not invariant, we do not know the end bound of the loop and 10738 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10739 // calculate the MaxBECount, given the start, stride and max value for the end 10740 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10741 // checked above). 10742 if (!isLoopInvariant(RHS, L)) { 10743 const SCEV *MaxBECount = computeMaxBECountForLT( 10744 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10745 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10746 false /*MaxOrZero*/, Predicates); 10747 } 10748 // If the backedge is taken at least once, then it will be taken 10749 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10750 // is the LHS value of the less-than comparison the first time it is evaluated 10751 // and End is the RHS. 10752 const SCEV *BECountIfBackedgeTaken = 10753 computeBECount(getMinusSCEV(End, Start), Stride, false); 10754 // If the loop entry is guarded by the result of the backedge test of the 10755 // first loop iteration, then we know the backedge will be taken at least 10756 // once and so the backedge taken count is as above. If not then we use the 10757 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10758 // as if the backedge is taken at least once max(End,Start) is End and so the 10759 // result is as above, and if not max(End,Start) is Start so we get a backedge 10760 // count of zero. 10761 const SCEV *BECount; 10762 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10763 BECount = BECountIfBackedgeTaken; 10764 else { 10765 // If we know that RHS >= Start in the context of loop, then we know that 10766 // max(RHS, Start) = RHS at this point. 10767 if (isLoopEntryGuardedByCond( 10768 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 10769 End = RHS; 10770 else 10771 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10772 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10773 } 10774 10775 const SCEV *MaxBECount; 10776 bool MaxOrZero = false; 10777 if (isa<SCEVConstant>(BECount)) 10778 MaxBECount = BECount; 10779 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10780 // If we know exactly how many times the backedge will be taken if it's 10781 // taken at least once, then the backedge count will either be that or 10782 // zero. 10783 MaxBECount = BECountIfBackedgeTaken; 10784 MaxOrZero = true; 10785 } else { 10786 MaxBECount = computeMaxBECountForLT( 10787 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10788 } 10789 10790 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10791 !isa<SCEVCouldNotCompute>(BECount)) 10792 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10793 10794 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10795 } 10796 10797 ScalarEvolution::ExitLimit 10798 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10799 const Loop *L, bool IsSigned, 10800 bool ControlsExit, bool AllowPredicates) { 10801 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10802 // We handle only IV > Invariant 10803 if (!isLoopInvariant(RHS, L)) 10804 return getCouldNotCompute(); 10805 10806 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10807 if (!IV && AllowPredicates) 10808 // Try to make this an AddRec using runtime tests, in the first X 10809 // iterations of this loop, where X is the SCEV expression found by the 10810 // algorithm below. 10811 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10812 10813 // Avoid weird loops 10814 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10815 return getCouldNotCompute(); 10816 10817 bool NoWrap = ControlsExit && 10818 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10819 10820 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10821 10822 // Avoid negative or zero stride values 10823 if (!isKnownPositive(Stride)) 10824 return getCouldNotCompute(); 10825 10826 // Avoid proven overflow cases: this will ensure that the backedge taken count 10827 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10828 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10829 // behaviors like the case of C language. 10830 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10831 return getCouldNotCompute(); 10832 10833 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10834 : ICmpInst::ICMP_UGT; 10835 10836 const SCEV *Start = IV->getStart(); 10837 const SCEV *End = RHS; 10838 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 10839 // If we know that Start >= RHS in the context of loop, then we know that 10840 // min(RHS, Start) = RHS at this point. 10841 if (isLoopEntryGuardedByCond( 10842 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 10843 End = RHS; 10844 else 10845 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10846 } 10847 10848 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10849 10850 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10851 : getUnsignedRangeMax(Start); 10852 10853 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10854 : getUnsignedRangeMin(Stride); 10855 10856 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10857 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10858 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10859 10860 // Although End can be a MIN expression we estimate MinEnd considering only 10861 // the case End = RHS. This is safe because in the other case (Start - End) 10862 // is zero, leading to a zero maximum backedge taken count. 10863 APInt MinEnd = 10864 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10865 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10866 10867 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10868 ? BECount 10869 : computeBECount(getConstant(MaxStart - MinEnd), 10870 getConstant(MinStride), false); 10871 10872 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10873 MaxBECount = BECount; 10874 10875 return ExitLimit(BECount, MaxBECount, false, Predicates); 10876 } 10877 10878 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10879 ScalarEvolution &SE) const { 10880 if (Range.isFullSet()) // Infinite loop. 10881 return SE.getCouldNotCompute(); 10882 10883 // If the start is a non-zero constant, shift the range to simplify things. 10884 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10885 if (!SC->getValue()->isZero()) { 10886 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10887 Operands[0] = SE.getZero(SC->getType()); 10888 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10889 getNoWrapFlags(FlagNW)); 10890 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10891 return ShiftedAddRec->getNumIterationsInRange( 10892 Range.subtract(SC->getAPInt()), SE); 10893 // This is strange and shouldn't happen. 10894 return SE.getCouldNotCompute(); 10895 } 10896 10897 // The only time we can solve this is when we have all constant indices. 10898 // Otherwise, we cannot determine the overflow conditions. 10899 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10900 return SE.getCouldNotCompute(); 10901 10902 // Okay at this point we know that all elements of the chrec are constants and 10903 // that the start element is zero. 10904 10905 // First check to see if the range contains zero. If not, the first 10906 // iteration exits. 10907 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10908 if (!Range.contains(APInt(BitWidth, 0))) 10909 return SE.getZero(getType()); 10910 10911 if (isAffine()) { 10912 // If this is an affine expression then we have this situation: 10913 // Solve {0,+,A} in Range === Ax in Range 10914 10915 // We know that zero is in the range. If A is positive then we know that 10916 // the upper value of the range must be the first possible exit value. 10917 // If A is negative then the lower of the range is the last possible loop 10918 // value. Also note that we already checked for a full range. 10919 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10920 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10921 10922 // The exit value should be (End+A)/A. 10923 APInt ExitVal = (End + A).udiv(A); 10924 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10925 10926 // Evaluate at the exit value. If we really did fall out of the valid 10927 // range, then we computed our trip count, otherwise wrap around or other 10928 // things must have happened. 10929 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10930 if (Range.contains(Val->getValue())) 10931 return SE.getCouldNotCompute(); // Something strange happened 10932 10933 // Ensure that the previous value is in the range. This is a sanity check. 10934 assert(Range.contains( 10935 EvaluateConstantChrecAtConstant(this, 10936 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10937 "Linear scev computation is off in a bad way!"); 10938 return SE.getConstant(ExitValue); 10939 } 10940 10941 if (isQuadratic()) { 10942 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10943 return SE.getConstant(S.getValue()); 10944 } 10945 10946 return SE.getCouldNotCompute(); 10947 } 10948 10949 const SCEVAddRecExpr * 10950 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10951 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10952 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10953 // but in this case we cannot guarantee that the value returned will be an 10954 // AddRec because SCEV does not have a fixed point where it stops 10955 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10956 // may happen if we reach arithmetic depth limit while simplifying. So we 10957 // construct the returned value explicitly. 10958 SmallVector<const SCEV *, 3> Ops; 10959 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10960 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10961 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10962 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10963 // We know that the last operand is not a constant zero (otherwise it would 10964 // have been popped out earlier). This guarantees us that if the result has 10965 // the same last operand, then it will also not be popped out, meaning that 10966 // the returned value will be an AddRec. 10967 const SCEV *Last = getOperand(getNumOperands() - 1); 10968 assert(!Last->isZero() && "Recurrency with zero step?"); 10969 Ops.push_back(Last); 10970 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10971 SCEV::FlagAnyWrap)); 10972 } 10973 10974 // Return true when S contains at least an undef value. 10975 static inline bool containsUndefs(const SCEV *S) { 10976 return SCEVExprContains(S, [](const SCEV *S) { 10977 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10978 return isa<UndefValue>(SU->getValue()); 10979 return false; 10980 }); 10981 } 10982 10983 namespace { 10984 10985 // Collect all steps of SCEV expressions. 10986 struct SCEVCollectStrides { 10987 ScalarEvolution &SE; 10988 SmallVectorImpl<const SCEV *> &Strides; 10989 10990 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10991 : SE(SE), Strides(S) {} 10992 10993 bool follow(const SCEV *S) { 10994 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10995 Strides.push_back(AR->getStepRecurrence(SE)); 10996 return true; 10997 } 10998 10999 bool isDone() const { return false; } 11000 }; 11001 11002 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11003 struct SCEVCollectTerms { 11004 SmallVectorImpl<const SCEV *> &Terms; 11005 11006 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11007 11008 bool follow(const SCEV *S) { 11009 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11010 isa<SCEVSignExtendExpr>(S)) { 11011 if (!containsUndefs(S)) 11012 Terms.push_back(S); 11013 11014 // Stop recursion: once we collected a term, do not walk its operands. 11015 return false; 11016 } 11017 11018 // Keep looking. 11019 return true; 11020 } 11021 11022 bool isDone() const { return false; } 11023 }; 11024 11025 // Check if a SCEV contains an AddRecExpr. 11026 struct SCEVHasAddRec { 11027 bool &ContainsAddRec; 11028 11029 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11030 ContainsAddRec = false; 11031 } 11032 11033 bool follow(const SCEV *S) { 11034 if (isa<SCEVAddRecExpr>(S)) { 11035 ContainsAddRec = true; 11036 11037 // Stop recursion: once we collected a term, do not walk its operands. 11038 return false; 11039 } 11040 11041 // Keep looking. 11042 return true; 11043 } 11044 11045 bool isDone() const { return false; } 11046 }; 11047 11048 // Find factors that are multiplied with an expression that (possibly as a 11049 // subexpression) contains an AddRecExpr. In the expression: 11050 // 11051 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11052 // 11053 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11054 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11055 // parameters as they form a product with an induction variable. 11056 // 11057 // This collector expects all array size parameters to be in the same MulExpr. 11058 // It might be necessary to later add support for collecting parameters that are 11059 // spread over different nested MulExpr. 11060 struct SCEVCollectAddRecMultiplies { 11061 SmallVectorImpl<const SCEV *> &Terms; 11062 ScalarEvolution &SE; 11063 11064 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11065 : Terms(T), SE(SE) {} 11066 11067 bool follow(const SCEV *S) { 11068 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11069 bool HasAddRec = false; 11070 SmallVector<const SCEV *, 0> Operands; 11071 for (auto Op : Mul->operands()) { 11072 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11073 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11074 Operands.push_back(Op); 11075 } else if (Unknown) { 11076 HasAddRec = true; 11077 } else { 11078 bool ContainsAddRec = false; 11079 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11080 visitAll(Op, ContiansAddRec); 11081 HasAddRec |= ContainsAddRec; 11082 } 11083 } 11084 if (Operands.size() == 0) 11085 return true; 11086 11087 if (!HasAddRec) 11088 return false; 11089 11090 Terms.push_back(SE.getMulExpr(Operands)); 11091 // Stop recursion: once we collected a term, do not walk its operands. 11092 return false; 11093 } 11094 11095 // Keep looking. 11096 return true; 11097 } 11098 11099 bool isDone() const { return false; } 11100 }; 11101 11102 } // end anonymous namespace 11103 11104 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11105 /// two places: 11106 /// 1) The strides of AddRec expressions. 11107 /// 2) Unknowns that are multiplied with AddRec expressions. 11108 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11109 SmallVectorImpl<const SCEV *> &Terms) { 11110 SmallVector<const SCEV *, 4> Strides; 11111 SCEVCollectStrides StrideCollector(*this, Strides); 11112 visitAll(Expr, StrideCollector); 11113 11114 LLVM_DEBUG({ 11115 dbgs() << "Strides:\n"; 11116 for (const SCEV *S : Strides) 11117 dbgs() << *S << "\n"; 11118 }); 11119 11120 for (const SCEV *S : Strides) { 11121 SCEVCollectTerms TermCollector(Terms); 11122 visitAll(S, TermCollector); 11123 } 11124 11125 LLVM_DEBUG({ 11126 dbgs() << "Terms:\n"; 11127 for (const SCEV *T : Terms) 11128 dbgs() << *T << "\n"; 11129 }); 11130 11131 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11132 visitAll(Expr, MulCollector); 11133 } 11134 11135 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11136 SmallVectorImpl<const SCEV *> &Terms, 11137 SmallVectorImpl<const SCEV *> &Sizes) { 11138 int Last = Terms.size() - 1; 11139 const SCEV *Step = Terms[Last]; 11140 11141 // End of recursion. 11142 if (Last == 0) { 11143 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11144 SmallVector<const SCEV *, 2> Qs; 11145 for (const SCEV *Op : M->operands()) 11146 if (!isa<SCEVConstant>(Op)) 11147 Qs.push_back(Op); 11148 11149 Step = SE.getMulExpr(Qs); 11150 } 11151 11152 Sizes.push_back(Step); 11153 return true; 11154 } 11155 11156 for (const SCEV *&Term : Terms) { 11157 // Normalize the terms before the next call to findArrayDimensionsRec. 11158 const SCEV *Q, *R; 11159 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11160 11161 // Bail out when GCD does not evenly divide one of the terms. 11162 if (!R->isZero()) 11163 return false; 11164 11165 Term = Q; 11166 } 11167 11168 // Remove all SCEVConstants. 11169 Terms.erase( 11170 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11171 Terms.end()); 11172 11173 if (Terms.size() > 0) 11174 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11175 return false; 11176 11177 Sizes.push_back(Step); 11178 return true; 11179 } 11180 11181 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11182 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11183 for (const SCEV *T : Terms) 11184 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11185 return true; 11186 11187 return false; 11188 } 11189 11190 // Return the number of product terms in S. 11191 static inline int numberOfTerms(const SCEV *S) { 11192 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11193 return Expr->getNumOperands(); 11194 return 1; 11195 } 11196 11197 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11198 if (isa<SCEVConstant>(T)) 11199 return nullptr; 11200 11201 if (isa<SCEVUnknown>(T)) 11202 return T; 11203 11204 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11205 SmallVector<const SCEV *, 2> Factors; 11206 for (const SCEV *Op : M->operands()) 11207 if (!isa<SCEVConstant>(Op)) 11208 Factors.push_back(Op); 11209 11210 return SE.getMulExpr(Factors); 11211 } 11212 11213 return T; 11214 } 11215 11216 /// Return the size of an element read or written by Inst. 11217 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11218 Type *Ty; 11219 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11220 Ty = Store->getValueOperand()->getType(); 11221 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11222 Ty = Load->getType(); 11223 else 11224 return nullptr; 11225 11226 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11227 return getSizeOfExpr(ETy, Ty); 11228 } 11229 11230 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11231 SmallVectorImpl<const SCEV *> &Sizes, 11232 const SCEV *ElementSize) { 11233 if (Terms.size() < 1 || !ElementSize) 11234 return; 11235 11236 // Early return when Terms do not contain parameters: we do not delinearize 11237 // non parametric SCEVs. 11238 if (!containsParameters(Terms)) 11239 return; 11240 11241 LLVM_DEBUG({ 11242 dbgs() << "Terms:\n"; 11243 for (const SCEV *T : Terms) 11244 dbgs() << *T << "\n"; 11245 }); 11246 11247 // Remove duplicates. 11248 array_pod_sort(Terms.begin(), Terms.end()); 11249 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11250 11251 // Put larger terms first. 11252 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11253 return numberOfTerms(LHS) > numberOfTerms(RHS); 11254 }); 11255 11256 // Try to divide all terms by the element size. If term is not divisible by 11257 // element size, proceed with the original term. 11258 for (const SCEV *&Term : Terms) { 11259 const SCEV *Q, *R; 11260 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11261 if (!Q->isZero()) 11262 Term = Q; 11263 } 11264 11265 SmallVector<const SCEV *, 4> NewTerms; 11266 11267 // Remove constant factors. 11268 for (const SCEV *T : Terms) 11269 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11270 NewTerms.push_back(NewT); 11271 11272 LLVM_DEBUG({ 11273 dbgs() << "Terms after sorting:\n"; 11274 for (const SCEV *T : NewTerms) 11275 dbgs() << *T << "\n"; 11276 }); 11277 11278 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11279 Sizes.clear(); 11280 return; 11281 } 11282 11283 // The last element to be pushed into Sizes is the size of an element. 11284 Sizes.push_back(ElementSize); 11285 11286 LLVM_DEBUG({ 11287 dbgs() << "Sizes:\n"; 11288 for (const SCEV *S : Sizes) 11289 dbgs() << *S << "\n"; 11290 }); 11291 } 11292 11293 void ScalarEvolution::computeAccessFunctions( 11294 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11295 SmallVectorImpl<const SCEV *> &Sizes) { 11296 // Early exit in case this SCEV is not an affine multivariate function. 11297 if (Sizes.empty()) 11298 return; 11299 11300 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11301 if (!AR->isAffine()) 11302 return; 11303 11304 const SCEV *Res = Expr; 11305 int Last = Sizes.size() - 1; 11306 for (int i = Last; i >= 0; i--) { 11307 const SCEV *Q, *R; 11308 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11309 11310 LLVM_DEBUG({ 11311 dbgs() << "Res: " << *Res << "\n"; 11312 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11313 dbgs() << "Res divided by Sizes[i]:\n"; 11314 dbgs() << "Quotient: " << *Q << "\n"; 11315 dbgs() << "Remainder: " << *R << "\n"; 11316 }); 11317 11318 Res = Q; 11319 11320 // Do not record the last subscript corresponding to the size of elements in 11321 // the array. 11322 if (i == Last) { 11323 11324 // Bail out if the remainder is too complex. 11325 if (isa<SCEVAddRecExpr>(R)) { 11326 Subscripts.clear(); 11327 Sizes.clear(); 11328 return; 11329 } 11330 11331 continue; 11332 } 11333 11334 // Record the access function for the current subscript. 11335 Subscripts.push_back(R); 11336 } 11337 11338 // Also push in last position the remainder of the last division: it will be 11339 // the access function of the innermost dimension. 11340 Subscripts.push_back(Res); 11341 11342 std::reverse(Subscripts.begin(), Subscripts.end()); 11343 11344 LLVM_DEBUG({ 11345 dbgs() << "Subscripts:\n"; 11346 for (const SCEV *S : Subscripts) 11347 dbgs() << *S << "\n"; 11348 }); 11349 } 11350 11351 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11352 /// sizes of an array access. Returns the remainder of the delinearization that 11353 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11354 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11355 /// expressions in the stride and base of a SCEV corresponding to the 11356 /// computation of a GCD (greatest common divisor) of base and stride. When 11357 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11358 /// 11359 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11360 /// 11361 /// void foo(long n, long m, long o, double A[n][m][o]) { 11362 /// 11363 /// for (long i = 0; i < n; i++) 11364 /// for (long j = 0; j < m; j++) 11365 /// for (long k = 0; k < o; k++) 11366 /// A[i][j][k] = 1.0; 11367 /// } 11368 /// 11369 /// the delinearization input is the following AddRec SCEV: 11370 /// 11371 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11372 /// 11373 /// From this SCEV, we are able to say that the base offset of the access is %A 11374 /// because it appears as an offset that does not divide any of the strides in 11375 /// the loops: 11376 /// 11377 /// CHECK: Base offset: %A 11378 /// 11379 /// and then SCEV->delinearize determines the size of some of the dimensions of 11380 /// the array as these are the multiples by which the strides are happening: 11381 /// 11382 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11383 /// 11384 /// Note that the outermost dimension remains of UnknownSize because there are 11385 /// no strides that would help identifying the size of the last dimension: when 11386 /// the array has been statically allocated, one could compute the size of that 11387 /// dimension by dividing the overall size of the array by the size of the known 11388 /// dimensions: %m * %o * 8. 11389 /// 11390 /// Finally delinearize provides the access functions for the array reference 11391 /// that does correspond to A[i][j][k] of the above C testcase: 11392 /// 11393 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11394 /// 11395 /// The testcases are checking the output of a function pass: 11396 /// DelinearizationPass that walks through all loads and stores of a function 11397 /// asking for the SCEV of the memory access with respect to all enclosing 11398 /// loops, calling SCEV->delinearize on that and printing the results. 11399 void ScalarEvolution::delinearize(const SCEV *Expr, 11400 SmallVectorImpl<const SCEV *> &Subscripts, 11401 SmallVectorImpl<const SCEV *> &Sizes, 11402 const SCEV *ElementSize) { 11403 // First step: collect parametric terms. 11404 SmallVector<const SCEV *, 4> Terms; 11405 collectParametricTerms(Expr, Terms); 11406 11407 if (Terms.empty()) 11408 return; 11409 11410 // Second step: find subscript sizes. 11411 findArrayDimensions(Terms, Sizes, ElementSize); 11412 11413 if (Sizes.empty()) 11414 return; 11415 11416 // Third step: compute the access functions for each subscript. 11417 computeAccessFunctions(Expr, Subscripts, Sizes); 11418 11419 if (Subscripts.empty()) 11420 return; 11421 11422 LLVM_DEBUG({ 11423 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11424 dbgs() << "ArrayDecl[UnknownSize]"; 11425 for (const SCEV *S : Sizes) 11426 dbgs() << "[" << *S << "]"; 11427 11428 dbgs() << "\nArrayRef"; 11429 for (const SCEV *S : Subscripts) 11430 dbgs() << "[" << *S << "]"; 11431 dbgs() << "\n"; 11432 }); 11433 } 11434 11435 bool ScalarEvolution::getIndexExpressionsFromGEP( 11436 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11437 SmallVectorImpl<int> &Sizes) { 11438 assert(Subscripts.empty() && Sizes.empty() && 11439 "Expected output lists to be empty on entry to this function."); 11440 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11441 Type *Ty = GEP->getPointerOperandType(); 11442 bool DroppedFirstDim = false; 11443 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11444 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11445 if (i == 1) { 11446 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11447 Ty = PtrTy->getElementType(); 11448 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11449 Ty = ArrayTy->getElementType(); 11450 } else { 11451 Subscripts.clear(); 11452 Sizes.clear(); 11453 return false; 11454 } 11455 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11456 if (Const->getValue()->isZero()) { 11457 DroppedFirstDim = true; 11458 continue; 11459 } 11460 Subscripts.push_back(Expr); 11461 continue; 11462 } 11463 11464 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11465 if (!ArrayTy) { 11466 Subscripts.clear(); 11467 Sizes.clear(); 11468 return false; 11469 } 11470 11471 Subscripts.push_back(Expr); 11472 if (!(DroppedFirstDim && i == 2)) 11473 Sizes.push_back(ArrayTy->getNumElements()); 11474 11475 Ty = ArrayTy->getElementType(); 11476 } 11477 return !Subscripts.empty(); 11478 } 11479 11480 //===----------------------------------------------------------------------===// 11481 // SCEVCallbackVH Class Implementation 11482 //===----------------------------------------------------------------------===// 11483 11484 void ScalarEvolution::SCEVCallbackVH::deleted() { 11485 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11486 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11487 SE->ConstantEvolutionLoopExitValue.erase(PN); 11488 SE->eraseValueFromMap(getValPtr()); 11489 // this now dangles! 11490 } 11491 11492 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11493 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11494 11495 // Forget all the expressions associated with users of the old value, 11496 // so that future queries will recompute the expressions using the new 11497 // value. 11498 Value *Old = getValPtr(); 11499 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11500 SmallPtrSet<User *, 8> Visited; 11501 while (!Worklist.empty()) { 11502 User *U = Worklist.pop_back_val(); 11503 // Deleting the Old value will cause this to dangle. Postpone 11504 // that until everything else is done. 11505 if (U == Old) 11506 continue; 11507 if (!Visited.insert(U).second) 11508 continue; 11509 if (PHINode *PN = dyn_cast<PHINode>(U)) 11510 SE->ConstantEvolutionLoopExitValue.erase(PN); 11511 SE->eraseValueFromMap(U); 11512 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11513 } 11514 // Delete the Old value. 11515 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11516 SE->ConstantEvolutionLoopExitValue.erase(PN); 11517 SE->eraseValueFromMap(Old); 11518 // this now dangles! 11519 } 11520 11521 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11522 : CallbackVH(V), SE(se) {} 11523 11524 //===----------------------------------------------------------------------===// 11525 // ScalarEvolution Class Implementation 11526 //===----------------------------------------------------------------------===// 11527 11528 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11529 AssumptionCache &AC, DominatorTree &DT, 11530 LoopInfo &LI) 11531 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11532 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11533 LoopDispositions(64), BlockDispositions(64) { 11534 // To use guards for proving predicates, we need to scan every instruction in 11535 // relevant basic blocks, and not just terminators. Doing this is a waste of 11536 // time if the IR does not actually contain any calls to 11537 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11538 // 11539 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11540 // to _add_ guards to the module when there weren't any before, and wants 11541 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11542 // efficient in lieu of being smart in that rather obscure case. 11543 11544 auto *GuardDecl = F.getParent()->getFunction( 11545 Intrinsic::getName(Intrinsic::experimental_guard)); 11546 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11547 } 11548 11549 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11550 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11551 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11552 ValueExprMap(std::move(Arg.ValueExprMap)), 11553 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11554 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11555 PendingMerges(std::move(Arg.PendingMerges)), 11556 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11557 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11558 PredicatedBackedgeTakenCounts( 11559 std::move(Arg.PredicatedBackedgeTakenCounts)), 11560 ConstantEvolutionLoopExitValue( 11561 std::move(Arg.ConstantEvolutionLoopExitValue)), 11562 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11563 LoopDispositions(std::move(Arg.LoopDispositions)), 11564 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11565 BlockDispositions(std::move(Arg.BlockDispositions)), 11566 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11567 SignedRanges(std::move(Arg.SignedRanges)), 11568 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11569 UniquePreds(std::move(Arg.UniquePreds)), 11570 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11571 LoopUsers(std::move(Arg.LoopUsers)), 11572 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11573 FirstUnknown(Arg.FirstUnknown) { 11574 Arg.FirstUnknown = nullptr; 11575 } 11576 11577 ScalarEvolution::~ScalarEvolution() { 11578 // Iterate through all the SCEVUnknown instances and call their 11579 // destructors, so that they release their references to their values. 11580 for (SCEVUnknown *U = FirstUnknown; U;) { 11581 SCEVUnknown *Tmp = U; 11582 U = U->Next; 11583 Tmp->~SCEVUnknown(); 11584 } 11585 FirstUnknown = nullptr; 11586 11587 ExprValueMap.clear(); 11588 ValueExprMap.clear(); 11589 HasRecMap.clear(); 11590 11591 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11592 // that a loop had multiple computable exits. 11593 for (auto &BTCI : BackedgeTakenCounts) 11594 BTCI.second.clear(); 11595 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11596 BTCI.second.clear(); 11597 11598 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11599 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11600 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11601 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11602 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11603 } 11604 11605 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11606 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11607 } 11608 11609 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11610 const Loop *L) { 11611 // Print all inner loops first 11612 for (Loop *I : *L) 11613 PrintLoopInfo(OS, SE, I); 11614 11615 OS << "Loop "; 11616 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11617 OS << ": "; 11618 11619 SmallVector<BasicBlock *, 8> ExitingBlocks; 11620 L->getExitingBlocks(ExitingBlocks); 11621 if (ExitingBlocks.size() != 1) 11622 OS << "<multiple exits> "; 11623 11624 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11625 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11626 else 11627 OS << "Unpredictable backedge-taken count.\n"; 11628 11629 if (ExitingBlocks.size() > 1) 11630 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11631 OS << " exit count for " << ExitingBlock->getName() << ": " 11632 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11633 } 11634 11635 OS << "Loop "; 11636 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11637 OS << ": "; 11638 11639 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11640 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11641 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11642 OS << ", actual taken count either this or zero."; 11643 } else { 11644 OS << "Unpredictable max backedge-taken count. "; 11645 } 11646 11647 OS << "\n" 11648 "Loop "; 11649 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11650 OS << ": "; 11651 11652 SCEVUnionPredicate Pred; 11653 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11654 if (!isa<SCEVCouldNotCompute>(PBT)) { 11655 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11656 OS << " Predicates:\n"; 11657 Pred.print(OS, 4); 11658 } else { 11659 OS << "Unpredictable predicated backedge-taken count. "; 11660 } 11661 OS << "\n"; 11662 11663 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11664 OS << "Loop "; 11665 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11666 OS << ": "; 11667 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11668 } 11669 } 11670 11671 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11672 switch (LD) { 11673 case ScalarEvolution::LoopVariant: 11674 return "Variant"; 11675 case ScalarEvolution::LoopInvariant: 11676 return "Invariant"; 11677 case ScalarEvolution::LoopComputable: 11678 return "Computable"; 11679 } 11680 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11681 } 11682 11683 void ScalarEvolution::print(raw_ostream &OS) const { 11684 // ScalarEvolution's implementation of the print method is to print 11685 // out SCEV values of all instructions that are interesting. Doing 11686 // this potentially causes it to create new SCEV objects though, 11687 // which technically conflicts with the const qualifier. This isn't 11688 // observable from outside the class though, so casting away the 11689 // const isn't dangerous. 11690 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11691 11692 if (ClassifyExpressions) { 11693 OS << "Classifying expressions for: "; 11694 F.printAsOperand(OS, /*PrintType=*/false); 11695 OS << "\n"; 11696 for (Instruction &I : instructions(F)) 11697 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11698 OS << I << '\n'; 11699 OS << " --> "; 11700 const SCEV *SV = SE.getSCEV(&I); 11701 SV->print(OS); 11702 if (!isa<SCEVCouldNotCompute>(SV)) { 11703 OS << " U: "; 11704 SE.getUnsignedRange(SV).print(OS); 11705 OS << " S: "; 11706 SE.getSignedRange(SV).print(OS); 11707 } 11708 11709 const Loop *L = LI.getLoopFor(I.getParent()); 11710 11711 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11712 if (AtUse != SV) { 11713 OS << " --> "; 11714 AtUse->print(OS); 11715 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11716 OS << " U: "; 11717 SE.getUnsignedRange(AtUse).print(OS); 11718 OS << " S: "; 11719 SE.getSignedRange(AtUse).print(OS); 11720 } 11721 } 11722 11723 if (L) { 11724 OS << "\t\t" "Exits: "; 11725 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11726 if (!SE.isLoopInvariant(ExitValue, L)) { 11727 OS << "<<Unknown>>"; 11728 } else { 11729 OS << *ExitValue; 11730 } 11731 11732 bool First = true; 11733 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11734 if (First) { 11735 OS << "\t\t" "LoopDispositions: { "; 11736 First = false; 11737 } else { 11738 OS << ", "; 11739 } 11740 11741 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11742 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11743 } 11744 11745 for (auto *InnerL : depth_first(L)) { 11746 if (InnerL == L) 11747 continue; 11748 if (First) { 11749 OS << "\t\t" "LoopDispositions: { "; 11750 First = false; 11751 } else { 11752 OS << ", "; 11753 } 11754 11755 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11756 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11757 } 11758 11759 OS << " }"; 11760 } 11761 11762 OS << "\n"; 11763 } 11764 } 11765 11766 OS << "Determining loop execution counts for: "; 11767 F.printAsOperand(OS, /*PrintType=*/false); 11768 OS << "\n"; 11769 for (Loop *I : LI) 11770 PrintLoopInfo(OS, &SE, I); 11771 } 11772 11773 ScalarEvolution::LoopDisposition 11774 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11775 auto &Values = LoopDispositions[S]; 11776 for (auto &V : Values) { 11777 if (V.getPointer() == L) 11778 return V.getInt(); 11779 } 11780 Values.emplace_back(L, LoopVariant); 11781 LoopDisposition D = computeLoopDisposition(S, L); 11782 auto &Values2 = LoopDispositions[S]; 11783 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11784 if (V.getPointer() == L) { 11785 V.setInt(D); 11786 break; 11787 } 11788 } 11789 return D; 11790 } 11791 11792 ScalarEvolution::LoopDisposition 11793 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11794 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11795 case scConstant: 11796 return LoopInvariant; 11797 case scTruncate: 11798 case scZeroExtend: 11799 case scSignExtend: 11800 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11801 case scAddRecExpr: { 11802 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11803 11804 // If L is the addrec's loop, it's computable. 11805 if (AR->getLoop() == L) 11806 return LoopComputable; 11807 11808 // Add recurrences are never invariant in the function-body (null loop). 11809 if (!L) 11810 return LoopVariant; 11811 11812 // Everything that is not defined at loop entry is variant. 11813 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11814 return LoopVariant; 11815 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11816 " dominate the contained loop's header?"); 11817 11818 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11819 if (AR->getLoop()->contains(L)) 11820 return LoopInvariant; 11821 11822 // This recurrence is variant w.r.t. L if any of its operands 11823 // are variant. 11824 for (auto *Op : AR->operands()) 11825 if (!isLoopInvariant(Op, L)) 11826 return LoopVariant; 11827 11828 // Otherwise it's loop-invariant. 11829 return LoopInvariant; 11830 } 11831 case scAddExpr: 11832 case scMulExpr: 11833 case scUMaxExpr: 11834 case scSMaxExpr: 11835 case scUMinExpr: 11836 case scSMinExpr: { 11837 bool HasVarying = false; 11838 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11839 LoopDisposition D = getLoopDisposition(Op, L); 11840 if (D == LoopVariant) 11841 return LoopVariant; 11842 if (D == LoopComputable) 11843 HasVarying = true; 11844 } 11845 return HasVarying ? LoopComputable : LoopInvariant; 11846 } 11847 case scUDivExpr: { 11848 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11849 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11850 if (LD == LoopVariant) 11851 return LoopVariant; 11852 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11853 if (RD == LoopVariant) 11854 return LoopVariant; 11855 return (LD == LoopInvariant && RD == LoopInvariant) ? 11856 LoopInvariant : LoopComputable; 11857 } 11858 case scUnknown: 11859 // All non-instruction values are loop invariant. All instructions are loop 11860 // invariant if they are not contained in the specified loop. 11861 // Instructions are never considered invariant in the function body 11862 // (null loop) because they are defined within the "loop". 11863 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11864 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11865 return LoopInvariant; 11866 case scCouldNotCompute: 11867 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11868 } 11869 llvm_unreachable("Unknown SCEV kind!"); 11870 } 11871 11872 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11873 return getLoopDisposition(S, L) == LoopInvariant; 11874 } 11875 11876 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11877 return getLoopDisposition(S, L) == LoopComputable; 11878 } 11879 11880 ScalarEvolution::BlockDisposition 11881 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11882 auto &Values = BlockDispositions[S]; 11883 for (auto &V : Values) { 11884 if (V.getPointer() == BB) 11885 return V.getInt(); 11886 } 11887 Values.emplace_back(BB, DoesNotDominateBlock); 11888 BlockDisposition D = computeBlockDisposition(S, BB); 11889 auto &Values2 = BlockDispositions[S]; 11890 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11891 if (V.getPointer() == BB) { 11892 V.setInt(D); 11893 break; 11894 } 11895 } 11896 return D; 11897 } 11898 11899 ScalarEvolution::BlockDisposition 11900 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11901 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11902 case scConstant: 11903 return ProperlyDominatesBlock; 11904 case scTruncate: 11905 case scZeroExtend: 11906 case scSignExtend: 11907 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11908 case scAddRecExpr: { 11909 // This uses a "dominates" query instead of "properly dominates" query 11910 // to test for proper dominance too, because the instruction which 11911 // produces the addrec's value is a PHI, and a PHI effectively properly 11912 // dominates its entire containing block. 11913 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11914 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11915 return DoesNotDominateBlock; 11916 11917 // Fall through into SCEVNAryExpr handling. 11918 LLVM_FALLTHROUGH; 11919 } 11920 case scAddExpr: 11921 case scMulExpr: 11922 case scUMaxExpr: 11923 case scSMaxExpr: 11924 case scUMinExpr: 11925 case scSMinExpr: { 11926 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11927 bool Proper = true; 11928 for (const SCEV *NAryOp : NAry->operands()) { 11929 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11930 if (D == DoesNotDominateBlock) 11931 return DoesNotDominateBlock; 11932 if (D == DominatesBlock) 11933 Proper = false; 11934 } 11935 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11936 } 11937 case scUDivExpr: { 11938 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11939 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11940 BlockDisposition LD = getBlockDisposition(LHS, BB); 11941 if (LD == DoesNotDominateBlock) 11942 return DoesNotDominateBlock; 11943 BlockDisposition RD = getBlockDisposition(RHS, BB); 11944 if (RD == DoesNotDominateBlock) 11945 return DoesNotDominateBlock; 11946 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11947 ProperlyDominatesBlock : DominatesBlock; 11948 } 11949 case scUnknown: 11950 if (Instruction *I = 11951 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11952 if (I->getParent() == BB) 11953 return DominatesBlock; 11954 if (DT.properlyDominates(I->getParent(), BB)) 11955 return ProperlyDominatesBlock; 11956 return DoesNotDominateBlock; 11957 } 11958 return ProperlyDominatesBlock; 11959 case scCouldNotCompute: 11960 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11961 } 11962 llvm_unreachable("Unknown SCEV kind!"); 11963 } 11964 11965 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11966 return getBlockDisposition(S, BB) >= DominatesBlock; 11967 } 11968 11969 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11970 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11971 } 11972 11973 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11974 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11975 } 11976 11977 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11978 auto IsS = [&](const SCEV *X) { return S == X; }; 11979 auto ContainsS = [&](const SCEV *X) { 11980 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11981 }; 11982 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11983 } 11984 11985 void 11986 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11987 ValuesAtScopes.erase(S); 11988 LoopDispositions.erase(S); 11989 BlockDispositions.erase(S); 11990 UnsignedRanges.erase(S); 11991 SignedRanges.erase(S); 11992 ExprValueMap.erase(S); 11993 HasRecMap.erase(S); 11994 MinTrailingZerosCache.erase(S); 11995 11996 for (auto I = PredicatedSCEVRewrites.begin(); 11997 I != PredicatedSCEVRewrites.end();) { 11998 std::pair<const SCEV *, const Loop *> Entry = I->first; 11999 if (Entry.first == S) 12000 PredicatedSCEVRewrites.erase(I++); 12001 else 12002 ++I; 12003 } 12004 12005 auto RemoveSCEVFromBackedgeMap = 12006 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12007 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12008 BackedgeTakenInfo &BEInfo = I->second; 12009 if (BEInfo.hasOperand(S, this)) { 12010 BEInfo.clear(); 12011 Map.erase(I++); 12012 } else 12013 ++I; 12014 } 12015 }; 12016 12017 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12018 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12019 } 12020 12021 void 12022 ScalarEvolution::getUsedLoops(const SCEV *S, 12023 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12024 struct FindUsedLoops { 12025 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12026 : LoopsUsed(LoopsUsed) {} 12027 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12028 bool follow(const SCEV *S) { 12029 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12030 LoopsUsed.insert(AR->getLoop()); 12031 return true; 12032 } 12033 12034 bool isDone() const { return false; } 12035 }; 12036 12037 FindUsedLoops F(LoopsUsed); 12038 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12039 } 12040 12041 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12042 SmallPtrSet<const Loop *, 8> LoopsUsed; 12043 getUsedLoops(S, LoopsUsed); 12044 for (auto *L : LoopsUsed) 12045 LoopUsers[L].push_back(S); 12046 } 12047 12048 void ScalarEvolution::verify() const { 12049 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12050 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12051 12052 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12053 12054 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12055 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12056 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12057 12058 const SCEV *visitConstant(const SCEVConstant *Constant) { 12059 return SE.getConstant(Constant->getAPInt()); 12060 } 12061 12062 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12063 return SE.getUnknown(Expr->getValue()); 12064 } 12065 12066 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12067 return SE.getCouldNotCompute(); 12068 } 12069 }; 12070 12071 SCEVMapper SCM(SE2); 12072 12073 while (!LoopStack.empty()) { 12074 auto *L = LoopStack.pop_back_val(); 12075 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12076 12077 auto *CurBECount = SCM.visit( 12078 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12079 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12080 12081 if (CurBECount == SE2.getCouldNotCompute() || 12082 NewBECount == SE2.getCouldNotCompute()) { 12083 // NB! This situation is legal, but is very suspicious -- whatever pass 12084 // change the loop to make a trip count go from could not compute to 12085 // computable or vice-versa *should have* invalidated SCEV. However, we 12086 // choose not to assert here (for now) since we don't want false 12087 // positives. 12088 continue; 12089 } 12090 12091 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12092 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12093 // not propagate undef aggressively). This means we can (and do) fail 12094 // verification in cases where a transform makes the trip count of a loop 12095 // go from "undef" to "undef+1" (say). The transform is fine, since in 12096 // both cases the loop iterates "undef" times, but SCEV thinks we 12097 // increased the trip count of the loop by 1 incorrectly. 12098 continue; 12099 } 12100 12101 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12102 SE.getTypeSizeInBits(NewBECount->getType())) 12103 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12104 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12105 SE.getTypeSizeInBits(NewBECount->getType())) 12106 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12107 12108 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12109 12110 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12111 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12112 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12113 dbgs() << "Old: " << *CurBECount << "\n"; 12114 dbgs() << "New: " << *NewBECount << "\n"; 12115 dbgs() << "Delta: " << *Delta << "\n"; 12116 std::abort(); 12117 } 12118 } 12119 12120 // Collect all valid loops currently in LoopInfo. 12121 SmallPtrSet<Loop *, 32> ValidLoops; 12122 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12123 while (!Worklist.empty()) { 12124 Loop *L = Worklist.pop_back_val(); 12125 if (ValidLoops.contains(L)) 12126 continue; 12127 ValidLoops.insert(L); 12128 Worklist.append(L->begin(), L->end()); 12129 } 12130 // Check for SCEV expressions referencing invalid/deleted loops. 12131 for (auto &KV : ValueExprMap) { 12132 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12133 if (!AR) 12134 continue; 12135 assert(ValidLoops.contains(AR->getLoop()) && 12136 "AddRec references invalid loop"); 12137 } 12138 } 12139 12140 bool ScalarEvolution::invalidate( 12141 Function &F, const PreservedAnalyses &PA, 12142 FunctionAnalysisManager::Invalidator &Inv) { 12143 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12144 // of its dependencies is invalidated. 12145 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12146 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12147 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12148 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12149 Inv.invalidate<LoopAnalysis>(F, PA); 12150 } 12151 12152 AnalysisKey ScalarEvolutionAnalysis::Key; 12153 12154 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12155 FunctionAnalysisManager &AM) { 12156 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12157 AM.getResult<AssumptionAnalysis>(F), 12158 AM.getResult<DominatorTreeAnalysis>(F), 12159 AM.getResult<LoopAnalysis>(F)); 12160 } 12161 12162 PreservedAnalyses 12163 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12164 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12165 return PreservedAnalyses::all(); 12166 } 12167 12168 PreservedAnalyses 12169 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12170 // For compatibility with opt's -analyze feature under legacy pass manager 12171 // which was not ported to NPM. This keeps tests using 12172 // update_analyze_test_checks.py working. 12173 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12174 << F.getName() << "':\n"; 12175 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12176 return PreservedAnalyses::all(); 12177 } 12178 12179 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12180 "Scalar Evolution Analysis", false, true) 12181 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12182 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12183 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12184 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12185 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12186 "Scalar Evolution Analysis", false, true) 12187 12188 char ScalarEvolutionWrapperPass::ID = 0; 12189 12190 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12191 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12192 } 12193 12194 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12195 SE.reset(new ScalarEvolution( 12196 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12197 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12198 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12199 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12200 return false; 12201 } 12202 12203 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12204 12205 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12206 SE->print(OS); 12207 } 12208 12209 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12210 if (!VerifySCEV) 12211 return; 12212 12213 SE->verify(); 12214 } 12215 12216 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12217 AU.setPreservesAll(); 12218 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12219 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12220 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12221 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12222 } 12223 12224 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12225 const SCEV *RHS) { 12226 FoldingSetNodeID ID; 12227 assert(LHS->getType() == RHS->getType() && 12228 "Type mismatch between LHS and RHS"); 12229 // Unique this node based on the arguments 12230 ID.AddInteger(SCEVPredicate::P_Equal); 12231 ID.AddPointer(LHS); 12232 ID.AddPointer(RHS); 12233 void *IP = nullptr; 12234 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12235 return S; 12236 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12237 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12238 UniquePreds.InsertNode(Eq, IP); 12239 return Eq; 12240 } 12241 12242 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12243 const SCEVAddRecExpr *AR, 12244 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12245 FoldingSetNodeID ID; 12246 // Unique this node based on the arguments 12247 ID.AddInteger(SCEVPredicate::P_Wrap); 12248 ID.AddPointer(AR); 12249 ID.AddInteger(AddedFlags); 12250 void *IP = nullptr; 12251 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12252 return S; 12253 auto *OF = new (SCEVAllocator) 12254 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12255 UniquePreds.InsertNode(OF, IP); 12256 return OF; 12257 } 12258 12259 namespace { 12260 12261 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12262 public: 12263 12264 /// Rewrites \p S in the context of a loop L and the SCEV predication 12265 /// infrastructure. 12266 /// 12267 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12268 /// equivalences present in \p Pred. 12269 /// 12270 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12271 /// \p NewPreds such that the result will be an AddRecExpr. 12272 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12273 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12274 SCEVUnionPredicate *Pred) { 12275 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12276 return Rewriter.visit(S); 12277 } 12278 12279 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12280 if (Pred) { 12281 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12282 for (auto *Pred : ExprPreds) 12283 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12284 if (IPred->getLHS() == Expr) 12285 return IPred->getRHS(); 12286 } 12287 return convertToAddRecWithPreds(Expr); 12288 } 12289 12290 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12291 const SCEV *Operand = visit(Expr->getOperand()); 12292 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12293 if (AR && AR->getLoop() == L && AR->isAffine()) { 12294 // This couldn't be folded because the operand didn't have the nuw 12295 // flag. Add the nusw flag as an assumption that we could make. 12296 const SCEV *Step = AR->getStepRecurrence(SE); 12297 Type *Ty = Expr->getType(); 12298 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12299 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12300 SE.getSignExtendExpr(Step, Ty), L, 12301 AR->getNoWrapFlags()); 12302 } 12303 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12304 } 12305 12306 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12307 const SCEV *Operand = visit(Expr->getOperand()); 12308 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12309 if (AR && AR->getLoop() == L && AR->isAffine()) { 12310 // This couldn't be folded because the operand didn't have the nsw 12311 // flag. Add the nssw flag as an assumption that we could make. 12312 const SCEV *Step = AR->getStepRecurrence(SE); 12313 Type *Ty = Expr->getType(); 12314 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12315 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12316 SE.getSignExtendExpr(Step, Ty), L, 12317 AR->getNoWrapFlags()); 12318 } 12319 return SE.getSignExtendExpr(Operand, Expr->getType()); 12320 } 12321 12322 private: 12323 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12324 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12325 SCEVUnionPredicate *Pred) 12326 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12327 12328 bool addOverflowAssumption(const SCEVPredicate *P) { 12329 if (!NewPreds) { 12330 // Check if we've already made this assumption. 12331 return Pred && Pred->implies(P); 12332 } 12333 NewPreds->insert(P); 12334 return true; 12335 } 12336 12337 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12338 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12339 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12340 return addOverflowAssumption(A); 12341 } 12342 12343 // If \p Expr represents a PHINode, we try to see if it can be represented 12344 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12345 // to add this predicate as a runtime overflow check, we return the AddRec. 12346 // If \p Expr does not meet these conditions (is not a PHI node, or we 12347 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12348 // return \p Expr. 12349 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12350 if (!isa<PHINode>(Expr->getValue())) 12351 return Expr; 12352 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12353 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12354 if (!PredicatedRewrite) 12355 return Expr; 12356 for (auto *P : PredicatedRewrite->second){ 12357 // Wrap predicates from outer loops are not supported. 12358 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12359 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12360 if (L != AR->getLoop()) 12361 return Expr; 12362 } 12363 if (!addOverflowAssumption(P)) 12364 return Expr; 12365 } 12366 return PredicatedRewrite->first; 12367 } 12368 12369 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12370 SCEVUnionPredicate *Pred; 12371 const Loop *L; 12372 }; 12373 12374 } // end anonymous namespace 12375 12376 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12377 SCEVUnionPredicate &Preds) { 12378 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12379 } 12380 12381 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12382 const SCEV *S, const Loop *L, 12383 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12384 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12385 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12386 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12387 12388 if (!AddRec) 12389 return nullptr; 12390 12391 // Since the transformation was successful, we can now transfer the SCEV 12392 // predicates. 12393 for (auto *P : TransformPreds) 12394 Preds.insert(P); 12395 12396 return AddRec; 12397 } 12398 12399 /// SCEV predicates 12400 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12401 SCEVPredicateKind Kind) 12402 : FastID(ID), Kind(Kind) {} 12403 12404 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12405 const SCEV *LHS, const SCEV *RHS) 12406 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12407 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12408 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12409 } 12410 12411 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12412 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12413 12414 if (!Op) 12415 return false; 12416 12417 return Op->LHS == LHS && Op->RHS == RHS; 12418 } 12419 12420 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12421 12422 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12423 12424 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12425 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12426 } 12427 12428 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12429 const SCEVAddRecExpr *AR, 12430 IncrementWrapFlags Flags) 12431 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12432 12433 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12434 12435 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12436 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12437 12438 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12439 } 12440 12441 bool SCEVWrapPredicate::isAlwaysTrue() const { 12442 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12443 IncrementWrapFlags IFlags = Flags; 12444 12445 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12446 IFlags = clearFlags(IFlags, IncrementNSSW); 12447 12448 return IFlags == IncrementAnyWrap; 12449 } 12450 12451 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12452 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12453 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12454 OS << "<nusw>"; 12455 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12456 OS << "<nssw>"; 12457 OS << "\n"; 12458 } 12459 12460 SCEVWrapPredicate::IncrementWrapFlags 12461 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12462 ScalarEvolution &SE) { 12463 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12464 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12465 12466 // We can safely transfer the NSW flag as NSSW. 12467 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12468 ImpliedFlags = IncrementNSSW; 12469 12470 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12471 // If the increment is positive, the SCEV NUW flag will also imply the 12472 // WrapPredicate NUSW flag. 12473 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12474 if (Step->getValue()->getValue().isNonNegative()) 12475 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12476 } 12477 12478 return ImpliedFlags; 12479 } 12480 12481 /// Union predicates don't get cached so create a dummy set ID for it. 12482 SCEVUnionPredicate::SCEVUnionPredicate() 12483 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12484 12485 bool SCEVUnionPredicate::isAlwaysTrue() const { 12486 return all_of(Preds, 12487 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12488 } 12489 12490 ArrayRef<const SCEVPredicate *> 12491 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12492 auto I = SCEVToPreds.find(Expr); 12493 if (I == SCEVToPreds.end()) 12494 return ArrayRef<const SCEVPredicate *>(); 12495 return I->second; 12496 } 12497 12498 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12499 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12500 return all_of(Set->Preds, 12501 [this](const SCEVPredicate *I) { return this->implies(I); }); 12502 12503 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12504 if (ScevPredsIt == SCEVToPreds.end()) 12505 return false; 12506 auto &SCEVPreds = ScevPredsIt->second; 12507 12508 return any_of(SCEVPreds, 12509 [N](const SCEVPredicate *I) { return I->implies(N); }); 12510 } 12511 12512 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12513 12514 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12515 for (auto Pred : Preds) 12516 Pred->print(OS, Depth); 12517 } 12518 12519 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12520 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12521 for (auto Pred : Set->Preds) 12522 add(Pred); 12523 return; 12524 } 12525 12526 if (implies(N)) 12527 return; 12528 12529 const SCEV *Key = N->getExpr(); 12530 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12531 " associated expression!"); 12532 12533 SCEVToPreds[Key].push_back(N); 12534 Preds.push_back(N); 12535 } 12536 12537 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12538 Loop &L) 12539 : SE(SE), L(L) {} 12540 12541 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12542 const SCEV *Expr = SE.getSCEV(V); 12543 RewriteEntry &Entry = RewriteMap[Expr]; 12544 12545 // If we already have an entry and the version matches, return it. 12546 if (Entry.second && Generation == Entry.first) 12547 return Entry.second; 12548 12549 // We found an entry but it's stale. Rewrite the stale entry 12550 // according to the current predicate. 12551 if (Entry.second) 12552 Expr = Entry.second; 12553 12554 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12555 Entry = {Generation, NewSCEV}; 12556 12557 return NewSCEV; 12558 } 12559 12560 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12561 if (!BackedgeCount) { 12562 SCEVUnionPredicate BackedgePred; 12563 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12564 addPredicate(BackedgePred); 12565 } 12566 return BackedgeCount; 12567 } 12568 12569 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12570 if (Preds.implies(&Pred)) 12571 return; 12572 Preds.add(&Pred); 12573 updateGeneration(); 12574 } 12575 12576 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12577 return Preds; 12578 } 12579 12580 void PredicatedScalarEvolution::updateGeneration() { 12581 // If the generation number wrapped recompute everything. 12582 if (++Generation == 0) { 12583 for (auto &II : RewriteMap) { 12584 const SCEV *Rewritten = II.second.second; 12585 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12586 } 12587 } 12588 } 12589 12590 void PredicatedScalarEvolution::setNoOverflow( 12591 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12592 const SCEV *Expr = getSCEV(V); 12593 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12594 12595 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12596 12597 // Clear the statically implied flags. 12598 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12599 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12600 12601 auto II = FlagsMap.insert({V, Flags}); 12602 if (!II.second) 12603 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12604 } 12605 12606 bool PredicatedScalarEvolution::hasNoOverflow( 12607 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12608 const SCEV *Expr = getSCEV(V); 12609 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12610 12611 Flags = SCEVWrapPredicate::clearFlags( 12612 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12613 12614 auto II = FlagsMap.find(V); 12615 12616 if (II != FlagsMap.end()) 12617 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12618 12619 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12620 } 12621 12622 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12623 const SCEV *Expr = this->getSCEV(V); 12624 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12625 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12626 12627 if (!New) 12628 return nullptr; 12629 12630 for (auto *P : NewPreds) 12631 Preds.add(P); 12632 12633 updateGeneration(); 12634 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12635 return New; 12636 } 12637 12638 PredicatedScalarEvolution::PredicatedScalarEvolution( 12639 const PredicatedScalarEvolution &Init) 12640 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12641 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12642 for (auto I : Init.FlagsMap) 12643 FlagsMap.insert(I); 12644 } 12645 12646 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12647 // For each block. 12648 for (auto *BB : L.getBlocks()) 12649 for (auto &I : *BB) { 12650 if (!SE.isSCEVable(I.getType())) 12651 continue; 12652 12653 auto *Expr = SE.getSCEV(&I); 12654 auto II = RewriteMap.find(Expr); 12655 12656 if (II == RewriteMap.end()) 12657 continue; 12658 12659 // Don't print things that are not interesting. 12660 if (II->second.second == Expr) 12661 continue; 12662 12663 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12664 OS.indent(Depth + 2) << *Expr << "\n"; 12665 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12666 } 12667 } 12668 12669 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12670 // arbitrary expressions. 12671 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12672 // 4, A / B becomes X / 8). 12673 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12674 const SCEV *&RHS) { 12675 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12676 if (Add == nullptr || Add->getNumOperands() != 2) 12677 return false; 12678 12679 const SCEV *A = Add->getOperand(1); 12680 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12681 12682 if (Mul == nullptr) 12683 return false; 12684 12685 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12686 // (SomeExpr + (-(SomeExpr / B) * B)). 12687 if (Expr == getURemExpr(A, B)) { 12688 LHS = A; 12689 RHS = B; 12690 return true; 12691 } 12692 return false; 12693 }; 12694 12695 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12696 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12697 return MatchURemWithDivisor(Mul->getOperand(1)) || 12698 MatchURemWithDivisor(Mul->getOperand(2)); 12699 12700 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12701 if (Mul->getNumOperands() == 2) 12702 return MatchURemWithDivisor(Mul->getOperand(1)) || 12703 MatchURemWithDivisor(Mul->getOperand(0)) || 12704 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12705 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12706 return false; 12707 } 12708 12709 const SCEV* ScalarEvolution::computeMaxBackedgeTakenCount(const Loop *L) { 12710 SmallVector<BasicBlock*, 16> ExitingBlocks; 12711 L->getExitingBlocks(ExitingBlocks); 12712 12713 // Form an expression for the maximum exit count possible for this loop. We 12714 // merge the max and exact information to approximate a version of 12715 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 12716 SmallVector<const SCEV*, 4> ExitCounts; 12717 for (BasicBlock *ExitingBB : ExitingBlocks) { 12718 const SCEV *ExitCount = getExitCount(L, ExitingBB); 12719 if (isa<SCEVCouldNotCompute>(ExitCount)) 12720 ExitCount = getExitCount(L, ExitingBB, 12721 ScalarEvolution::ConstantMaximum); 12722 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 12723 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 12724 "We should only have known counts for exiting blocks that " 12725 "dominate latch!"); 12726 ExitCounts.push_back(ExitCount); 12727 } 12728 } 12729 if (ExitCounts.empty()) 12730 return getCouldNotCompute(); 12731 return getUMinFromMismatchedTypes(ExitCounts); 12732 } 12733 12734 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 12735 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 12736 /// we cannot guarantee that the replacement is loop invariant in the loop of 12737 /// the AddRec. 12738 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 12739 ValueToSCEVMapTy ⤅ 12740 12741 public: 12742 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 12743 : SCEVRewriteVisitor(SE), Map(M) {} 12744 12745 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 12746 12747 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12748 auto I = Map.find(Expr->getValue()); 12749 if (I == Map.end()) 12750 return Expr; 12751 return I->second; 12752 } 12753 }; 12754 12755 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 12756 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 12757 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 12758 if (!isa<SCEVUnknown>(LHS)) { 12759 std::swap(LHS, RHS); 12760 Predicate = CmpInst::getSwappedPredicate(Predicate); 12761 } 12762 12763 // For now, limit to conditions that provide information about unknown 12764 // expressions. 12765 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 12766 if (!LHSUnknown) 12767 return; 12768 12769 // TODO: use information from more predicates. 12770 switch (Predicate) { 12771 case CmpInst::ICMP_ULT: { 12772 if (!containsAddRecurrence(RHS)) { 12773 const SCEV *Base = LHS; 12774 auto I = RewriteMap.find(LHSUnknown->getValue()); 12775 if (I != RewriteMap.end()) 12776 Base = I->second; 12777 12778 RewriteMap[LHSUnknown->getValue()] = 12779 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 12780 } 12781 break; 12782 } 12783 case CmpInst::ICMP_ULE: { 12784 if (!containsAddRecurrence(RHS)) { 12785 const SCEV *Base = LHS; 12786 auto I = RewriteMap.find(LHSUnknown->getValue()); 12787 if (I != RewriteMap.end()) 12788 Base = I->second; 12789 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 12790 } 12791 break; 12792 } 12793 case CmpInst::ICMP_EQ: 12794 if (isa<SCEVConstant>(RHS)) 12795 RewriteMap[LHSUnknown->getValue()] = RHS; 12796 break; 12797 case CmpInst::ICMP_NE: 12798 if (isa<SCEVConstant>(RHS) && 12799 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 12800 RewriteMap[LHSUnknown->getValue()] = 12801 getUMaxExpr(LHS, getOne(RHS->getType())); 12802 break; 12803 default: 12804 break; 12805 } 12806 }; 12807 // Starting at the loop predecessor, climb up the predecessor chain, as long 12808 // as there are predecessors that can be found that have unique successors 12809 // leading to the original header. 12810 // TODO: share this logic with isLoopEntryGuardedByCond. 12811 ValueToSCEVMapTy RewriteMap; 12812 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 12813 L->getLoopPredecessor(), L->getHeader()); 12814 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 12815 12816 const BranchInst *LoopEntryPredicate = 12817 dyn_cast<BranchInst>(Pair.first->getTerminator()); 12818 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 12819 continue; 12820 12821 // TODO: use information from more complex conditions, e.g. AND expressions. 12822 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 12823 if (!Cmp) 12824 continue; 12825 12826 auto Predicate = Cmp->getPredicate(); 12827 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 12828 Predicate = CmpInst::getInversePredicate(Predicate); 12829 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 12830 getSCEV(Cmp->getOperand(1)), RewriteMap); 12831 } 12832 12833 // Also collect information from assumptions dominating the loop. 12834 for (auto &AssumeVH : AC.assumptions()) { 12835 if (!AssumeVH) 12836 continue; 12837 auto *AssumeI = cast<CallInst>(AssumeVH); 12838 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 12839 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 12840 continue; 12841 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 12842 getSCEV(Cmp->getOperand(1)), RewriteMap); 12843 } 12844 12845 if (RewriteMap.empty()) 12846 return Expr; 12847 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 12848 return Rewriter.visit(Expr); 12849 } 12850